file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
./full_match/97/0xD013d3E87ddb6100C51814e01992C80807e4dCBc/sources/project_/contracts/staking/TokenStaker.sol
Withdraw tokens from TokenStaker.
function withdraw(uint256 pid, uint256 amount) external stakingStarted(pid) { PoolInfo storage poolInfo = _poolInfo[pid]; UserInfo storage userInfo = _userInfo[pid][msg.sender]; require(userInfo.amount >= amount, "TokenStaker: insufficient balance"); _updatePool(pid); uint256 pending = userInfo.amount * poolInfo.accSTRFPerShare / 1e12 - userInfo.rewardDebt; if (pending > 0) { _STRFLocker.lock(msg.sender, pending); } userInfo.amount = userInfo.amount - amount; userInfo.rewardDebt = userInfo.amount * poolInfo.accSTRFPerShare / 1e12; poolInfo.token.safeTransfer(address(msg.sender), amount); emit Withdraw(msg.sender, pid, amount); }
3,272,060
// SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2021 ZeroEx Intl. 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. */ pragma solidity ^0.8.13; import "../zero-ex/src/storage/LibCommonNftOrdersStorage.sol"; import "../zero-ex/src/storage/LibERC1155OrdersStorage.sol"; import "../zero-ex/src/features/libs/LibNFTOrder.sol"; import "../zero-ex/src/features/libs/LibSignature.sol"; import "../zero-ex/src/features/nft_orders/NFTOrders.sol"; import "./interfaces/IAuthenticatedProxy.sol"; import "./interfaces/IProxyRegistry.sol"; import "./interfaces/ISharedERC1155OrdersFeature.sol"; /// @dev Feature for interacting with ERC1155 orders. contract ElementERC1155OrdersFeature is ISharedERC1155OrdersFeature, NFTOrders { using LibNFTOrder for LibNFTOrder.ERC1155SellOrder; using LibNFTOrder for LibNFTOrder.ERC1155BuyOrder; using LibNFTOrder for LibNFTOrder.NFTSellOrder; using LibNFTOrder for LibNFTOrder.NFTBuyOrder; /// @dev User registry IProxyRegistry public immutable registry; constructor(IEtherToken weth, IProxyRegistry registryAddress) NFTOrders(weth) { registry = registryAddress; } /// @dev Sells an ERC1155 asset to fill the given order. /// @param buyOrder The ERC1155 buy order. /// @param signature The order signature from the maker. /// @param erc1155TokenId The ID of the ERC1155 asset being /// sold. If the given order specifies properties, /// the asset must satisfy those properties. Otherwise, /// it must equal the tokenId in the order. /// @param erc1155SellAmount The amount of the ERC1155 asset /// to sell. /// @param unwrapNativeToken If this parameter is true and the /// ERC20 token of the order is e.g. WETH, unwraps the /// token before transferring it to the taker. /// @param callbackData If this parameter is non-zero, invokes /// `zeroExERC1155OrderCallback` on `msg.sender` after /// the ERC20 tokens have been transferred to `msg.sender` /// but before transferring the ERC1155 asset to the buyer. function sellSharedERC1155( LibNFTOrder.ERC1155BuyOrder memory buyOrder, LibSignature.Signature memory signature, uint256 erc1155TokenId, uint128 erc1155SellAmount, bool unwrapNativeToken, bytes memory callbackData ) public override { _sellERC1155( buyOrder, signature, SellParams( erc1155SellAmount, erc1155TokenId, unwrapNativeToken, msg.sender, // taker msg.sender, // owner callbackData ) ); } /// @dev Buys an ERC1155 asset by filling the given order. /// @param sellOrder The ERC1155 sell order. /// @param signature The order signature. /// @param erc1155BuyAmount The amount of the ERC1155 asset /// to buy. /// @param callbackData If this parameter is non-zero, invokes /// `zeroExERC1155OrderCallback` on `msg.sender` after /// the ERC1155 asset has been transferred to `msg.sender` /// but before transferring the ERC20 tokens to the seller. /// Native tokens acquired during the callback can be used /// to fill the order. function buySharedERC1155( LibNFTOrder.ERC1155SellOrder memory sellOrder, LibSignature.Signature memory signature, address taker, uint128 erc1155BuyAmount, bytes memory callbackData ) public override payable { uint256 ethBalanceBefore = address(this).balance - msg.value; _buySharedERC1155( sellOrder, signature, BuyParams( erc1155BuyAmount, msg.value, taker, callbackData ) ); _transferEth(payable(msg.sender), address(this).balance - ethBalanceBefore); } /// @dev Buys multiple ERC1155 assets by filling the /// given orders. /// @param sellOrders The ERC1155 sell orders. /// @param signatures The order signatures. /// @param erc1155FillAmounts The amounts of the ERC1155 assets /// to buy for each order. /// @param callbackData The data (if any) to pass to the taker /// callback for each order. Refer to the `callbackData` /// parameter to for `buyERC1155`. /// @param revertIfIncomplete If true, reverts if this /// function fails to fill any individual order. /// @return successes An array of booleans corresponding to whether /// each order in `orders` was successfully filled. function batchBuySharedERC1155s( LibNFTOrder.ERC1155SellOrder[] memory sellOrders, LibSignature.Signature[] memory signatures, address[] calldata takers, uint128[] calldata erc1155FillAmounts, bytes[] memory callbackData, bool revertIfIncomplete ) public override payable returns (bool[] memory successes) { uint256 length = sellOrders.length; require( length == signatures.length && length == takers.length && length == erc1155FillAmounts.length && length == callbackData.length, "ARRAY_LENGTH_MISMATCH" ); successes = new bool[](length); uint256 ethBalanceBefore = address(this).balance - msg.value; if (revertIfIncomplete) { for (uint256 i = 0; i < length; i++) { // Will revert if _buySharedERC1155 reverts. _buySharedERC1155( sellOrders[i], signatures[i], BuyParams( erc1155FillAmounts[i], address(this).balance - ethBalanceBefore, // Remaining ETH available takers[i], callbackData[i] ) ); successes[i] = true; } } else { for (uint256 i = 0; i < length; i++) { // Delegatecall `_buySharedERC1155FromProxy` to catch swallow reverts while // preserving execution context. (successes[i], ) = _implementation.delegatecall( abi.encodeWithSelector( this._buySharedERC1155FromProxy.selector, sellOrders[i], signatures[i], BuyParams( erc1155FillAmounts[i], address(this).balance - ethBalanceBefore, // Remaining ETH available takers[i], callbackData[i] ) ) ); } } // Refund _transferEth(payable(msg.sender), address(this).balance - ethBalanceBefore); } // @Note `_buySharedERC1155FromProxy` is a external function, must call from an external Exchange Proxy, // but should not be registered in the Exchange Proxy. function _buySharedERC1155FromProxy( LibNFTOrder.ERC1155SellOrder memory sellOrder, LibSignature.Signature memory signature, BuyParams memory params ) external payable { require(_implementation != address(this)); _buySharedERC1155(sellOrder, signature, params); } // Core settlement logic for selling an ERC1155 asset. // Used by `sellSharedERC1155` and `onERC1155Received`. function _sellERC1155( LibNFTOrder.ERC1155BuyOrder memory buyOrder, LibSignature.Signature memory signature, SellParams memory params ) private { (uint256 erc20FillAmount, bytes32 orderHash) = _sellNFT( buyOrder.asNFTBuyOrder(), signature, params ); emit ERC1155BuyOrderFilled( buyOrder.maker, params.taker, (erc20FillAmount << 160) | uint160(address(buyOrder.erc20Token)), (params.tokenId << 160) | uint160(buyOrder.erc1155Token), params.sellAmount, orderHash ); } function _buySharedERC1155( LibNFTOrder.ERC1155SellOrder memory sellOrder, LibSignature.Signature memory signature, BuyParams memory params ) internal { if (params.taker == address(0)) { params.taker = msg.sender; } else { require(params.taker != address(this), "_buy1155Ex/TAKER_CANNOT_SELF"); } (uint256 erc20FillAmount, bytes32 orderHash) = _buyNFTEx( sellOrder.asNFTSellOrder(), signature, params ); emit ERC1155SellOrderFilled( sellOrder.maker, msg.sender, (erc20FillAmount << 160) | uint160(address(sellOrder.erc20Token)), (sellOrder.erc1155TokenId << 160) | uint160(sellOrder.erc1155Token), params.buyAmount, orderHash ); } /// @dev Validates that the given signature is valid for the /// given maker and order hash. Reverts if the signature /// is not valid. /// @param orderHash The hash of the order that was signed. /// @param signature The signature to check. /// @param maker The maker of the order. function _validateOrderSignature( bytes32 orderHash, LibSignature.Signature memory signature, address maker ) internal override view { if (signature.signatureType == LibSignature.SignatureType.PRESIGNED) { require( LibERC1155OrdersStorage.getStorage().orderState[orderHash].preSigned == LibCommonNftOrdersStorage.getStorage().hashNonces[maker] + 1, "PRESIGNED_INVALID_SIGNER" ); } else { require( maker != address(0) && maker == ecrecover(orderHash, signature.v, signature.r, signature.s), "INVALID_SIGNER_ERROR" ); } } /// @dev Transfers an NFT asset. /// @param token The address of the NFT contract. /// @param from The address currently holding the asset. /// @param to The address to transfer the asset to. /// @param tokenId The ID of the asset to transfer. /// @param amount The amount of the asset to transfer. function _transferNFTAssetFrom( address token, address from, address to, uint256 tokenId, uint256 amount ) internal override { /* Retrieve delegateProxy contract. */ IAuthenticatedProxy proxy = registry.proxies(from); /* Proxy must exist. */ require(address(proxy) != address(0), "!delegateProxy"); /* require implementation. */ require(proxy.implementation() == registry.delegateProxyImplementation(), "!implementation"); // 0xf242432a = keccak256(abi.encode(safeTransferFrom(address,address,uint256,uint256,bytes)) bytes memory dataToCall = abi.encodeWithSelector(0xf242432a, from, to, tokenId, amount, ""); require(proxy.proxy(token, 0, dataToCall), "!proxy call"); } /// @dev Matches a pair of complementary orders that have /// a non-negative spread. Each order is filled at /// their respective price, and the matcher receives /// a profit denominated in the ERC20 token. /// @param sellOrder Order selling an ERC1155 asset. /// @param buyOrder Order buying an ERC1155 asset. /// @param sellOrderSignature Signature for the sell order. /// @param buyOrderSignature Signature for the buy order. /// @return profit The amount of profit earned by the caller /// of this function (denominated in the ERC20 token /// of the matched orders). function matchSharedERC1155Orders( LibNFTOrder.ERC1155SellOrder memory sellOrder, LibNFTOrder.ERC1155BuyOrder memory buyOrder, LibSignature.Signature memory sellOrderSignature, LibSignature.Signature memory buyOrderSignature ) public override returns (uint256 profit) { // The ERC1155 tokens must match if (sellOrder.erc1155Token != buyOrder.erc1155Token) { revert("ERC1155_TOKEN_MISMATCH_ERROR"); } LibNFTOrder.NFTSellOrder memory sellNFTOrder = sellOrder.asNFTSellOrder(); LibNFTOrder.NFTBuyOrder memory buyNFTOrder = buyOrder.asNFTBuyOrder(); LibNFTOrder.OrderInfo memory sellOrderInfo = _getOrderInfo(sellNFTOrder); LibNFTOrder.OrderInfo memory buyOrderInfo = _getOrderInfo(buyNFTOrder); bool isEnglishAuction = (sellOrder.expiry >> 252 == 2); if (isEnglishAuction) { require( sellOrderInfo.orderAmount == sellOrderInfo.remainingAmount && sellOrderInfo.orderAmount == buyOrderInfo.orderAmount && sellOrderInfo.orderAmount == buyOrderInfo.remainingAmount, "UNMATCH_ORDER_AMOUNT" ); } _validateSellOrder( sellNFTOrder, sellOrderSignature, sellOrderInfo, buyOrder.maker ); _validateBuyOrder( buyNFTOrder, buyOrderSignature, buyOrderInfo, sellOrder.maker, sellOrder.erc1155TokenId ); // fillAmount = min(sellOrder.remainingAmount, buyOrder.remainingAmount) uint128 erc1155FillAmount = sellOrderInfo.remainingAmount < buyOrderInfo.remainingAmount ? sellOrderInfo.remainingAmount : buyOrderInfo.remainingAmount; // Reset sellOrder.erc20TokenAmount if (erc1155FillAmount != sellOrderInfo.orderAmount) { sellOrder.erc20TokenAmount = _ceilDiv( sellOrder.erc20TokenAmount * erc1155FillAmount, sellOrderInfo.orderAmount ); } // Reset buyOrder.erc20TokenAmount if (erc1155FillAmount != buyOrderInfo.orderAmount) { buyOrder.erc20TokenAmount = buyOrder.erc20TokenAmount * erc1155FillAmount / buyOrderInfo.orderAmount; } if (isEnglishAuction) { _resetEnglishAuctionTokenAmountAndFees( sellNFTOrder, buyOrder.erc20TokenAmount, erc1155FillAmount, sellOrderInfo.orderAmount ); } // Mark both orders as filled. _updateOrderState(sellNFTOrder, sellOrderInfo.orderHash, erc1155FillAmount); _updateOrderState(buyNFTOrder.asNFTSellOrder(), buyOrderInfo.orderHash, erc1155FillAmount); // The buyer must be willing to pay at least the amount that the // seller is asking. if (buyOrder.erc20TokenAmount < sellOrder.erc20TokenAmount) { revert("NEGATIVE_SPREAD_ERROR"); } // The difference in ERC20 token amounts is the spread. uint256 spread = buyOrder.erc20TokenAmount - sellOrder.erc20TokenAmount; // Transfer the ERC1155 asset from seller to buyer. _transferNFTAssetFrom( address(sellOrder.erc1155Token), sellOrder.maker, buyOrder.maker, sellOrder.erc1155TokenId, erc1155FillAmount ); // Handle the ERC20 side of the order: if ( address(sellOrder.erc20Token) == NATIVE_TOKEN_ADDRESS && buyOrder.erc20Token == WETH ) { // The sell order specifies ETH, while the buy order specifies WETH. // The orders are still compatible with one another, but we'll have // to unwrap the WETH on behalf of the buyer. // Step 1: Transfer WETH from the buyer to the EP. // Note that we transfer `buyOrder.erc20TokenAmount`, which // is the amount the buyer signaled they are willing to pay // for the ERC1155 asset, which may be more than the seller's // ask. _transferERC20TokensFrom( WETH, buyOrder.maker, address(this), buyOrder.erc20TokenAmount ); // Step 2: Unwrap the WETH into ETH. We unwrap the entire // `buyOrder.erc20TokenAmount`. // The ETH will be used for three purposes: // - To pay the seller // - To pay fees for the sell order // - Any remaining ETH will be sent to // `msg.sender` as profit. WETH.withdraw(buyOrder.erc20TokenAmount); // Step 3: Pay the seller (in ETH). _transferEth(payable(sellOrder.maker), sellOrder.erc20TokenAmount); // Step 4: Pay fees for the buy order. Note that these are paid // in _WETH_ by the _buyer_. By signing the buy order, the // buyer signals that they are willing to spend a total // of `erc20TokenAmount` _plus_ fees, all denominated in // the `erc20Token`, which in this case is WETH. _payFees( buyNFTOrder.asNFTSellOrder(), buyOrder.maker, // payer erc1155FillAmount, buyOrderInfo.orderAmount, false // useNativeToken ); // Step 5: Pay fees for the sell order. The `erc20Token` of the // sell order is ETH, so the fees are paid out in ETH. // There should be `spread` wei of ETH remaining in the // EP at this point, which we will use ETH to pay the // sell order fees. uint256 sellOrderFees = _payFees( sellNFTOrder, address(this), // payer erc1155FillAmount, sellOrderInfo.orderAmount, true // useNativeToken ); // Step 6: The spread must be enough to cover the sell order fees. // If not, either `_payFees` will have reverted, or we // have spent ETH that was in the EP before this // `matchSharedERC1155Orders` call, which we disallow. if (spread < sellOrderFees) { revert("SELL_ORDER_FEES_EXCEED_SPREAD"); } // Step 7: The spread less the sell order fees is the amount of ETH // remaining in the EP that can be sent to `msg.sender` as // the profit from matching these two orders. profit = spread - sellOrderFees; if (profit > 0) { _transferEth(payable(msg.sender), profit); } } else { // ERC20 tokens must match if (sellOrder.erc20Token != buyOrder.erc20Token) { revert("ERC20_TOKEN_MISMATCH"); } // Step 1: Transfer the ERC20 token from the buyer to the seller. // Note that we transfer `sellOrder.erc20TokenAmount`, which // is at most `buyOrder.erc20TokenAmount`. _transferERC20TokensFrom( buyOrder.erc20Token, buyOrder.maker, sellOrder.maker, sellOrder.erc20TokenAmount ); // Step 2: Pay fees for the buy order. Note that these are paid // by the buyer. By signing the buy order, the buyer signals // that they are willing to spend a total of // `buyOrder.erc20TokenAmount` _plus_ `buyOrder.fees`. _payFees( buyNFTOrder.asNFTSellOrder(), buyOrder.maker, // payer erc1155FillAmount, buyOrderInfo.orderAmount, false // useNativeToken ); // Step 3: Pay fees for the sell order. These are paid by the buyer // as well. After paying these fees, we may have taken more // from the buyer than they agreed to in the buy order. If // so, we revert in the following step. uint256 sellOrderFees = _payFees( sellNFTOrder, buyOrder.maker, // payer erc1155FillAmount, sellOrderInfo.orderAmount, false // useNativeToken ); // Step 4: The spread must be enough to cover the sell order fees. // If not, `_payFees` will have taken more tokens from the // buyer than they had agreed to in the buy order, in which // case we revert here. if (spread < sellOrderFees) { revert("SELL_ORDER_FEES_EXCEED_SPREAD"); } // Step 5: We calculate the profit as: // profit = buyOrder.erc20TokenAmount - sellOrder.erc20TokenAmount - sellOrderFees // = spread - sellOrderFees // I.e. the buyer would've been willing to pay up to `profit` // more to buy the asset, so instead that amount is sent to // `msg.sender` as the profit from matching these two orders. profit = spread - sellOrderFees; if (profit > 0) { _transferERC20TokensFrom( buyOrder.erc20Token, buyOrder.maker, msg.sender, profit ); } } _emitEventSellOrderFilled( sellOrder, buyOrder.maker, // taker erc1155FillAmount, sellOrderInfo.orderHash ); _emitEventBuyOrderFilled( buyOrder, sellOrder.maker, // taker sellOrder.erc1155TokenId, erc1155FillAmount, buyOrderInfo.orderHash ); } function _emitEventSellOrderFilled( LibNFTOrder.ERC1155SellOrder memory sellOrder, address taker, uint128 erc1155FillAmount, bytes32 orderHash ) private { emit ERC1155SellOrderFilled( sellOrder.maker, taker, (sellOrder.erc20TokenAmount << 160) | uint160(address(sellOrder.erc20Token)), (sellOrder.erc1155TokenId << 160) | uint160(sellOrder.erc1155Token), erc1155FillAmount, orderHash ); } function _emitEventBuyOrderFilled( LibNFTOrder.ERC1155BuyOrder memory buyOrder, address taker, uint256 erc1155TokenId, uint128 erc1155FillAmount, bytes32 orderHash ) private { emit ERC1155BuyOrderFilled( buyOrder.maker, taker, (buyOrder.erc20TokenAmount << 160) | uint160(address(buyOrder.erc20Token)), (erc1155TokenId << 160) | uint160(buyOrder.erc1155Token), erc1155FillAmount, orderHash ); } /// @dev Matches pairs of complementary orders that have /// non-negative spreads. Each order is filled at /// their respective price, and the matcher receives /// a profit denominated in the ERC20 token. /// @param sellOrders Orders selling ERC1155 assets. /// @param buyOrders Orders buying ERC1155 assets. /// @param sellOrderSignatures Signatures for the sell orders. /// @param buyOrderSignatures Signatures for the buy orders. /// @return profits The amount of profit earned by the caller /// of this function for each pair of matched orders /// (denominated in the ERC20 token of the order pair). /// @return successes An array of booleans corresponding to /// whether each pair of orders was successfully matched. function batchMatchSharedERC1155Orders( LibNFTOrder.ERC1155SellOrder[] memory sellOrders, LibNFTOrder.ERC1155BuyOrder[] memory buyOrders, LibSignature.Signature[] memory sellOrderSignatures, LibSignature.Signature[] memory buyOrderSignatures ) public override returns (uint256[] memory profits, bool[] memory successes) { require( sellOrders.length == buyOrders.length && sellOrderSignatures.length == buyOrderSignatures.length && sellOrders.length == sellOrderSignatures.length ); profits = new uint256[](sellOrders.length); successes = new bool[](sellOrders.length); for (uint256 i = 0; i < sellOrders.length; i++) { bytes memory returnData; // Delegatecall `matchSharedERC1155Orders` to catch reverts while // preserving execution context. (successes[i], returnData) = _implementation.delegatecall( abi.encodeWithSelector( this.matchSharedERC1155Orders.selector, sellOrders[i], buyOrders[i], sellOrderSignatures[i], buyOrderSignatures[i] ) ); if (successes[i]) { // If the matching succeeded, record the profit. (uint256 profit) = abi.decode(returnData, (uint256)); profits[i] = profit; } } } /// @dev Updates storage to indicate that the given order /// has been filled by the given amount. /// @param orderHash The hash of `order`. /// @param fillAmount The amount (denominated in the NFT asset) /// that the order has been filled by. function _updateOrderState( LibNFTOrder.NFTSellOrder memory /* order */, bytes32 orderHash, uint128 fillAmount ) internal override { LibERC1155OrdersStorage.Storage storage stor = LibERC1155OrdersStorage.getStorage(); uint128 filledAmount = stor.orderState[orderHash].filledAmount; // Filled amount should never overflow 128 bits require(filledAmount + fillAmount > filledAmount); stor.orderState[orderHash].filledAmount = filledAmount + fillAmount; } /// @dev Get the order info for an NFT sell order. /// @param nftSellOrder The NFT sell order. /// @return orderInfo Info about the order. function _getOrderInfo(LibNFTOrder.NFTSellOrder memory nftSellOrder) internal override view returns (LibNFTOrder.OrderInfo memory orderInfo) { LibNFTOrder.ERC1155SellOrder memory order = nftSellOrder.asERC1155SellOrder(); orderInfo.orderAmount = order.erc1155TokenAmount; orderInfo.orderHash = _getERC1155SellOrderHash(order); // Check for listingTime. // Gas Optimize, listingTime only used in rare cases. if (order.expiry & 0xffffffff00000000 > 0) { if ((order.expiry >> 32) & 0xffffffff > block.timestamp) { orderInfo.status = LibNFTOrder.OrderStatus.INVALID; return orderInfo; } } // Check for expiryTime. if (order.expiry & 0xffffffff <= block.timestamp) { orderInfo.status = LibNFTOrder.OrderStatus.EXPIRED; return orderInfo; } { LibERC1155OrdersStorage.Storage storage stor = LibERC1155OrdersStorage.getStorage(); LibERC1155OrdersStorage.OrderState storage orderState = stor.orderState[orderInfo.orderHash]; orderInfo.remainingAmount = order.erc1155TokenAmount - orderState.filledAmount; // `orderCancellationByMaker` is indexed by maker and nonce. uint256 orderCancellationBitVector = stor.orderCancellationByMaker[order.maker][uint248(order.nonce >> 8)]; // The bitvector is indexed by the lower 8 bits of the nonce. uint256 flag = 1 << (order.nonce & 255); if (orderInfo.remainingAmount == 0 || orderCancellationBitVector & flag != 0) { orderInfo.status = LibNFTOrder.OrderStatus.UNFILLABLE; return orderInfo; } } // Otherwise, the order is fillable. orderInfo.status = LibNFTOrder.OrderStatus.FILLABLE; return orderInfo; } /// @dev Get the order info for an NFT buy order. /// @param nftBuyOrder The NFT buy order. /// @return orderInfo Info about the order. function _getOrderInfo(LibNFTOrder.NFTBuyOrder memory nftBuyOrder) internal override view returns (LibNFTOrder.OrderInfo memory orderInfo) { LibNFTOrder.ERC1155BuyOrder memory order = nftBuyOrder.asERC1155BuyOrder(); orderInfo.orderAmount = order.erc1155TokenAmount; orderInfo.orderHash = _getERC1155BuyOrderHash(order); // Only buy orders with `erc1155TokenId` == 0 can be property // orders. if (order.erc1155TokenId != 0 && order.erc1155TokenProperties.length > 0) { orderInfo.status = LibNFTOrder.OrderStatus.INVALID; return orderInfo; } // Buy orders cannot use ETH as the ERC20 token, since ETH cannot be // transferred from the buyer by a contract. if (address(order.erc20Token) == NATIVE_TOKEN_ADDRESS) { orderInfo.status = LibNFTOrder.OrderStatus.INVALID; return orderInfo; } // Check for listingTime. // Gas Optimize, listingTime only used in rare cases. if (order.expiry & 0xffffffff00000000 > 0) { if ((order.expiry >> 32) & 0xffffffff > block.timestamp) { orderInfo.status = LibNFTOrder.OrderStatus.INVALID; return orderInfo; } } // Check for expiryTime. if (order.expiry & 0xffffffff <= block.timestamp) { orderInfo.status = LibNFTOrder.OrderStatus.EXPIRED; return orderInfo; } { LibERC1155OrdersStorage.Storage storage stor = LibERC1155OrdersStorage.getStorage(); LibERC1155OrdersStorage.OrderState storage orderState = stor.orderState[orderInfo.orderHash]; orderInfo.remainingAmount = order.erc1155TokenAmount - orderState.filledAmount; // `orderCancellationByMaker` is indexed by maker and nonce. uint256 orderCancellationBitVector = stor.orderCancellationByMaker[order.maker][uint248(order.nonce >> 8)]; // The bitvector is indexed by the lower 8 bits of the nonce. uint256 flag = 1 << (order.nonce & 255); if (orderInfo.remainingAmount == 0 || orderCancellationBitVector & flag != 0) { orderInfo.status = LibNFTOrder.OrderStatus.UNFILLABLE; return orderInfo; } } // Otherwise, the order is fillable. orderInfo.status = LibNFTOrder.OrderStatus.FILLABLE; return orderInfo; } function _getERC1155SellOrderHash(LibNFTOrder.ERC1155SellOrder memory order) private view returns (bytes32 orderHash) { return _getEIP712Hash( LibNFTOrder.getERC1155SellOrderStructHash( order, LibCommonNftOrdersStorage.getStorage().hashNonces[order.maker] ) ); } function _getERC1155BuyOrderHash(LibNFTOrder.ERC1155BuyOrder memory order) private view returns (bytes32 orderHash) { return _getEIP712Hash( LibNFTOrder.getERC1155BuyOrderStructHash( order, LibCommonNftOrdersStorage.getStorage().hashNonces[order.maker] ) ); } } // SPDX-License-Identifier: Apache-2.0 /* Copyright 2022 Element.Market 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. */ pragma solidity ^0.8.13; import "./LibStorage.sol"; library LibCommonNftOrdersStorage { /// @dev Storage bucket for this feature. struct Storage { /* Track per-maker nonces that can be incremented by the maker to cancel orders in bulk. */ // The current nonce for the maker represents the only valid nonce that can be signed by the maker // If a signature was signed with a nonce that's different from the one stored in nonces, it // will fail validation. mapping(address => uint256) hashNonces; } /// @dev Get the storage bucket for this contract. function getStorage() internal pure returns (Storage storage stor) { uint256 storageSlot = LibStorage.STORAGE_ID_COMMON_NFT_ORDERS; // Dip into assembly to change the slot pointed to by the local // variable `stor`. // See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries assembly { stor.slot := storageSlot } } } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2020 ZeroEx Intl. 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. */ pragma solidity ^0.8.13; import "./LibStorage.sol"; /// @dev Storage helpers for `ERC1155OrdersFeature`. library LibERC1155OrdersStorage { struct OrderState { // The amount (denominated in the ERC1155 asset) // that the order has been filled by. uint128 filledAmount; // Whether the order has been pre-signed. uint128 preSigned; } /// @dev Storage bucket for this feature. struct Storage { // Mapping from order hash to order state: mapping(bytes32 => OrderState) orderState; // maker => nonce range => order cancellation bit vector mapping(address => mapping(uint248 => uint256)) orderCancellationByMaker; } /// @dev Get the storage bucket for this contract. function getStorage() internal pure returns (Storage storage stor) { uint256 storageSlot = LibStorage.STORAGE_ID_ERC1155_ORDERS; // Dip into assembly to change the slot pointed to by the local // variable `stor`. // See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries assembly { stor.slot := storageSlot } } } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2021 ZeroEx Intl. 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. */ pragma solidity ^0.8.13; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../../vendor/IPropertyValidator.sol"; /// @dev A library for common NFT order operations. library LibNFTOrder { enum OrderStatus { INVALID, FILLABLE, UNFILLABLE, EXPIRED } struct Property { IPropertyValidator propertyValidator; bytes propertyData; } struct Fee { address recipient; uint256 amount; bytes feeData; } struct NFTSellOrder { address maker; address taker; uint256 expiry; uint256 nonce; IERC20 erc20Token; uint256 erc20TokenAmount; Fee[] fees; address nft; uint256 nftId; } // All fields except `nftProperties` align // with those of NFTSellOrder struct NFTBuyOrder { address maker; address taker; uint256 expiry; uint256 nonce; IERC20 erc20Token; uint256 erc20TokenAmount; Fee[] fees; address nft; uint256 nftId; Property[] nftProperties; } // All fields except `erc1155TokenAmount` align // with those of NFTSellOrder struct ERC1155SellOrder { address maker; address taker; uint256 expiry; uint256 nonce; IERC20 erc20Token; uint256 erc20TokenAmount; Fee[] fees; address erc1155Token; uint256 erc1155TokenId; // End of fields shared with NFTOrder uint128 erc1155TokenAmount; } // All fields except `erc1155TokenAmount` align // with those of NFTBuyOrder struct ERC1155BuyOrder { address maker; address taker; uint256 expiry; uint256 nonce; IERC20 erc20Token; uint256 erc20TokenAmount; Fee[] fees; address erc1155Token; uint256 erc1155TokenId; Property[] erc1155TokenProperties; // End of fields shared with NFTOrder uint128 erc1155TokenAmount; } struct OrderInfo { bytes32 orderHash; OrderStatus status; // `orderAmount` is 1 for all ERC721Orders, and // `erc1155TokenAmount` for ERC1155Orders. uint128 orderAmount; // The remaining amount of the ERC721/ERC1155 asset // that can be filled for the order. uint128 remainingAmount; } // The type hash for sell orders, which is: // keccak256(abi.encodePacked( // "NFTSellOrder(", // "address maker,", // "address taker,", // "uint256 expiry,", // "uint256 nonce,", // "address erc20Token,", // "uint256 erc20TokenAmount,", // "Fee[] fees,", // "address nft,", // "uint256 nftId,", // "uint256 hashNonce", // ")", // "Fee(", // "address recipient,", // "uint256 amount,", // "bytes feeData", // ")" // )) uint256 private constant _NFT_SELL_ORDER_TYPE_HASH = 0xed676c7f3e8232a311454799b1cf26e75b4abc90c9bf06c9f7e8e79fcc7fe14d; // The type hash for buy orders, which is: // keccak256(abi.encodePacked( // "NFTBuyOrder(", // "address maker,", // "address taker,", // "uint256 expiry,", // "uint256 nonce,", // "address erc20Token,", // "uint256 erc20TokenAmount,", // "Fee[] fees,", // "address nft,", // "uint256 nftId,", // "Property[] nftProperties,", // "uint256 hashNonce", // ")", // "Fee(", // "address recipient,", // "uint256 amount,", // "bytes feeData", // ")", // "Property(", // "address propertyValidator,", // "bytes propertyData", // ")" // )) uint256 private constant _NFT_BUY_ORDER_TYPE_HASH = 0xa525d336300f566329800fcbe82fd263226dc27d6c109f060d9a4a364281521c; // The type hash for ERC1155 sell orders, which is: // keccak256(abi.encodePacked( // "ERC1155SellOrder(", // "address maker,", // "address taker,", // "uint256 expiry,", // "uint256 nonce,", // "address erc20Token,", // "uint256 erc20TokenAmount,", // "Fee[] fees,", // "address erc1155Token,", // "uint256 erc1155TokenId,", // "uint128 erc1155TokenAmount,", // "uint256 hashNonce", // ")", // "Fee(", // "address recipient,", // "uint256 amount,", // "bytes feeData", // ")" // )) uint256 private constant _ERC_1155_SELL_ORDER_TYPE_HASH = 0x3529b5920cc48ecbceb24e9c51dccb50fefd8db2cf05d36e356aeb1754e19eda; // The type hash for ERC1155 buy orders, which is: // keccak256(abi.encodePacked( // "ERC1155BuyOrder(", // "address maker,", // "address taker,", // "uint256 expiry,", // "uint256 nonce,", // "address erc20Token,", // "uint256 erc20TokenAmount,", // "Fee[] fees,", // "address erc1155Token,", // "uint256 erc1155TokenId,", // "Property[] erc1155TokenProperties,", // "uint128 erc1155TokenAmount,", // "uint256 hashNonce", // ")", // "Fee(", // "address recipient,", // "uint256 amount,", // "bytes feeData", // ")", // "Property(", // "address propertyValidator,", // "bytes propertyData", // ")" // )) uint256 private constant _ERC_1155_BUY_ORDER_TYPE_HASH = 0x1a6eaae1fbed341e0974212ec17f035a9d419cadc3bf5154841cbf7fd605ba48; // keccak256(abi.encodePacked( // "Fee(", // "address recipient,", // "uint256 amount,", // "bytes feeData", // ")" // )) uint256 private constant _FEE_TYPE_HASH = 0xe68c29f1b4e8cce0bbcac76eb1334bdc1dc1f293a517c90e9e532340e1e94115; // keccak256(abi.encodePacked( // "Property(", // "address propertyValidator,", // "bytes propertyData", // ")" // )) uint256 private constant _PROPERTY_TYPE_HASH = 0x6292cf854241cb36887e639065eca63b3af9f7f70270cebeda4c29b6d3bc65e8; // keccak256(""); bytes32 private constant _EMPTY_ARRAY_KECCAK256 = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // keccak256(abi.encodePacked(keccak256(abi.encode( // _PROPERTY_TYPE_HASH, // address(0), // keccak256("") // )))); bytes32 private constant _NULL_PROPERTY_STRUCT_HASH = 0x720ee400a9024f6a49768142c339bf09d2dd9056ab52d20fbe7165faba6e142d; uint256 private constant ADDRESS_MASK = (1 << 160) - 1; function asNFTSellOrder(NFTBuyOrder memory nftBuyOrder) internal pure returns (NFTSellOrder memory order) { assembly { order := nftBuyOrder } } function asNFTSellOrder(ERC1155SellOrder memory erc1155SellOrder) internal pure returns (NFTSellOrder memory order) { assembly { order := erc1155SellOrder } } function asNFTBuyOrder(ERC1155BuyOrder memory erc1155BuyOrder) internal pure returns (NFTBuyOrder memory order) { assembly { order := erc1155BuyOrder } } function asERC1155SellOrder(NFTSellOrder memory nftSellOrder) internal pure returns (ERC1155SellOrder memory order) { assembly { order := nftSellOrder } } function asERC1155BuyOrder(NFTBuyOrder memory nftBuyOrder) internal pure returns (ERC1155BuyOrder memory order) { assembly { order := nftBuyOrder } } // @dev Get the struct hash of an sell order. /// @param order The sell order. /// @return structHash The struct hash of the order. function getNFTSellOrderStructHash(NFTSellOrder memory order, uint256 hashNonce) internal pure returns (bytes32 structHash) { bytes32 feesHash = _feesHash(order.fees); // Hash in place, equivalent to: // return keccak256(abi.encode( // _NFT_SELL_ORDER_TYPE_HASH, // order.maker, // order.taker, // order.expiry, // order.nonce, // order.erc20Token, // order.erc20TokenAmount, // feesHash, // order.nft, // order.nftId, // hashNonce // )); assembly { if lt(order, 32) { invalid() } // Don't underflow memory. let typeHashPos := sub(order, 32) // order - 32 let feesHashPos := add(order, 192) // order + (32 * 6) let hashNoncePos := add(order, 288) // order + (32 * 9) let typeHashMemBefore := mload(typeHashPos) let feeHashMemBefore := mload(feesHashPos) let hashNonceMemBefore := mload(hashNoncePos) mstore(typeHashPos, _NFT_SELL_ORDER_TYPE_HASH) mstore(feesHashPos, feesHash) mstore(hashNoncePos, hashNonce) structHash := keccak256(typeHashPos, 352 /* 32 * 11 */ ) mstore(typeHashPos, typeHashMemBefore) mstore(feesHashPos, feeHashMemBefore) mstore(hashNoncePos, hashNonceMemBefore) } return structHash; } /// @dev Get the struct hash of an buy order. /// @param order The buy order. /// @return structHash The struct hash of the order. function getNFTBuyOrderStructHash(NFTBuyOrder memory order, uint256 hashNonce) internal pure returns (bytes32 structHash) { bytes32 propertiesHash = _propertiesHash(order.nftProperties); bytes32 feesHash = _feesHash(order.fees); // Hash in place, equivalent to: // return keccak256(abi.encode( // _NFT_BUY_ORDER_TYPE_HASH, // order.maker, // order.taker, // order.expiry, // order.nonce, // order.erc20Token, // order.erc20TokenAmount, // feesHash, // order.nft, // order.nftId, // propertiesHash, // hashNonce // )); assembly { if lt(order, 32) { invalid() } // Don't underflow memory. let typeHashPos := sub(order, 32) // order - 32 let feesHashPos := add(order, 192) // order + (32 * 6) let propertiesHashPos := add(order, 288) // order + (32 * 9) let hashNoncePos := add(order, 320) // order + (32 * 10) let typeHashMemBefore := mload(typeHashPos) let feeHashMemBefore := mload(feesHashPos) let propertiesHashMemBefore := mload(propertiesHashPos) let hashNonceMemBefore := mload(hashNoncePos) mstore(typeHashPos, _NFT_BUY_ORDER_TYPE_HASH) mstore(feesHashPos, feesHash) mstore(propertiesHashPos, propertiesHash) mstore(hashNoncePos, hashNonce) structHash := keccak256(typeHashPos, 384 /* 32 * 12 */ ) mstore(typeHashPos, typeHashMemBefore) mstore(feesHashPos, feeHashMemBefore) mstore(propertiesHashPos, propertiesHashMemBefore) mstore(hashNoncePos, hashNonceMemBefore) } return structHash; } /// @dev Get the struct hash of an ERC1155 sell order. /// @param order The ERC1155 sell order. /// @return structHash The struct hash of the order. function getERC1155SellOrderStructHash(ERC1155SellOrder memory order, uint256 hashNonce) internal pure returns (bytes32 structHash) { bytes32 feesHash = _feesHash(order.fees); // Hash in place, equivalent to: // return keccak256(abi.encode( // _ERC_1155_SELL_ORDER_TYPE_HASH, // order.maker, // order.taker, // order.expiry, // order.nonce, // order.erc20Token, // order.erc20TokenAmount, // feesHash, // order.erc1155Token, // order.erc1155TokenId, // order.erc1155TokenAmount, // hashNonce // )); assembly { if lt(order, 32) { invalid() } // Don't underflow memory. let typeHashPos := sub(order, 32) // order - 32 let feesHashPos := add(order, 192) // order + (32 * 6) let hashNoncePos := add(order, 320) // order + (32 * 10) let typeHashMemBefore := mload(typeHashPos) let feesHashMemBefore := mload(feesHashPos) let hashNonceMemBefore := mload(hashNoncePos) mstore(typeHashPos, _ERC_1155_SELL_ORDER_TYPE_HASH) mstore(feesHashPos, feesHash) mstore(hashNoncePos, hashNonce) structHash := keccak256(typeHashPos, 384 /* 32 * 12 */ ) mstore(typeHashPos, typeHashMemBefore) mstore(feesHashPos, feesHashMemBefore) mstore(hashNoncePos, hashNonceMemBefore) } return structHash; } /// @dev Get the struct hash of an ERC1155 buy order. /// @param order The ERC1155 buy order. /// @return structHash The struct hash of the order. function getERC1155BuyOrderStructHash(ERC1155BuyOrder memory order, uint256 hashNonce) internal pure returns (bytes32 structHash) { bytes32 propertiesHash = _propertiesHash(order.erc1155TokenProperties); bytes32 feesHash = _feesHash(order.fees); // Hash in place, equivalent to: // return keccak256(abi.encode( // _ERC_1155_BUY_ORDER_TYPE_HASH, // order.maker, // order.taker, // order.expiry, // order.nonce, // order.erc20Token, // order.erc20TokenAmount, // feesHash, // order.erc1155Token, // order.erc1155TokenId, // propertiesHash, // order.erc1155TokenAmount, // hashNonce // )); assembly { if lt(order, 32) { invalid() } // Don't underflow memory. let typeHashPos := sub(order, 32) // order - 32 let feesHashPos := add(order, 192) // order + (32 * 6) let propertiesHashPos := add(order, 288) // order + (32 * 9) let hashNoncePos := add(order, 352) // order + (32 * 11) let typeHashMemBefore := mload(typeHashPos) let feesHashMemBefore := mload(feesHashPos) let propertiesHashMemBefore := mload(propertiesHashPos) let hashNonceMemBefore := mload(hashNoncePos) mstore(typeHashPos, _ERC_1155_BUY_ORDER_TYPE_HASH) mstore(feesHashPos, feesHash) mstore(propertiesHashPos, propertiesHash) mstore(hashNoncePos, hashNonce) structHash := keccak256(typeHashPos, 416 /* 32 * 13 */ ) mstore(typeHashPos, typeHashMemBefore) mstore(feesHashPos, feesHashMemBefore) mstore(propertiesHashPos, propertiesHashMemBefore) mstore(hashNoncePos, hashNonceMemBefore) } return structHash; } // Hashes the `properties` array as part of computing the // EIP-712 hash of an `ERC721Order` or `ERC1155Order`. function _propertiesHash(Property[] memory properties) private pure returns (bytes32 propertiesHash) { uint256 numProperties = properties.length; // We give `properties.length == 0` and `properties.length == 1` // special treatment because we expect these to be the most common. if (numProperties == 0) { propertiesHash = _EMPTY_ARRAY_KECCAK256; } else if (numProperties == 1) { Property memory property = properties[0]; if (address(property.propertyValidator) == address(0) && property.propertyData.length == 0) { propertiesHash = _NULL_PROPERTY_STRUCT_HASH; } else { // propertiesHash = keccak256(abi.encodePacked(keccak256(abi.encode( // _PROPERTY_TYPE_HASH, // properties[0].propertyValidator, // keccak256(properties[0].propertyData) // )))); bytes32 dataHash = keccak256(property.propertyData); assembly { // Load free memory pointer let mem := mload(64) mstore(mem, _PROPERTY_TYPE_HASH) // property.propertyValidator mstore(add(mem, 32), and(ADDRESS_MASK, mload(property))) // keccak256(property.propertyData) mstore(add(mem, 64), dataHash) mstore(mem, keccak256(mem, 96)) propertiesHash := keccak256(mem, 32) } } } else { bytes32[] memory propertyStructHashArray = new bytes32[](numProperties); for (uint256 i = 0; i < numProperties; i++) { propertyStructHashArray[i] = keccak256(abi.encode( _PROPERTY_TYPE_HASH, properties[i].propertyValidator, keccak256(properties[i].propertyData))); } assembly { propertiesHash := keccak256(add(propertyStructHashArray, 32), mul(numProperties, 32)) } } } // Hashes the `fees` array as part of computing the // EIP-712 hash of an `ERC721Order` or `ERC1155Order`. function _feesHash(Fee[] memory fees) private pure returns (bytes32 feesHash) { uint256 numFees = fees.length; // We give `fees.length == 0` and `fees.length == 1` // special treatment because we expect these to be the most common. if (numFees == 0) { feesHash = _EMPTY_ARRAY_KECCAK256; } else if (numFees == 1) { // feesHash = keccak256(abi.encodePacked(keccak256(abi.encode( // _FEE_TYPE_HASH, // fees[0].recipient, // fees[0].amount, // keccak256(fees[0].feeData) // )))); Fee memory fee = fees[0]; bytes32 dataHash = keccak256(fee.feeData); assembly { // Load free memory pointer let mem := mload(64) mstore(mem, _FEE_TYPE_HASH) // fee.recipient mstore(add(mem, 32), and(ADDRESS_MASK, mload(fee))) // fee.amount mstore(add(mem, 64), mload(add(fee, 32))) // keccak256(fee.feeData) mstore(add(mem, 96), dataHash) mstore(mem, keccak256(mem, 128)) feesHash := keccak256(mem, 32) } } else { bytes32[] memory feeStructHashArray = new bytes32[](numFees); for (uint256 i = 0; i < numFees; i++) { feeStructHashArray[i] = keccak256(abi.encode(_FEE_TYPE_HASH, fees[i].recipient, fees[i].amount, keccak256(fees[i].feeData))); } assembly { feesHash := keccak256(add(feeStructHashArray, 32), mul(numFees, 32)) } } } } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2020 ZeroEx Intl. 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. */ pragma solidity ^0.8.13; /// @dev A library for validating signatures. library LibSignature { /// @dev Allowed signature types. enum SignatureType { EIP712, PRESIGNED } /// @dev Encoded EC signature. struct Signature { // How to validate the signature. SignatureType signatureType; // EC Signature data. uint8 v; // EC Signature data. bytes32 r; // EC Signature data. bytes32 s; } } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2021 ZeroEx Intl. 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. */ pragma solidity ^0.8.13; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../../fixins/FixinEIP712.sol"; import "../../fixins/FixinTokenSpender.sol"; import "../../vendor/IEtherToken.sol"; import "../../vendor/IFeeRecipient.sol"; import "../../vendor/ITakerCallback.sol"; import "../libs/LibSignature.sol"; import "../libs/LibNFTOrder.sol"; /// @dev Abstract base contract inherited by ERC721OrdersFeature and NFTOrders abstract contract NFTOrders is FixinEIP712, FixinTokenSpender { using LibNFTOrder for LibNFTOrder.NFTBuyOrder; /// @dev Native token pseudo-address. address constant internal NATIVE_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @dev The WETH token contract. IEtherToken internal immutable WETH; /// @dev The implementation address of this feature. address internal immutable _implementation; /// @dev The magic return value indicating the success of a `receiveZeroExFeeCallback`. bytes4 private constant FEE_CALLBACK_MAGIC_BYTES = IFeeRecipient.receiveZeroExFeeCallback.selector; /// @dev The magic return value indicating the success of a `zeroExTakerCallback`. bytes4 private constant TAKER_CALLBACK_MAGIC_BYTES = ITakerCallback.zeroExTakerCallback.selector; constructor(IEtherToken weth) { WETH = weth; // Remember this feature's original address. _implementation = address(this); } struct SellParams { uint128 sellAmount; uint256 tokenId; bool unwrapNativeToken; address taker; address currentNftOwner; bytes takerCallbackData; } struct BuyParams { uint128 buyAmount; uint256 ethAvailable; address taker; bytes takerCallbackData; } // Core settlement logic for selling an NFT asset. function _sellNFT( LibNFTOrder.NFTBuyOrder memory buyOrder, LibSignature.Signature memory signature, SellParams memory params ) internal returns (uint256 erc20FillAmount, bytes32 orderHash) { LibNFTOrder.OrderInfo memory orderInfo = _getOrderInfo(buyOrder); orderHash = orderInfo.orderHash; // Check that the order can be filled. _validateBuyOrder(buyOrder, signature, orderInfo, params.taker, params.tokenId); // Check amount. if (params.sellAmount > orderInfo.remainingAmount) { revert("_sellNFT/EXCEEDS_REMAINING_AMOUNT"); } // Update the order state. _updateOrderState(buyOrder.asNFTSellOrder(), orderInfo.orderHash, params.sellAmount); // Calculate erc20 pay amount. erc20FillAmount = (params.sellAmount == orderInfo.orderAmount) ? buyOrder.erc20TokenAmount : buyOrder.erc20TokenAmount * params.sellAmount / orderInfo.orderAmount; if (params.unwrapNativeToken) { // The ERC20 token must be WETH for it to be unwrapped. require(buyOrder.erc20Token == WETH, "_sellNFT/ERC20_TOKEN_MISMATCH_ERROR"); // Transfer the WETH from the maker to the Exchange Proxy // so we can unwrap it before sending it to the seller. // TODO: Probably safe to just use WETH.transferFrom for some // small gas savings _transferERC20TokensFrom(WETH, buyOrder.maker, address(this), erc20FillAmount); // Unwrap WETH into ETH. WETH.withdraw(erc20FillAmount); // Send ETH to the seller. _transferEth(payable(params.taker), erc20FillAmount); } else { // Transfer the ERC20 token from the buyer to the seller. _transferERC20TokensFrom(buyOrder.erc20Token, buyOrder.maker, params.taker, erc20FillAmount); } if (params.takerCallbackData.length > 0) { require(params.taker != address(this), "_sellNFT/CANNOT_CALLBACK_SELF"); // Invoke the callback bytes4 callbackResult = ITakerCallback(params.taker).zeroExTakerCallback(orderInfo.orderHash, params.takerCallbackData); // Check for the magic success bytes require(callbackResult == TAKER_CALLBACK_MAGIC_BYTES, "_sellNFT/CALLBACK_FAILED"); } // Transfer the NFT asset to the buyer. // If this function is called from the // `onNFTReceived` callback the Exchange Proxy // holds the asset. Otherwise, transfer it from // the seller. _transferNFTAssetFrom(buyOrder.nft, params.currentNftOwner, buyOrder.maker, params.tokenId, params.sellAmount); // The buyer pays the order fees. _payFees(buyOrder.asNFTSellOrder(), buyOrder.maker, params.sellAmount, orderInfo.orderAmount, false); } // Core settlement logic for buying an NFT asset. function _buyNFT( LibNFTOrder.NFTSellOrder memory sellOrder, LibSignature.Signature memory signature, uint128 buyAmount ) internal returns (uint256 erc20FillAmount, bytes32 orderHash) { LibNFTOrder.OrderInfo memory orderInfo = _getOrderInfo(sellOrder); orderHash = orderInfo.orderHash; // Check that the order can be filled. _validateSellOrder(sellOrder, signature, orderInfo, msg.sender); // Check amount. if (buyAmount > orderInfo.remainingAmount) { revert("_buyNFT/EXCEEDS_REMAINING_AMOUNT"); } // Update the order state. _updateOrderState(sellOrder, orderInfo.orderHash, buyAmount); // Calculate erc20 pay amount. erc20FillAmount = (buyAmount == orderInfo.orderAmount) ? sellOrder.erc20TokenAmount : _ceilDiv(sellOrder.erc20TokenAmount * buyAmount, orderInfo.orderAmount); // Transfer the NFT asset to the buyer (`msg.sender`). _transferNFTAssetFrom(sellOrder.nft, sellOrder.maker, msg.sender, sellOrder.nftId, buyAmount); if (address(sellOrder.erc20Token) == NATIVE_TOKEN_ADDRESS) { // Transfer ETH to the seller. _transferEth(payable(sellOrder.maker), erc20FillAmount); // Fees are paid from the EP's current balance of ETH. _payFees(sellOrder, address(this), buyAmount, orderInfo.orderAmount, true); } else { // Transfer ERC20 token from the buyer to the seller. _transferERC20TokensFrom(sellOrder.erc20Token, msg.sender, sellOrder.maker, erc20FillAmount); // The buyer pays fees. _payFees(sellOrder, msg.sender, buyAmount, orderInfo.orderAmount, false); } } function _buyNFTEx( LibNFTOrder.NFTSellOrder memory sellOrder, LibSignature.Signature memory signature, BuyParams memory params ) internal returns (uint256 erc20FillAmount, bytes32 orderHash) { LibNFTOrder.OrderInfo memory orderInfo = _getOrderInfo(sellOrder); orderHash = orderInfo.orderHash; // Check that the order can be filled. _validateSellOrder(sellOrder, signature, orderInfo, params.taker); // Check amount. if (params.buyAmount > orderInfo.remainingAmount) { revert("_buyNFTEx/EXCEEDS_REMAINING_AMOUNT"); } // Update the order state. _updateOrderState(sellOrder, orderInfo.orderHash, params.buyAmount); // Dutch Auction if (sellOrder.expiry >> 252 == 1) { uint256 count = (sellOrder.expiry >> 64) & 0xffffffff; if (count > 0) { _resetDutchAuctionTokenAmountAndFees(sellOrder, count); } } // Calculate erc20 pay amount. erc20FillAmount = (params.buyAmount == orderInfo.orderAmount) ? sellOrder.erc20TokenAmount : _ceilDiv(sellOrder.erc20TokenAmount * params.buyAmount, orderInfo.orderAmount); // Transfer the NFT asset to the buyer. _transferNFTAssetFrom(sellOrder.nft, sellOrder.maker, params.taker, sellOrder.nftId, params.buyAmount); uint256 ethAvailable = params.ethAvailable; if (params.takerCallbackData.length > 0) { require(msg.sender != address(this), "_buyNFTEx/CANNOT_CALLBACK_SELF"); uint256 ethBalanceBeforeCallback = address(this).balance; // Invoke the callback bytes4 callbackResult = ITakerCallback(msg.sender).zeroExTakerCallback(orderInfo.orderHash, params.takerCallbackData); // Update `ethAvailable` with amount acquired during // the callback ethAvailable += address(this).balance - ethBalanceBeforeCallback; // Check for the magic success bytes require(callbackResult == TAKER_CALLBACK_MAGIC_BYTES, "_buyNFTEx/CALLBACK_FAILED"); } if (address(sellOrder.erc20Token) == NATIVE_TOKEN_ADDRESS) { uint256 totalPaid = erc20FillAmount + _calcTotalFeesPaid(sellOrder.fees, params.buyAmount, orderInfo.orderAmount); if (ethAvailable < totalPaid) { // Transfer WETH from the buyer to this contract. uint256 withDrawAmount = totalPaid - ethAvailable; _transferERC20TokensFrom(WETH, msg.sender, address(this), withDrawAmount); // Unwrap WETH into ETH. WETH.withdraw(withDrawAmount); } // Transfer ETH to the seller. _transferEth(payable(sellOrder.maker), erc20FillAmount); // Fees are paid from the EP's current balance of ETH. _payFees(sellOrder, address(this), params.buyAmount, orderInfo.orderAmount, true); } else if (sellOrder.erc20Token == WETH) { uint256 totalFeesPaid = _calcTotalFeesPaid(sellOrder.fees, params.buyAmount, orderInfo.orderAmount); if (ethAvailable > totalFeesPaid) { uint256 depositAmount = ethAvailable - totalFeesPaid; if (depositAmount < erc20FillAmount) { // Transfer WETH from the buyer to this contract. _transferERC20TokensFrom(WETH, msg.sender, address(this), (erc20FillAmount - depositAmount)); } else { depositAmount = erc20FillAmount; } // Wrap ETH. WETH.deposit{value: depositAmount}(); // Transfer WETH to the seller. _transferERC20Tokens(WETH, sellOrder.maker, erc20FillAmount); // Fees are paid from the EP's current balance of ETH. _payFees(sellOrder, address(this), params.buyAmount, orderInfo.orderAmount, true); } else { // Transfer WETH from the buyer to the seller. _transferERC20TokensFrom(WETH, msg.sender, sellOrder.maker, erc20FillAmount); if (ethAvailable > 0) { if (ethAvailable < totalFeesPaid) { // Transfer WETH from the buyer to this contract. uint256 value = totalFeesPaid - ethAvailable; _transferERC20TokensFrom(WETH, msg.sender, address(this), value); // Unwrap WETH into ETH. WETH.withdraw(value); } // Fees are paid from the EP's current balance of ETH. _payFees(sellOrder, address(this), params.buyAmount, orderInfo.orderAmount, true); } else { // The buyer pays fees using WETH. _payFees(sellOrder, msg.sender, params.buyAmount, orderInfo.orderAmount, false); } } } else { // Transfer ERC20 token from the buyer to the seller. _transferERC20TokensFrom(sellOrder.erc20Token, msg.sender, sellOrder.maker, erc20FillAmount); // The buyer pays fees. _payFees(sellOrder, msg.sender, params.buyAmount, orderInfo.orderAmount, false); } } function _validateSellOrder( LibNFTOrder.NFTSellOrder memory sellOrder, LibSignature.Signature memory signature, LibNFTOrder.OrderInfo memory orderInfo, address taker ) internal view { // Taker must match the order taker, if one is specified. require(sellOrder.taker == address(0) || sellOrder.taker == taker, "_validateOrder/ONLY_TAKER"); // Check that the order is valid and has not expired, been cancelled, // or been filled. require(orderInfo.status == LibNFTOrder.OrderStatus.FILLABLE, "_validateOrder/ORDER_NOT_FILL"); // Check the signature. _validateOrderSignature(orderInfo.orderHash, signature, sellOrder.maker); } function _validateBuyOrder( LibNFTOrder.NFTBuyOrder memory buyOrder, LibSignature.Signature memory signature, LibNFTOrder.OrderInfo memory orderInfo, address taker, uint256 tokenId ) internal view { // The ERC20 token cannot be ETH. require(address(buyOrder.erc20Token) != NATIVE_TOKEN_ADDRESS, "_validateBuyOrder/TOKEN_MISMATCH"); // Taker must match the order taker, if one is specified. require(buyOrder.taker == address(0) || buyOrder.taker == taker, "_validateBuyOrder/ONLY_TAKER"); // Check that the order is valid and has not expired, been cancelled, // or been filled. require(orderInfo.status == LibNFTOrder.OrderStatus.FILLABLE, "_validateOrder/ORDER_NOT_FILL"); // Check that the asset with the given token ID satisfies the properties // specified by the order. _validateOrderProperties(buyOrder, tokenId); // Check the signature. _validateOrderSignature(orderInfo.orderHash, signature, buyOrder.maker); } function _resetDutchAuctionTokenAmountAndFees(LibNFTOrder.NFTSellOrder memory order, uint256 count) internal view { require(count <= 100000000, "COUNT_OUT_OF_SIDE"); uint256 listingTime = (order.expiry >> 32) & 0xffffffff; uint256 denominator = ((order.expiry & 0xffffffff) - listingTime) * 100000000; uint256 multiplier = (block.timestamp - listingTime) * count; // Reset erc20TokenAmount uint256 amount = order.erc20TokenAmount; order.erc20TokenAmount = amount - amount * multiplier / denominator; // Reset fees for (uint256 i = 0; i < order.fees.length; i++) { amount = order.fees[i].amount; order.fees[i].amount = amount - amount * multiplier / denominator; } } function _resetEnglishAuctionTokenAmountAndFees( LibNFTOrder.NFTSellOrder memory sellOrder, uint256 buyERC20Amount, uint256 fillAmount, uint256 orderAmount ) internal pure { uint256 sellOrderFees = _calcTotalFeesPaid(sellOrder.fees, fillAmount, orderAmount); uint256 sellTotalAmount = sellOrderFees + sellOrder.erc20TokenAmount; if (buyERC20Amount != sellTotalAmount) { uint256 spread = buyERC20Amount - sellTotalAmount; uint256 sum; // Reset fees if (sellTotalAmount > 0) { for (uint256 i = 0; i < sellOrder.fees.length; i++) { uint256 diff = spread * sellOrder.fees[i].amount / sellTotalAmount; sellOrder.fees[i].amount += diff; sum += diff; } } // Reset erc20TokenAmount sellOrder.erc20TokenAmount += spread - sum; } } function _ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // ceil(a / b) = floor((a + b - 1) / b) return (a + b - 1) / b; } function _calcTotalFeesPaid(LibNFTOrder.Fee[] memory fees, uint256 fillAmount, uint256 orderAmount) private pure returns (uint256 totalFeesPaid) { if (fillAmount == orderAmount) { for (uint256 i = 0; i < fees.length; i++) { totalFeesPaid += fees[i].amount; } } else { for (uint256 i = 0; i < fees.length; i++) { totalFeesPaid += fees[i].amount * fillAmount / orderAmount; } } return totalFeesPaid; } function _payFees( LibNFTOrder.NFTSellOrder memory order, address payer, uint128 fillAmount, uint128 orderAmount, bool useNativeToken ) internal returns (uint256 totalFeesPaid) { for (uint256 i = 0; i < order.fees.length; i++) { LibNFTOrder.Fee memory fee = order.fees[i]; uint256 feeFillAmount = (fillAmount == orderAmount) ? fee.amount : fee.amount * fillAmount / orderAmount; if (useNativeToken) { // Transfer ETH to the fee recipient. _transferEth(payable(fee.recipient), feeFillAmount); } else { if (feeFillAmount > 0) { // Transfer ERC20 token from payer to recipient. _transferERC20TokensFrom(order.erc20Token, payer, fee.recipient, feeFillAmount); } } // Note that the fee callback is _not_ called if zero // `feeData` is provided. If `feeData` is provided, we assume // the fee recipient is a contract that implements the // `IFeeRecipient` interface. if (fee.feeData.length > 0) { // Invoke the callback bytes4 callbackResult = IFeeRecipient(fee.recipient).receiveZeroExFeeCallback( useNativeToken ? NATIVE_TOKEN_ADDRESS : address(order.erc20Token), feeFillAmount, fee.feeData ); // Check for the magic success bytes require(callbackResult == FEE_CALLBACK_MAGIC_BYTES, "_payFees/CALLBACK_FAILED"); } // Sum the fees paid totalFeesPaid += feeFillAmount; } return totalFeesPaid; } function _validateOrderProperties(LibNFTOrder.NFTBuyOrder memory order, uint256 tokenId) internal view { // If no properties are specified, check that the given // `tokenId` matches the one specified in the order. if (order.nftProperties.length == 0) { require(tokenId == order.nftId, "_validateProperties/TOKEN_ID_ERR"); } else { // Validate each property for (uint256 i = 0; i < order.nftProperties.length; i++) { LibNFTOrder.Property memory property = order.nftProperties[i]; // `address(0)` is interpreted as a no-op. Any token ID // will satisfy a property with `propertyValidator == address(0)`. if (address(property.propertyValidator) != address(0)) { // Call the property validator and throw a descriptive error // if the call reverts. try property.propertyValidator.validateProperty(order.nft, tokenId, property.propertyData) { } catch (bytes memory /* reason */) { revert("PROPERTY_VALIDATION_FAILED"); } } } } } /// @dev Validates that the given signature is valid for the /// given maker and order hash. Reverts if the signature /// is not valid. /// @param orderHash The hash of the order that was signed. /// @param signature The signature to check. /// @param maker The maker of the order. function _validateOrderSignature(bytes32 orderHash, LibSignature.Signature memory signature, address maker) internal virtual view; /// @dev Transfers an NFT asset. /// @param token The address of the NFT contract. /// @param from The address currently holding the asset. /// @param to The address to transfer the asset to. /// @param tokenId The ID of the asset to transfer. /// @param amount The amount of the asset to transfer. Always /// 1 for ERC721 assets. function _transferNFTAssetFrom(address token, address from, address to, uint256 tokenId, uint256 amount) internal virtual; /// @dev Updates storage to indicate that the given order /// has been filled by the given amount. /// @param order The order that has been filled. /// @param orderHash The hash of `order`. /// @param fillAmount The amount (denominated in the NFT asset) /// that the order has been filled by. function _updateOrderState(LibNFTOrder.NFTSellOrder memory order, bytes32 orderHash, uint128 fillAmount) internal virtual; /// @dev Get the order info for an NFT sell order. /// @param nftSellOrder The NFT sell order. /// @return orderInfo Info about the order. function _getOrderInfo(LibNFTOrder.NFTSellOrder memory nftSellOrder) internal virtual view returns (LibNFTOrder.OrderInfo memory); /// @dev Get the order info for an NFT buy order. /// @param nftBuyOrder The NFT buy order. /// @return orderInfo Info about the order. function _getOrderInfo(LibNFTOrder.NFTBuyOrder memory nftBuyOrder) internal virtual view returns (LibNFTOrder.OrderInfo memory); } // SPDX-License-Identifier: Apache-2.0 /* Copyright 2022 Element.Market 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. */ pragma solidity ^0.8.13; interface IAuthenticatedProxy { function implementation() external view returns (address); /** * Execute a message call from the proxy contract * * @dev Can be called by the user, or by a contract authorized by the registry as long as the user has not revoked access * @param dest Address to which the call will be sent * @param howToCall 0 - Call, 1 - DelegateCall * @param data Calldata to send * @return result Result of the call (success or failure) */ function proxy(address dest, uint8 howToCall, bytes calldata data) external returns (bool); /** * Execute a message call and assert success * * @dev Same functionality as `proxy`, just asserts the return value * @param dest Address to which the call will be sent * @param howToCall 0 - Call, 1 - DelegateCall * @param data Calldata to send */ function proxyAssert(address dest, uint8 howToCall, bytes calldata data) external; } // SPDX-License-Identifier: Apache-2.0 /* Copyright 2022 Element.Market 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. */ pragma solidity ^0.8.13; import {IAuthenticatedProxy} from './IAuthenticatedProxy.sol'; interface IProxyRegistry { function delegateProxyImplementation() external view returns (address); function proxies(address user) external view returns (IAuthenticatedProxy proxy); } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2021 ZeroEx Intl. 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. */ pragma solidity ^0.8.13; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "../../zero-ex/src/features/libs/LibNFTOrder.sol"; import "../../zero-ex/src/features/libs/LibSignature.sol"; import "../../zero-ex/src/features/interfaces/IERC1155OrdersEvent.sol"; /// @dev Feature for interacting with ERC1155 orders. interface ISharedERC1155OrdersFeature is IERC1155OrdersEvent { /// @dev Sells an ERC1155 asset to fill the given order. /// @param buyOrder The ERC1155 buy order. /// @param signature The order signature from the maker. /// @param erc1155TokenId The ID of the ERC1155 asset being /// sold. If the given order specifies properties, /// the asset must satisfy those properties. Otherwise, /// it must equal the tokenId in the order. /// @param erc1155SellAmount The amount of the ERC1155 asset /// to sell. /// @param unwrapNativeToken If this parameter is true and the /// ERC20 token of the order is e.g. WETH, unwraps the /// token before transferring it to the taker. /// @param callbackData If this parameter is non-zero, invokes /// `zeroExERC1155OrderCallback` on `msg.sender` after /// the ERC20 tokens have been transferred to `msg.sender` /// but before transferring the ERC1155 asset to the buyer. function sellSharedERC1155( LibNFTOrder.ERC1155BuyOrder calldata buyOrder, LibSignature.Signature calldata signature, uint256 erc1155TokenId, uint128 erc1155SellAmount, bool unwrapNativeToken, bytes calldata callbackData ) external; /// @dev Buys an ERC1155 asset by filling the given order. /// @param sellOrder The ERC1155 sell order. /// @param signature The order signature. /// @param erc1155BuyAmount The amount of the ERC1155 asset /// to buy. /// @param callbackData If this parameter is non-zero, invokes /// `zeroExERC1155OrderCallback` on `msg.sender` after /// the ERC1155 asset has been transferred to `msg.sender` /// but before transferring the ERC20 tokens to the seller. /// Native tokens acquired during the callback can be used /// to fill the order. function buySharedERC1155( LibNFTOrder.ERC1155SellOrder calldata sellOrder, LibSignature.Signature calldata signature, address taker, uint128 erc1155BuyAmount, bytes calldata callbackData ) external payable; /// @dev Buys multiple ERC1155 assets by filling the /// given orders. /// @param sellOrders The ERC1155 sell orders. /// @param signatures The order signatures. /// @param erc1155FillAmounts The amounts of the ERC1155 assets /// to buy for each order. /// @param callbackData The data (if any) to pass to the taker /// callback for each order. Refer to the `callbackData` /// parameter to for `buyERC1155`. /// @param revertIfIncomplete If true, reverts if this /// function fails to fill any individual order. /// @return successes An array of booleans corresponding to whether /// each order in `orders` was successfully filled. function batchBuySharedERC1155s( LibNFTOrder.ERC1155SellOrder[] calldata sellOrders, LibSignature.Signature[] calldata signatures, address[] calldata takers, uint128[] calldata erc1155FillAmounts, bytes[] calldata callbackData, bool revertIfIncomplete ) external payable returns (bool[] memory successes); /// @dev Matches a pair of complementary orders that have /// a non-negative spread. Each order is filled at /// their respective price, and the matcher receives /// a profit denominated in the ERC20 token. /// @param sellOrder Order selling an ERC1155 asset. /// @param buyOrder Order buying an ERC1155 asset. /// @param sellOrderSignature Signature for the sell order. /// @param buyOrderSignature Signature for the buy order. /// @return profit The amount of profit earned by the caller /// of this function (denominated in the ERC20 token /// of the matched orders). function matchSharedERC1155Orders( LibNFTOrder.ERC1155SellOrder calldata sellOrder, LibNFTOrder.ERC1155BuyOrder calldata buyOrder, LibSignature.Signature calldata sellOrderSignature, LibSignature.Signature calldata buyOrderSignature ) external returns (uint256 profit); /// @dev Matches pairs of complementary orders that have /// non-negative spreads. Each order is filled at /// their respective price, and the matcher receives /// a profit denominated in the ERC20 token. /// @param sellOrders Orders selling ERC1155 assets. /// @param buyOrders Orders buying ERC1155 assets. /// @param sellOrderSignatures Signatures for the sell orders. /// @param buyOrderSignatures Signatures for the buy orders. /// @return profits The amount of profit earned by the caller /// of this function for each pair of matched orders /// (denominated in the ERC20 token of the order pair). /// @return successes An array of booleans corresponding to /// whether each pair of orders was successfully matched. function batchMatchSharedERC1155Orders( LibNFTOrder.ERC1155SellOrder[] calldata sellOrders, LibNFTOrder.ERC1155BuyOrder[] calldata buyOrders, LibSignature.Signature[] calldata sellOrderSignatures, LibSignature.Signature[] calldata buyOrderSignatures ) external returns (uint256[] memory profits, bool[] memory successes); } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2020 ZeroEx Intl. 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. */ pragma solidity ^0.8.13; /// @dev Common storage helpers library LibStorage { /// @dev What to bit-shift a storage ID by to get its slot. /// This gives us a maximum of 2**128 inline fields in each bucket. uint256 constant STORAGE_ID_PROXY = 1 << 128; uint256 constant STORAGE_ID_SIMPLE_FUNCTION_REGISTRY = 2 << 128; uint256 constant STORAGE_ID_OWNABLE = 3 << 128; uint256 constant STORAGE_ID_COMMON_NFT_ORDERS = 4 << 128; uint256 constant STORAGE_ID_ERC721_ORDERS = 5 << 128; uint256 constant STORAGE_ID_ERC1155_ORDERS = 6 << 128; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2021 ZeroEx Intl. 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. */ pragma solidity ^0.8.13; interface IPropertyValidator { /// @dev Checks that the given ERC721/ERC1155 asset satisfies the properties encoded in `propertyData`. /// Should revert if the asset does not satisfy the specified properties. /// @param tokenAddress The ERC721/ERC1155 token contract address. /// @param tokenId The ERC721/ERC1155 tokenId of the asset to check. /// @param propertyData Encoded properties or auxiliary data needed to perform the check. function validateProperty(address tokenAddress, uint256 tokenId, bytes calldata propertyData) external view; } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2020 ZeroEx Intl. 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. */ pragma solidity ^0.8.13; /// @dev EIP712 helpers for features. abstract contract FixinEIP712 { bytes32 private constant DOMAIN = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); bytes32 private constant NAME = keccak256("ElementEx"); bytes32 private constant VERSION = keccak256("1.0.0"); uint256 private immutable CHAIN_ID; constructor() { uint256 chainId; assembly { chainId := chainid() } CHAIN_ID = chainId; } function _getEIP712Hash(bytes32 structHash) internal view returns (bytes32) { return keccak256(abi.encodePacked(hex"1901", keccak256(abi.encode(DOMAIN, NAME, VERSION, CHAIN_ID, address(this))), structHash)); } } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2020 ZeroEx Intl. 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. */ pragma solidity ^0.8.13; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; /// @dev Helpers for moving tokens around. abstract contract FixinTokenSpender { // Mask of the lower 20 bytes of a bytes32. uint256 constant private ADDRESS_MASK = 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff; /// @dev Transfers ERC20 tokens from `owner` to `to`. /// @param token The token to spend. /// @param owner The owner of the tokens. /// @param to The recipient of the tokens. /// @param amount The amount of `token` to transfer. function _transferERC20TokensFrom(IERC20 token, address owner, address to, uint256 amount) internal { uint256 success; assembly { let ptr := mload(0x40) // free memory pointer // selector for transferFrom(address,address,uint256) mstore(ptr, 0x23b872dd00000000000000000000000000000000000000000000000000000000) mstore(add(ptr, 0x04), and(owner, ADDRESS_MASK)) mstore(add(ptr, 0x24), and(to, ADDRESS_MASK)) mstore(add(ptr, 0x44), amount) success := call(gas(), and(token, ADDRESS_MASK), 0, ptr, 0x64, ptr, 32) let rdsize := returndatasize() // Check for ERC20 success. ERC20 tokens should return a boolean, // but some don't. We accept 0-length return data as success, or at // least 32 bytes that starts with a 32-byte boolean true. success := and( success, // call itself succeeded or( iszero(rdsize), // no return data, or and( iszero(lt(rdsize, 32)), // at least 32 bytes eq(mload(ptr), 1) // starts with uint256(1) ) ) ) } require(success != 0, "_transferERC20/TRANSFER_FAILED"); } /// @dev Transfers ERC20 tokens from ourselves to `to`. /// @param token The token to spend. /// @param to The recipient of the tokens. /// @param amount The amount of `token` to transfer. function _transferERC20Tokens(IERC20 token, address to, uint256 amount) internal { uint256 success; assembly { let ptr := mload(0x40) // free memory pointer // selector for transfer(address,uint256) mstore(ptr, 0xa9059cbb00000000000000000000000000000000000000000000000000000000) mstore(add(ptr, 0x04), and(to, ADDRESS_MASK)) mstore(add(ptr, 0x24), amount) success := call(gas(), and(token, ADDRESS_MASK), 0, ptr, 0x44, ptr, 32) let rdsize := returndatasize() // Check for ERC20 success. ERC20 tokens should return a boolean, // but some don't. We accept 0-length return data as success, or at // least 32 bytes that starts with a 32-byte boolean true. success := and( success, // call itself succeeded or( iszero(rdsize), // no return data, or and( iszero(lt(rdsize, 32)), // at least 32 bytes eq(mload(ptr), 1) // starts with uint256(1) ) ) ) } require(success != 0, "_transferERC20/TRANSFER_FAILED"); } /// @dev Transfers some amount of ETH to the given recipient and /// reverts if the transfer fails. /// @param recipient The recipient of the ETH. /// @param amount The amount of ETH to transfer. function _transferEth(address payable recipient, uint256 amount) internal { if (amount > 0) { (bool success,) = recipient.call{value: amount}(""); require(success, "_transferEth/TRANSFER_FAILED"); } } /// @dev Gets the maximum amount of an ERC20 token `token` that can be /// pulled from `owner` by this address. /// @param token The token to spend. /// @param owner The owner of the tokens. /// @return amount The amount of tokens that can be pulled. function _getSpendableERC20BalanceOf(IERC20 token, address owner) internal view returns (uint256) { return Math.min(token.allowance(owner, address(this)), token.balanceOf(owner)); } } // SPDX-License-Identifier: Apache-2.0 /* Copyright 2022 Element.Market 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. */ pragma solidity ^0.8.13; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IEtherToken is IERC20 { /// @dev Wrap ether. function deposit() external payable; /// @dev Unwrap ether. function withdraw(uint256 amount) external; } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2021 ZeroEx Intl. 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. */ pragma solidity ^0.8.13; interface IFeeRecipient { /// @dev A callback function invoked in the ERC721Feature for each ERC721 /// order fee that get paid. Integrators can make use of this callback /// to implement arbitrary fee-handling logic, e.g. splitting the fee /// between multiple parties. /// @param tokenAddress The address of the token in which the received fee is /// denominated. `0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE` indicates /// that the fee was paid in the native token (e.g. ETH). /// @param amount The amount of the given token received. /// @param feeData Arbitrary data encoded in the `Fee` used by this callback. /// @return success The selector of this function (0x0190805e), /// indicating that the callback succeeded. function receiveZeroExFeeCallback(address tokenAddress, uint256 amount, bytes calldata feeData) external returns (bytes4 success); } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2021 ZeroEx Intl. 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. */ pragma solidity ^0.8.13; interface ITakerCallback { /// @dev A taker callback function invoked in ERC721OrdersFeature and /// ERC1155OrdersFeature between the maker -> taker transfer and /// the taker -> maker transfer. /// @param orderHash The hash of the order being filled when this /// callback is invoked. /// @param data Arbitrary data used by this callback. /// @return success The selector of this function, /// indicating that the callback succeeded. function zeroExTakerCallback(bytes32 orderHash, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @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. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2021 ZeroEx Intl. 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. */ pragma solidity ^0.8.13; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../libs/LibNFTOrder.sol"; interface IERC1155OrdersEvent { /// @dev Emitted whenever an `ERC1155SellOrder` is filled. /// @param maker The maker of the order. /// @param taker The taker of the order. /// @param erc20Token (96bit ERC20FillAmount + 160bit ERC20TokenAddress). /// @param erc1155Token (96bit ERC1155TokenId + 160bit ERC1155TokenAddress). /// @param erc1155FillAmount The amount of ERC1155 asset filled. event ERC1155SellOrderFilled( address maker, address taker, uint256 erc20Token, uint256 erc1155Token, uint128 erc1155FillAmount, bytes32 orderHash ); /// @dev Emitted whenever an `ERC1155BuyOrder` is filled. /// @param maker The maker of the order. /// @param taker The taker of the order. /// @param erc20Token (96bit ERC20FillAmount + 160bit ERC20TokenAddress). /// @param erc1155Token (96bit ERC1155TokenId + 160bit ERC1155TokenAddress). /// @param erc1155FillAmount The amount of ERC1155 asset filled. event ERC1155BuyOrderFilled( address maker, address taker, uint256 erc20Token, uint256 erc1155Token, uint128 erc1155FillAmount, bytes32 orderHash ); /// @dev Emitted when an `ERC1155SellOrder` is pre-signed. /// Contains all the fields of the order. event ERC1155SellOrderPreSigned( address maker, address taker, uint256 expiry, uint256 nonce, IERC20 erc20Token, uint256 erc20TokenAmount, LibNFTOrder.Fee[] fees, address erc1155Token, uint256 erc1155TokenId, uint128 erc1155TokenAmount ); /// @dev Emitted when an `ERC1155BuyOrder` is pre-signed. /// Contains all the fields of the order. event ERC1155BuyOrderPreSigned( address maker, address taker, uint256 expiry, uint256 nonce, IERC20 erc20Token, uint256 erc20TokenAmount, LibNFTOrder.Fee[] fees, address erc1155Token, uint256 erc1155TokenId, LibNFTOrder.Property[] erc1155TokenProperties, uint128 erc1155TokenAmount ); /// @dev Emitted whenever an `ERC1155Order` is cancelled. /// @param maker The maker of the order. /// @param nonce The nonce of the order that was cancelled. event ERC1155OrderCancelled(address maker, uint256 nonce); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
Matches a pair of complementary orders that have a non-negative spread. Each order is filled at their respective price, and the matcher receives a profit denominated in the ERC20 token. sellOrder Order selling an ERC1155 asset. buyOrder Order buying an ERC1155 asset. sellOrderSignature Signature for the sell order. buyOrderSignature Signature for the buy order. return profit The amount of profit earned by the caller of this function (denominated in the ERC20 token of the matched orders). The ERC1155 tokens must match Reset sellOrder.erc20TokenAmount Reset buyOrder.erc20TokenAmount The buyer must be willing to pay at least the amount that the seller is asking. The sell order specifies ETH, while the buy order specifies WETH. The orders are still compatible with one another, but we'll have to unwrap the WETH on behalf of the buyer. Step 1: Transfer WETH from the buyer to the EP. Note that we transfer `buyOrder.erc20TokenAmount`, which is the amount the buyer signaled they are willing to pay for the ERC1155 asset, which may be more than the seller's ask. Step 2: Unwrap the WETH into ETH. We unwrap the entire `buyOrder.erc20TokenAmount`. The ETH will be used for three purposes: - To pay the seller - To pay fees for the sell order - Any remaining ETH will be sent to `msg.sender` as profit. Step 3: Pay the seller (in ETH). Step 4: Pay fees for the buy order. Note that these are paid in _WETH_ by the _buyer_. By signing the buy order, the buyer signals that they are willing to spend a total of `erc20TokenAmount` _plus_ fees, all denominated in the `erc20Token`, which in this case is WETH. Step 5: Pay fees for the sell order. The `erc20Token` of the sell order is ETH, so the fees are paid out in ETH. There should be `spread` wei of ETH remaining in the EP at this point, which we will use ETH to pay the sell order fees. Step 6: The spread must be enough to cover the sell order fees. If not, either `_payFees` will have reverted, or we have spent ETH that was in the EP before this `matchSharedERC1155Orders` call, which we disallow. ERC20 tokens must match Step 4: The spread must be enough to cover the sell order fees. If not, `_payFees` will have taken more tokens from the buyer than they had agreed to in the buy order, in which case we revert here.
function matchSharedERC1155Orders( LibNFTOrder.ERC1155SellOrder memory sellOrder, LibNFTOrder.ERC1155BuyOrder memory buyOrder, LibSignature.Signature memory sellOrderSignature, LibSignature.Signature memory buyOrderSignature ) public override returns (uint256 profit) { if (sellOrder.erc1155Token != buyOrder.erc1155Token) { revert("ERC1155_TOKEN_MISMATCH_ERROR"); } LibNFTOrder.NFTSellOrder memory sellNFTOrder = sellOrder.asNFTSellOrder(); LibNFTOrder.NFTBuyOrder memory buyNFTOrder = buyOrder.asNFTBuyOrder(); LibNFTOrder.OrderInfo memory sellOrderInfo = _getOrderInfo(sellNFTOrder); LibNFTOrder.OrderInfo memory buyOrderInfo = _getOrderInfo(buyNFTOrder); bool isEnglishAuction = (sellOrder.expiry >> 252 == 2); if (isEnglishAuction) { require( sellOrderInfo.orderAmount == sellOrderInfo.remainingAmount && sellOrderInfo.orderAmount == buyOrderInfo.orderAmount && sellOrderInfo.orderAmount == buyOrderInfo.remainingAmount, "UNMATCH_ORDER_AMOUNT" ); } _validateSellOrder( sellNFTOrder, sellOrderSignature, sellOrderInfo, buyOrder.maker ); _validateBuyOrder( buyNFTOrder, buyOrderSignature, buyOrderInfo, sellOrder.maker, sellOrder.erc1155TokenId ); sellOrderInfo.remainingAmount : buyOrderInfo.remainingAmount; if (erc1155FillAmount != sellOrderInfo.orderAmount) { sellOrder.erc20TokenAmount = _ceilDiv( sellOrder.erc20TokenAmount * erc1155FillAmount, sellOrderInfo.orderAmount ); } if (erc1155FillAmount != buyOrderInfo.orderAmount) { buyOrder.erc20TokenAmount = buyOrder.erc20TokenAmount * erc1155FillAmount / buyOrderInfo.orderAmount; } if (isEnglishAuction) { _resetEnglishAuctionTokenAmountAndFees( sellNFTOrder, buyOrder.erc20TokenAmount, erc1155FillAmount, sellOrderInfo.orderAmount ); } _updateOrderState(buyNFTOrder.asNFTSellOrder(), buyOrderInfo.orderHash, erc1155FillAmount); if (buyOrder.erc20TokenAmount < sellOrder.erc20TokenAmount) { revert("NEGATIVE_SPREAD_ERROR"); } address(sellOrder.erc1155Token), sellOrder.maker, buyOrder.maker, sellOrder.erc1155TokenId, erc1155FillAmount ); address(sellOrder.erc20Token) == NATIVE_TOKEN_ADDRESS && buyOrder.erc20Token == WETH ) { _transferERC20TokensFrom( WETH, buyOrder.maker, address(this), buyOrder.erc20TokenAmount ); WETH.withdraw(buyOrder.erc20TokenAmount); _transferEth(payable(sellOrder.maker), sellOrder.erc20TokenAmount); _payFees( buyNFTOrder.asNFTSellOrder(), erc1155FillAmount, buyOrderInfo.orderAmount, ); uint256 sellOrderFees = _payFees( sellNFTOrder, erc1155FillAmount, sellOrderInfo.orderAmount, ); if (spread < sellOrderFees) { revert("SELL_ORDER_FEES_EXCEED_SPREAD"); } if (profit > 0) { _transferEth(payable(msg.sender), profit); } if (sellOrder.erc20Token != buyOrder.erc20Token) { revert("ERC20_TOKEN_MISMATCH"); } buyOrder.erc20Token, buyOrder.maker, sellOrder.maker, sellOrder.erc20TokenAmount ); buyNFTOrder.asNFTSellOrder(), erc1155FillAmount, buyOrderInfo.orderAmount, ); sellNFTOrder, erc1155FillAmount, sellOrderInfo.orderAmount, ); if (spread < sellOrderFees) { revert("SELL_ORDER_FEES_EXCEED_SPREAD"); } if (profit > 0) { _transferERC20TokensFrom( buyOrder.erc20Token, buyOrder.maker, msg.sender, profit ); } } _emitEventSellOrderFilled( sellOrder, erc1155FillAmount, sellOrderInfo.orderHash ); _emitEventBuyOrderFilled( buyOrder, sellOrder.erc1155TokenId, erc1155FillAmount, buyOrderInfo.orderHash ); }
6,264,057
// Based on https://github.com/HausDAO/Molochv2.1 // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; // import "hardhat/console.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract 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 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; } } interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract Moloch is ReentrancyGuard { /*************** GLOBAL CONSTANTS ***************/ uint256 public periodDuration; // default = 17280 = 4.8 hours in seconds (5 periods per day) uint256 public votingPeriodLength; // default = 35 periods (7 days) uint256 public gracePeriodLength; // default = 35 periods (7 days) uint256 public proposalDeposit; // default = 10 ETH (~$1,000 worth of ETH at contract deployment) uint256 public dilutionBound; // default = 3 - maximum multiplier a YES voter will be obligated to pay in case of mass ragequit uint256 public processingReward; // default = 0.1 - amount of ETH to give to whoever processes a proposal uint256 public summoningTime; // needed to determine the current period bool private initialized; // internally tracks deployment under eip-1167 proxy pattern address public depositToken; // deposit token contract reference; default = wETH uint256 public spamPrevention; address public spamPreventionAddr; // can have multiple shamans mapping(address => bool) public shamans; // HARD-CODED LIMITS // These numbers are quite arbitrary; they are small enough to avoid overflows when doing calculations // with periods or shares, yet big enough to not limit reasonable use cases. uint256 constant MAX_VOTING_PERIOD_LENGTH = 10**18; // maximum length of voting period uint256 constant MAX_GRACE_PERIOD_LENGTH = 10**18; // maximum length of grace period uint256 constant MAX_DILUTION_BOUND = 10**18; // maximum dilution bound uint256 constant MAX_NUMBER_OF_SHARES_AND_LOOT = 10**18; // maximum number of shares that can be minted uint256 constant MAX_TOKEN_WHITELIST_COUNT = 400; // maximum number of whitelisted tokens uint256 constant MAX_TOKEN_GUILDBANK_COUNT = 200; // maximum number of tokens with non-zero balance in guildbank // *************** // EVENTS // *************** event SummonComplete( address indexed summoner, address[] tokens, uint256 summoningTime, uint256 periodDuration, uint256 votingPeriodLength, uint256 gracePeriodLength, uint256 proposalDeposit, uint256 dilutionBound, uint256 processingReward ); event SubmitProposal( address indexed applicant, uint256 sharesRequested, uint256 lootRequested, uint256 tributeOffered, address tributeToken, uint256 paymentRequested, address paymentToken, string details, bool[6] flags, uint256 proposalId, address indexed delegateKey, address indexed memberAddress ); event SponsorProposal( address indexed delegateKey, address indexed memberAddress, uint256 proposalId, uint256 proposalIndex, uint256 startingPeriod ); event SubmitVote( uint256 proposalId, uint256 indexed proposalIndex, address indexed delegateKey, address indexed memberAddress, uint8 uintVote ); event ProcessProposal( uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass ); event ProcessWhitelistProposal( uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass ); event ProcessGuildKickProposal( uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass ); event Ragequit( address indexed memberAddress, uint256 sharesToBurn, uint256 lootToBurn ); event TokensCollected(address indexed token, uint256 amountToCollect); event CancelProposal(uint256 indexed proposalId, address applicantAddress); event UpdateDelegateKey( address indexed memberAddress, address newDelegateKey ); event Withdraw( address indexed memberAddress, address token, uint256 amount ); event Shaman( address indexed memberAddress, uint256 shares, uint256 loot, bool mint ); event SetSpamPrevention(address spamPreventionAddr, uint256 spamPrevention); event SetShaman(address indexed shaman, bool isEnabled); event SetConfig( uint256 periodDuration, uint256 votingPeriodLength, uint256 gracePeriodLength, uint256 proposalDeposit, uint256 dilutionBound, uint256 processingReward ); // ******************* // INTERNAL ACCOUNTING // ******************* uint256 public proposalCount = 0; // total proposals submitted uint256 public totalShares = 0; // total shares across all members uint256 public totalLoot = 0; // total loot across all members uint256 public totalGuildBankTokens = 0; // total tokens with non-zero balance in guild bank address public constant GUILD = address(0xdead); address public constant ESCROW = address(0xbeef); address public constant TOTAL = address(0xbabe); mapping(address => mapping(address => uint256)) public userTokenBalances; // userTokenBalances[userAddress][tokenAddress] enum Vote { Null, // default value, counted as abstention Yes, No } struct Member { address delegateKey; // the key responsible for submitting proposals and voting - defaults to member address unless updated uint256 shares; // the # of voting shares assigned to this member uint256 loot; // the loot amount available to this member (combined with shares on ragequit) bool exists; // always true once a member has been created uint256 highestIndexYesVote; // highest proposal index # on which the member voted YES uint256 jailed; // set to proposalIndex of a passing guild kick proposal for this member, prevents voting on and sponsoring proposals } struct Proposal { address applicant; // the applicant who wishes to become a member - this key will be used for withdrawals (doubles as guild kick target for gkick proposals) address proposer; // the account that submitted the proposal (can be non-member) address sponsor; // the member that sponsored the proposal (moving it into the queue) uint256 sharesRequested; // the # of shares the applicant is requesting uint256 lootRequested; // the amount of loot the applicant is requesting uint256 tributeOffered; // amount of tokens offered as tribute address tributeToken; // tribute token contract reference uint256 paymentRequested; // amount of tokens requested as payment address paymentToken; // payment token contract reference uint256 startingPeriod; // the period in which voting can start for this proposal uint256 yesVotes; // the total number of YES votes for this proposal uint256 noVotes; // the total number of NO votes for this proposal bool[6] flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick] string details; // proposal details - could be IPFS hash, plaintext, or JSON uint256 maxTotalSharesAndLootAtYesVote; // the maximum # of total shares encountered at a yes vote on this proposal } mapping(uint256 => mapping(address => Vote)) voteHistory; // maps voting decisions on proposals proposal => member => voted mapping(address => bool) public tokenWhitelist; address[] public approvedTokens; mapping(address => bool) public proposedToWhitelist; mapping(address => bool) public proposedToKick; mapping(address => Member) public members; mapping(address => address) public memberAddressByDelegateKey; // TODO: whats this for? address[] public memberList; mapping(uint256 => Proposal) public proposals; uint256[] public proposalQueue; modifier onlyMember() { require( members[msg.sender].shares > 0 || members[msg.sender].loot > 0, "not a member" ); _; } modifier onlyShareholder() { require(members[msg.sender].shares > 0, "not a shareholder"); _; } modifier onlyDelegate() { require( members[memberAddressByDelegateKey[msg.sender]].shares > 0, "not a delegate" ); _; } modifier onlyDelegateOrShaman() { require( members[memberAddressByDelegateKey[msg.sender]].shares > 0 || shamans[msg.sender], "!delegate || !shaman" ); _; } modifier onlyShaman() { require(shamans[msg.sender], "!shaman"); _; } function setShaman(address _shaman, bool _enable) public onlyShaman { shamans[_shaman] = _enable; emit SetShaman(_shaman, _enable); } function setConfig(address _spamPreventionAddr, uint256 _spamPrevention) public onlyShaman { spamPreventionAddr = _spamPreventionAddr; spamPrevention = _spamPrevention; emit SetSpamPrevention(_spamPreventionAddr, _spamPrevention); } // allow member to do this if no active props function setSharesLoot( address[] memory _applicants, uint256[] memory _applicantShares, uint256[] memory _applicantLoot, bool mint ) public onlyShaman { require(_applicants.length == _applicantShares.length, "mismatch"); require(_applicants.length == _applicantLoot.length, "mismatch"); for (uint256 i = 0; i < _applicants.length; i++) { _setSharesLoot( _applicants[i], _applicantShares[i], _applicantLoot[i], mint ); // TODO: maybe emit only once in the future emit Shaman( _applicants[i], _applicantShares[i], _applicantLoot[i], mint ); } } function setSingleSharesLoot( address _applicant, uint256 _applicantShares, uint256 _applicantLoot, bool mint ) public onlyShaman { _setSharesLoot( _applicant, _applicantShares, _applicantLoot, mint ); // TODO: maybe emit only once in the future emit Shaman(_applicant, _applicantShares, _applicantLoot, mint); } function _setSharesLoot( address applicant, uint256 shares, uint256 loot, bool mint ) internal { if (mint) { if (members[applicant].exists) { members[applicant].shares = members[applicant].shares + shares; members[applicant].loot = members[applicant].loot + loot; // the applicant is a new member, create a new record for them } else { // if the applicant address is already taken by a member's delegateKey, reset it to their member address if (members[memberAddressByDelegateKey[applicant]].exists) { address memberToOverride = memberAddressByDelegateKey[ applicant ]; memberAddressByDelegateKey[ memberToOverride ] = memberToOverride; members[memberToOverride].delegateKey = memberToOverride; } // use applicant address as delegateKey by default members[applicant] = Member( applicant, shares, loot, true, 0, 0 ); memberAddressByDelegateKey[applicant] = applicant; } totalShares = totalShares + shares; totalLoot = totalLoot + loot; } else { members[applicant].shares = members[applicant].shares - shares; members[applicant].loot = members[applicant].loot - loot; totalShares = totalShares - shares; totalLoot = totalLoot - loot; } require( (totalShares + shares + loot) <= MAX_NUMBER_OF_SHARES_AND_LOOT, "too many shares requested" ); } function _setConfig( uint256 _periodDuration, uint256 _votingPeriodLength, uint256 _gracePeriodLength, uint256 _proposalDeposit, uint256 _dilutionBound, uint256 _processingReward ) internal { require(_periodDuration > 0, "_periodDuration cannot be 0"); require(_votingPeriodLength > 0, "_votingPeriodLength cannot be 0"); require( _votingPeriodLength <= MAX_VOTING_PERIOD_LENGTH, "_votingPeriodLength exceeds limit" ); require( _gracePeriodLength <= MAX_GRACE_PERIOD_LENGTH, "_gracePeriodLength exceeds limit" ); require(_dilutionBound > 0, "_dilutionBound cannot be 0"); require( _dilutionBound <= MAX_DILUTION_BOUND, "_dilutionBound exceeds limit" ); require( _proposalDeposit >= _processingReward, "_proposalDeposit cannot be smaller than _processingReward" ); periodDuration = _periodDuration; votingPeriodLength = _votingPeriodLength; gracePeriodLength = _gracePeriodLength; proposalDeposit = _proposalDeposit; dilutionBound = _dilutionBound; processingReward = _processingReward; } function init( // address _summoner, address _shaman, address[] calldata _approvedTokens, uint256 _periodDuration, uint256 _votingPeriodLength, uint256 _gracePeriodLength, uint256 _proposalDeposit, uint256 _dilutionBound, uint256 _processingReward ) external { require(!initialized, "initialized"); require(_approvedTokens.length > 0, "need at least one approved token"); require( _approvedTokens.length <= MAX_TOKEN_WHITELIST_COUNT, "too many tokens" ); _setConfig( _periodDuration, _votingPeriodLength, _gracePeriodLength, _proposalDeposit, _dilutionBound, _processingReward ); summoningTime = block.timestamp; initialized = true; depositToken = _approvedTokens[0]; shamans[_shaman] = true; require( totalShares <= MAX_NUMBER_OF_SHARES_AND_LOOT, "too many shares requested" ); for (uint256 i = 0; i < _approvedTokens.length; i++) { require( _approvedTokens[i] != address(0), "_approvedToken cannot be 0" ); require( !tokenWhitelist[_approvedTokens[i]], "duplicate approved token" ); tokenWhitelist[_approvedTokens[i]] = true; approvedTokens.push(_approvedTokens[i]); } } /***************** PROPOSAL FUNCTIONS *****************/ function submitProposal( address applicant, uint256 sharesRequested, uint256 lootRequested, uint256 tributeOffered, address tributeToken, uint256 paymentRequested, address paymentToken, string memory details ) public nonReentrant returns (uint256 proposalId) { require( (sharesRequested + lootRequested) <= MAX_NUMBER_OF_SHARES_AND_LOOT, "too many shares requested" ); require( tokenWhitelist[tributeToken], "tributeToken is not whitelisted" ); require(tokenWhitelist[paymentToken], "payment is not whitelisted"); require(applicant != address(0), "applicant cannot be 0"); require( applicant != GUILD && applicant != ESCROW && applicant != TOTAL, "applicant address cannot be reserved" ); require( members[applicant].jailed == 0, "proposal applicant must not be jailed" ); if (tributeOffered > 0 && userTokenBalances[GUILD][tributeToken] == 0) { require( totalGuildBankTokens < MAX_TOKEN_GUILDBANK_COUNT, "cannot submit more tribute proposals for new tokens - guildbank is full" ); } // collect tribute from proposer and store it in the Moloch until the proposal is processed require( IERC20(tributeToken).transferFrom( msg.sender, address(this), tributeOffered ), "tribute token transfer failed" ); unsafeAddToBalance(ESCROW, tributeToken, tributeOffered); bool[6] memory flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick] _submitProposal( applicant, sharesRequested, lootRequested, tributeOffered, tributeToken, paymentRequested, paymentToken, details, flags ); return proposalCount - 1; // return proposalId - contracts calling submit might want it } function submitWhitelistProposal( address tokenToWhitelist, string memory details ) public nonReentrant returns (uint256 proposalId) { require(tokenToWhitelist != address(0), "must provide token address"); require( !tokenWhitelist[tokenToWhitelist], "cannot already have whitelisted the token" ); require( approvedTokens.length < MAX_TOKEN_WHITELIST_COUNT, "cannot submit more whitelist proposals" ); bool[6] memory flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick] flags[4] = true; // whitelist _submitProposal( address(0), 0, 0, 0, tokenToWhitelist, 0, address(0), details, flags ); return proposalCount - 1; } function submitGuildKickProposal( address memberToKick, string memory details ) public nonReentrant returns (uint256 proposalId) { Member memory member = members[memberToKick]; require( member.shares > 0 || member.loot > 0, "member must have at least one share or one loot" ); require( members[memberToKick].jailed == 0, "member must not already be jailed" ); bool[6] memory flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick] flags[5] = true; // guild kick _submitProposal( memberToKick, 0, 0, 0, address(0), 0, address(0), details, flags ); return proposalCount - 1; } function _submitProposal( address applicant, uint256 sharesRequested, uint256 lootRequested, uint256 tributeOffered, address tributeToken, uint256 paymentRequested, address paymentToken, string memory details, bool[6] memory flags ) internal { require(msg.value >= spamPrevention, "spam prevention on"); if (spamPrevention > 0 && !shamans[msg.sender]) { (bool success, ) = spamPreventionAddr.call{value: msg.value}(""); require(success, "failed"); } Proposal memory proposal = Proposal({ applicant: applicant, proposer: msg.sender, sponsor: address(0), sharesRequested: sharesRequested, lootRequested: lootRequested, tributeOffered: tributeOffered, tributeToken: tributeToken, paymentRequested: paymentRequested, paymentToken: paymentToken, startingPeriod: 0, yesVotes: 0, noVotes: 0, flags: flags, details: details, maxTotalSharesAndLootAtYesVote: 0 }); proposals[proposalCount] = proposal; address memberAddress = memberAddressByDelegateKey[msg.sender]; // NOTE: argument order matters, avoid stack too deep emit SubmitProposal( applicant, sharesRequested, lootRequested, tributeOffered, tributeToken, paymentRequested, paymentToken, details, flags, proposalCount, msg.sender, memberAddress ); proposalCount += 1; } function sponsorProposal(uint256 proposalId) public nonReentrant onlyDelegate { // collect proposal deposit from sponsor and store it in the Moloch until the proposal is processed require( IERC20(depositToken).transferFrom( msg.sender, address(this), proposalDeposit ), "proposal deposit token transfer failed" ); unsafeAddToBalance(ESCROW, depositToken, proposalDeposit); Proposal storage proposal = proposals[proposalId]; require( proposal.proposer != address(0), "proposal must have been proposed" ); require(!proposal.flags[0], "proposal has already been sponsored"); require(!proposal.flags[3], "proposal has been cancelled"); require( members[proposal.applicant].jailed == 0, "proposal applicant must not be jailed" ); if ( proposal.tributeOffered > 0 && userTokenBalances[GUILD][proposal.tributeToken] == 0 ) { require( totalGuildBankTokens < MAX_TOKEN_GUILDBANK_COUNT, "cannot sponsor more tribute proposals for new tokens - guildbank is full" ); } // whitelist proposal if (proposal.flags[4]) { require( !tokenWhitelist[address(proposal.tributeToken)], "cannot already have whitelisted the token" ); require( !proposedToWhitelist[address(proposal.tributeToken)], "already proposed to whitelist" ); require( approvedTokens.length < MAX_TOKEN_WHITELIST_COUNT, "cannot sponsor more whitelist proposals" ); proposedToWhitelist[address(proposal.tributeToken)] = true; // guild kick proposal } else if (proposal.flags[5]) { require( !proposedToKick[proposal.applicant], "already proposed to kick" ); proposedToKick[proposal.applicant] = true; } // compute startingPeriod for proposal uint256 startingPeriod = max( getCurrentPeriod(), proposalQueue.length == 0 ? 0 : proposals[proposalQueue[proposalQueue.length - 1]] .startingPeriod ) + 1; proposal.startingPeriod = startingPeriod; address memberAddress = memberAddressByDelegateKey[msg.sender]; proposal.sponsor = memberAddress; proposal.flags[0] = true; // sponsored // append proposal to the queue proposalQueue.push(proposalId); emit SponsorProposal( msg.sender, memberAddress, proposalId, proposalQueue.length - 1, startingPeriod ); } // NOTE: In MolochV2 proposalIndex !== proposalId function submitVote(uint256 proposalIndex, uint8 uintVote) public nonReentrant onlyDelegate { address memberAddress = memberAddressByDelegateKey[msg.sender]; Member storage member = members[memberAddress]; require( proposalIndex < proposalQueue.length, "proposal does not exist" ); Proposal storage proposal = proposals[proposalQueue[proposalIndex]]; require(uintVote < 3, "must be less than 3"); Vote vote = Vote(uintVote); require( getCurrentPeriod() >= proposal.startingPeriod, "voting period has not started" ); require( !hasVotingPeriodExpired(proposal.startingPeriod), "proposal voting period has expired" ); require( voteHistory[proposalIndex][memberAddress] == Vote.Null, "member has already voted" ); require( vote == Vote.Yes || vote == Vote.No, "vote must be either Yes or No" ); voteHistory[proposalIndex][memberAddress] = vote; if (vote == Vote.Yes) { proposal.yesVotes = proposal.yesVotes + member.shares; // set highest index (latest) yes vote - must be processed for member to ragequit if (proposalIndex > member.highestIndexYesVote) { member.highestIndexYesVote = proposalIndex; } // set maximum of total shares encountered at a yes vote - used to bound dilution for yes voters if ( (totalShares + totalLoot) > proposal.maxTotalSharesAndLootAtYesVote ) { proposal.maxTotalSharesAndLootAtYesVote = totalShares + totalLoot; } } else if (vote == Vote.No) { proposal.noVotes = proposal.noVotes + member.shares; } // NOTE: subgraph indexes by proposalId not proposalIndex since proposalIndex isn't set untill it's been sponsored but proposal is created on submission emit SubmitVote( proposalQueue[proposalIndex], proposalIndex, msg.sender, memberAddress, uintVote ); } function processProposal(uint256 proposalIndex) public nonReentrant { _validateProposalForProcessing(proposalIndex); uint256 proposalId = proposalQueue[proposalIndex]; Proposal storage proposal = proposals[proposalId]; require( !proposal.flags[4] && !proposal.flags[5], "must be a standard proposal" ); proposal.flags[1] = true; // processed bool didPass = _didPass(proposalIndex); // Make the proposal fail if the new total number of shares and loot exceeds the limit if ( (totalShares + totalLoot + proposal.sharesRequested + proposal.lootRequested) > MAX_NUMBER_OF_SHARES_AND_LOOT ) { didPass = false; } // Make the proposal fail if it is requesting more tokens as payment than the available guild bank balance if ( proposal.paymentRequested > userTokenBalances[GUILD][proposal.paymentToken] ) { didPass = false; } // Make the proposal fail if it would result in too many tokens with non-zero balance in guild bank if ( proposal.tributeOffered > 0 && userTokenBalances[GUILD][proposal.tributeToken] == 0 && totalGuildBankTokens >= MAX_TOKEN_GUILDBANK_COUNT ) { didPass = false; } // PROPOSAL PASSED if (didPass) { proposal.flags[2] = true; // didPass _setSharesLoot( proposal.applicant, proposal.sharesRequested, proposal.lootRequested, true ); // if the proposal tribute is the first tokens of its kind to make it into the guild bank, increment total guild bank tokens if ( userTokenBalances[GUILD][proposal.tributeToken] == 0 && proposal.tributeOffered > 0 ) { totalGuildBankTokens += 1; } unsafeInternalTransfer( ESCROW, GUILD, proposal.tributeToken, proposal.tributeOffered ); unsafeInternalTransfer( GUILD, proposal.applicant, proposal.paymentToken, proposal.paymentRequested ); // if the proposal spends 100% of guild bank balance for a token, decrement total guild bank tokens if ( userTokenBalances[GUILD][proposal.paymentToken] == 0 && proposal.paymentRequested > 0 ) { totalGuildBankTokens -= 1; } // PROPOSAL FAILED } else { // return all tokens to the proposer (not the applicant, because funds come from proposer) unsafeInternalTransfer( ESCROW, proposal.proposer, proposal.tributeToken, proposal.tributeOffered ); } _returnDeposit(proposal.sponsor); emit ProcessProposal(proposalIndex, proposalId, didPass); } function processWhitelistProposal(uint256 proposalIndex) public nonReentrant { _validateProposalForProcessing(proposalIndex); uint256 proposalId = proposalQueue[proposalIndex]; Proposal storage proposal = proposals[proposalId]; require(proposal.flags[4], "must be a whitelist proposal"); proposal.flags[1] = true; // processed bool didPass = _didPass(proposalIndex); if (approvedTokens.length >= MAX_TOKEN_WHITELIST_COUNT) { didPass = false; } if (didPass) { proposal.flags[2] = true; // didPass tokenWhitelist[address(proposal.tributeToken)] = true; approvedTokens.push(proposal.tributeToken); } proposedToWhitelist[address(proposal.tributeToken)] = false; _returnDeposit(proposal.sponsor); emit ProcessWhitelistProposal(proposalIndex, proposalId, didPass); } function processGuildKickProposal(uint256 proposalIndex) public nonReentrant { _validateProposalForProcessing(proposalIndex); uint256 proposalId = proposalQueue[proposalIndex]; Proposal storage proposal = proposals[proposalId]; require(proposal.flags[5], "must be a guild kick proposal"); proposal.flags[1] = true; // processed bool didPass = _didPass(proposalIndex); if (didPass) { proposal.flags[2] = true; // didPass Member storage member = members[proposal.applicant]; member.jailed = proposalIndex; // transfer shares to loot member.loot = member.loot + member.shares; totalShares = totalShares - member.shares; totalLoot = totalLoot + member.shares; member.shares = 0; // revoke all shares } proposedToKick[proposal.applicant] = false; _returnDeposit(proposal.sponsor); emit ProcessGuildKickProposal(proposalIndex, proposalId, didPass); } function _didPass(uint256 proposalIndex) internal view returns (bool didPass) { Proposal memory proposal = proposals[proposalQueue[proposalIndex]]; didPass = proposal.yesVotes > proposal.noVotes; // Make the proposal fail if the dilutionBound is exceeded if ( (totalShares + totalLoot) * (dilutionBound) < proposal.maxTotalSharesAndLootAtYesVote ) { didPass = false; } // Make the proposal fail if the applicant is jailed // - for standard proposals, we don't want the applicant to get any shares/loot/payment // - for guild kick proposals, we should never be able to propose to kick a jailed member (or have two kick proposals active), so it doesn't matter if (members[proposal.applicant].jailed != 0) { didPass = false; } return didPass; } function _validateProposalForProcessing(uint256 proposalIndex) internal view { require( proposalIndex < proposalQueue.length, "proposal does not exist" ); Proposal memory proposal = proposals[proposalQueue[proposalIndex]]; require( getCurrentPeriod() >= (proposal.startingPeriod + votingPeriodLength + gracePeriodLength), "proposal is not ready to be processed" ); require( proposal.flags[1] == false, "proposal has already been processed" ); require( proposalIndex == 0 || proposals[proposalQueue[proposalIndex - 1]].flags[1], "previous proposal must be processed" ); } function _returnDeposit(address sponsor) internal { unsafeInternalTransfer( ESCROW, msg.sender, depositToken, processingReward ); unsafeInternalTransfer( ESCROW, sponsor, depositToken, proposalDeposit - processingReward ); } function ragequit(uint256 sharesToBurn, uint256 lootToBurn) public nonReentrant onlyMember { _ragequit(msg.sender, sharesToBurn, lootToBurn); } function _ragequit( address memberAddress, uint256 sharesToBurn, uint256 lootToBurn ) internal { uint256 initialTotalSharesAndLoot = totalShares + totalLoot; Member storage member = members[memberAddress]; require(member.shares >= sharesToBurn, "insufficient shares"); require(member.loot >= lootToBurn, "insufficient loot"); require( canRagequit(member.highestIndexYesVote), "cannot ragequit until highest index proposal member voted YES on is processed" ); uint256 sharesAndLootToBurn = sharesToBurn + lootToBurn; // burn shares and loot _setSharesLoot(memberAddress, sharesToBurn, lootToBurn, false); for (uint256 i = 0; i < approvedTokens.length; i++) { uint256 amountToRagequit = fairShare( userTokenBalances[GUILD][approvedTokens[i]], sharesAndLootToBurn, initialTotalSharesAndLoot ); if (amountToRagequit > 0) { // gas optimization to allow a higher maximum token limit // deliberately not using safemath here to keep overflows from preventing the function execution (which would break ragekicks) // if a token overflows, it is because the supply was artificially inflated to oblivion, so we probably don't care about it anyways userTokenBalances[GUILD][approvedTokens[i]] -= amountToRagequit; userTokenBalances[memberAddress][ approvedTokens[i] ] += amountToRagequit; } } emit Ragequit(memberAddress, sharesToBurn, lootToBurn); } function ragekick(address memberToKick) public nonReentrant { Member storage member = members[memberToKick]; require(member.jailed != 0, "member must be in jail"); require(member.loot > 0, "member must have some loot"); // note - should be impossible for jailed member to have shares require( canRagequit(member.highestIndexYesVote), "cannot ragequit until highest index proposal member voted YES on is processed" ); _ragequit(memberToKick, 0, member.loot); } function withdrawBalance(address token, uint256 amount) public nonReentrant { _withdrawBalance(token, amount); } function withdrawBalances( address[] memory tokens, uint256[] memory amounts, bool shouldWithdrawMax ) public nonReentrant { require( tokens.length == amounts.length, "tokens and amounts arrays must be matching lengths" ); for (uint256 i = 0; i < tokens.length; i++) { uint256 withdrawAmount = amounts[i]; if (shouldWithdrawMax) { // withdraw the maximum balance withdrawAmount = userTokenBalances[msg.sender][tokens[i]]; } _withdrawBalance(tokens[i], withdrawAmount); } } function _withdrawBalance(address token, uint256 amount) internal { require( userTokenBalances[msg.sender][token] >= amount, "insufficient balance" ); unsafeSubtractFromBalance(msg.sender, token, amount); require(IERC20(token).transfer(msg.sender, amount), "transfer failed"); emit Withdraw(msg.sender, token, amount); } function collectTokens(address token) public onlyDelegateOrShaman nonReentrant { uint256 amountToCollect = IERC20(token).balanceOf(address(this)) - userTokenBalances[TOTAL][token]; // only collect if 1) there are tokens to collect 2) token is whitelisted 3) token has non-zero balance require(amountToCollect > 0, "no tokens to collect"); require(tokenWhitelist[token], "token to collect must be whitelisted"); require( userTokenBalances[GUILD][token] > 0 || totalGuildBankTokens < MAX_TOKEN_GUILDBANK_COUNT, "token to collect must have non-zero guild bank balance" ); if (userTokenBalances[GUILD][token] == 0) { totalGuildBankTokens += 1; } unsafeAddToBalance(GUILD, token, amountToCollect); emit TokensCollected(token, amountToCollect); } // NOTE: requires that delegate key which sent the original proposal cancels, msg.sender == proposal.proposer function cancelProposal(uint256 proposalId) public nonReentrant { Proposal storage proposal = proposals[proposalId]; require(!proposal.flags[0], "proposal has already been sponsored"); require(!proposal.flags[3], "proposal has already been cancelled"); require( msg.sender == proposal.proposer, "solely the proposer can cancel" ); proposal.flags[3] = true; // cancelled unsafeInternalTransfer( ESCROW, proposal.proposer, proposal.tributeToken, proposal.tributeOffered ); emit CancelProposal(proposalId, msg.sender); } function updateDelegateKey(address newDelegateKey) public nonReentrant onlyShareholder { require(newDelegateKey != address(0), "newDelegateKey cannot be 0"); // skip checks if member is setting the delegate key to their member address if (newDelegateKey != msg.sender) { require( !members[newDelegateKey].exists, "cannot overwrite existing members" ); require( !members[memberAddressByDelegateKey[newDelegateKey]].exists, "cannot overwrite existing delegate keys" ); } Member storage member = members[msg.sender]; memberAddressByDelegateKey[member.delegateKey] = address(0); memberAddressByDelegateKey[newDelegateKey] = msg.sender; member.delegateKey = newDelegateKey; emit UpdateDelegateKey(msg.sender, newDelegateKey); } // can only ragequit if the latest proposal you voted YES on has been processed function canRagequit(uint256 highestIndexYesVote) public view returns (bool) { // TODO: fixed to allow ragequit before any proposals, write test if(proposalQueue.length == 0){ return true; } require( highestIndexYesVote < proposalQueue.length, "proposal does not exist" ); return proposals[proposalQueue[highestIndexYesVote]].flags[1]; } function hasVotingPeriodExpired(uint256 startingPeriod) public view returns (bool) { return getCurrentPeriod() >= (startingPeriod + votingPeriodLength); } /*************** GETTER FUNCTIONS ***************/ function max(uint256 x, uint256 y) internal pure returns (uint256) { return x >= y ? x : y; } function getCurrentPeriod() public view returns (uint256) { return (block.timestamp - summoningTime) / (periodDuration); } function getProposalQueueLength() public view returns (uint256) { return proposalQueue.length; } function getProposalFlags(uint256 proposalId) public view returns (bool[6] memory) { return proposals[proposalId].flags; } function getUserTokenBalance(address user, address token) public view returns (uint256) { return userTokenBalances[user][token]; } function getMemberProposalVote(address memberAddress, uint256 proposalIndex) public view returns (Vote) { require(members[memberAddress].exists, "member does not exist"); require( proposalIndex < proposalQueue.length, "proposal does not exist" ); return voteHistory[proposalIndex][memberAddress]; } function getTokenCount() public view returns (uint256) { return approvedTokens.length; } /*************** HELPER FUNCTIONS ***************/ function unsafeAddToBalance( address user, address token, uint256 amount ) internal { userTokenBalances[user][token] += amount; userTokenBalances[TOTAL][token] += amount; } function unsafeSubtractFromBalance( address user, address token, uint256 amount ) internal { userTokenBalances[user][token] -= amount; userTokenBalances[TOTAL][token] -= amount; } function unsafeInternalTransfer( address from, address to, address token, uint256 amount ) internal { unsafeSubtractFromBalance(from, token, amount); unsafeAddToBalance(to, token, amount); } function fairShare( uint256 balance, uint256 shares, uint256 _totalShares ) internal pure returns (uint256) { require(_totalShares != 0); if (balance == 0) { return 0; } uint256 prod = balance * shares; if (prod / balance == shares) { // no overflow in multiplication above? return prod / _totalShares; } return (balance / _totalShares) * shares; } } /* The MIT License (MIT) Copyright (c) 2018 Murray Software, LLC. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ contract CloneFactory { // implementation of eip-1167 - see https://eips.ethereum.org/EIPS/eip-1167 function createClone(address target) internal returns (address result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore( clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 ) mstore(add(clone, 0x14), targetBytes) mstore( add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) result := create(0, clone, 0x37) } } } contract MolochSummoner is CloneFactory { address public template; mapping(uint256 => address) public daos; uint256 public daoIdx = 0; // Moloch private moloch; // moloch contract constructor(address _template) { template = _template; } event SummonComplete( address indexed moloch, address _summoner, address _shaman, address[] tokens, uint256 summoningTime, uint256 periodDuration, uint256 votingPeriodLength, uint256 gracePeriodLength, uint256 proposalDeposit, uint256 dilutionBound, uint256 processingReward ); function summonMoloch( address _summoner, address _shaman, address[] memory _approvedTokens, uint256 _periodDuration, uint256 _votingPeriodLength, uint256 _gracePeriodLength, uint256 _proposalDeposit, uint256 _dilutionBound, uint256 _processingReward ) public returns (address) { Moloch moloch = Moloch(createClone(template)); moloch.init( // _summoner, _shaman, _approvedTokens, _periodDuration, _votingPeriodLength, _gracePeriodLength, _proposalDeposit, _dilutionBound, _processingReward ); daoIdx = daoIdx + 1; daos[daoIdx] = address(moloch); emit SummonComplete( address(moloch), _summoner, _shaman, _approvedTokens, block.timestamp, _periodDuration, _votingPeriodLength, _gracePeriodLength, _proposalDeposit, _dilutionBound, _processingReward ); return address(moloch); } }
Make the proposal fail if the new total number of shares and loot exceeds the limit PROPOSAL PASSED if the proposal tribute is the first tokens of its kind to make it into the guild bank, increment total guild bank tokens
function processProposal(uint256 proposalIndex) public nonReentrant { _validateProposalForProcessing(proposalIndex); uint256 proposalId = proposalQueue[proposalIndex]; Proposal storage proposal = proposals[proposalId]; require( !proposal.flags[4] && !proposal.flags[5], "must be a standard proposal" ); bool didPass = _didPass(proposalIndex); if ( (totalShares + totalLoot + proposal.sharesRequested + proposal.lootRequested) > MAX_NUMBER_OF_SHARES_AND_LOOT ) { didPass = false; } proposal.paymentRequested > userTokenBalances[GUILD][proposal.paymentToken] ) { didPass = false; } proposal.tributeOffered > 0 && userTokenBalances[GUILD][proposal.tributeToken] == 0 && totalGuildBankTokens >= MAX_TOKEN_GUILDBANK_COUNT ) { didPass = false; } if (didPass) { _setSharesLoot( proposal.applicant, proposal.sharesRequested, proposal.lootRequested, true ); if ( userTokenBalances[GUILD][proposal.tributeToken] == 0 && proposal.tributeOffered > 0 ) { totalGuildBankTokens += 1; } unsafeInternalTransfer( ESCROW, GUILD, proposal.tributeToken, proposal.tributeOffered ); unsafeInternalTransfer( GUILD, proposal.applicant, proposal.paymentToken, proposal.paymentRequested ); userTokenBalances[GUILD][proposal.paymentToken] == 0 && proposal.paymentRequested > 0 ) { totalGuildBankTokens -= 1; } ESCROW, proposal.proposer, proposal.tributeToken, proposal.tributeOffered ); } _returnDeposit(proposal.sponsor); emit ProcessProposal(proposalIndex, proposalId, didPass); }
32,963
/* Copyright 2019 Wanchain Foundation. 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. */ // _ _ _ // __ ____ _ _ __ ___| |__ __ _(_)_ __ __| | _____ __ // \ \ /\ / / _` | '_ \ / __| '_ \ / _` | | '_ \@/ _` |/ _ \ \ / / // \ V V / (_| | | | | (__| | | | (_| | | | | | (_| | __/\ V / // \_/\_/ \__,_|_| |_|\___|_| |_|\__,_|_|_| |_|\__,_|\___| \_/ // // pragma solidity ^0.4.26; pragma experimental ABIEncoderV2; import "../components/Halt.sol"; import "../components/ReentrancyGuard.sol"; import "./CrossStorage.sol"; // import "./lib/HTLCMintLib.sol"; // import "./lib/HTLCBurnLib.sol"; import "./lib/HTLCDebtLib.sol"; import "./lib/RapidityLib.sol"; contract CrossDelegate is CrossStorage, ReentrancyGuard, Halt { using SafeMath for uint; /** * * EVENTS * **/ /// @notice event of storeman group ID withdraw the original coin to receiver /// @param smgID ID of storemanGroup /// @param timeStamp timestamp of the withdraw /// @param receiver receiver address /// @param fee shadow coin of the fee which the storeman group pk got it event SmgWithdrawFeeLogger(bytes32 indexed smgID, uint timeStamp, address indexed receiver, uint fee); /** * * MODIFIERS * */ /// @dev Check valid value modifier onlyMeaningfulValue(uint value) { require(value != 0, "Value is null"); _; } /// @notice check the storeman group is ready /// @param smgID ID of storeman group modifier onlyReadySmg(bytes32 smgID) { uint8 status; uint startTime; uint endTime; (status,startTime,endTime) = storageData.smgAdminProxy.getStoremanGroupStatus(smgID); require(status == uint8(GroupStatus.ready) && now >= startTime && now <= endTime, "PK is not ready"); _; } // function _checkValue(uint value) private view { // require(value != 0, "Value is null"); // } // function _checkReadySmg(bytes32 smgID) private view { // uint8 status; // uint startTime; // uint endTime; // (,status,,,,,,,,startTime,endTime) = storageData.smgAdminProxy.getStoremanGroupConfig(smgID); // require(status == uint8(GroupStatus.ready) && now >= startTime && now <= endTime, "PK is not ready"); // } // function _checkUnregisteredSmg(bytes32 smgID) private view { // uint8 status; // (,status,,,,,,,,,) = storageData.smgAdminProxy.getStoremanGroupConfig(smgID); // require(status == uint8(GroupStatus.unregistered), "PK is not unregistered"); // } /** * * MANIPULATIONS * */ // /// @notice get the exist storeman group info // /// @param smgID ID of storeman group // /// @return curveID ID of elliptic curve // /// @return PK PK of storeman group // function acquireExistSmgInfo(bytes32 smgID) // private // view // returns (uint curveID, bytes memory PK) // { // uint origChainID; // (,,,origChainID,,curveID,,PK,,,) = storageData.smgAdminProxy.getStoremanGroupConfig(smgID); // require(origChainID != 0, "PK does not exist"); // return (curveID, PK); // } /// @notice check the storeman group is ready or not /// @param smgID ID of storeman group /// @return curveID ID of elliptic curve /// @return PK PK of storeman group function acquireReadySmgInfo(bytes32 smgID) private view returns (uint curveID, bytes memory PK) { uint8 status; uint startTime; uint endTime; (,status,,,,curveID,,PK,,startTime,endTime) = storageData.smgAdminProxy.getStoremanGroupConfig(smgID); require(status == uint8(GroupStatus.ready) && now >= startTime && now <= endTime, "PK is not ready"); return (curveID, PK); } /// @notice get the unregistered storeman group info /// @param smgID ID of storeman group /// @return curveID ID of elliptic curve /// @return PK PK of storeman group function acquireUnregisteredSmgInfo(bytes32 smgID) private view returns (uint curveID, bytes memory PK) { uint8 status; (,status,,,,curveID,,PK,,,) = storageData.smgAdminProxy.getStoremanGroupConfig(smgID); require(status == uint8(GroupStatus.unregistered), "PK is not unregistered"); } /* /// @notice request exchange RC20 token with WRC20 on wanchain /// @param xHash hash of HTLC random number /// @param smgID ID of storeman /// @param tokenPairID token pair ID of cross chain token /// @param value exchange value /// @param userAccount account of user, used to receive WRC20 token function userMintLock(bytes32 xHash, bytes32 smgID, uint tokenPairID, uint value, bytes userAccount) external payable notHalted nonReentrant onlyReadySmg(smgID) onlyMeaningfulValue(value) { HTLCMintLib.HTLCUserMintLockParams memory params = HTLCMintLib.HTLCUserMintLockParams({ xHash: xHash, smgID: smgID, tokenPairID: tokenPairID, value: value, lockedTime: lockedTime.mul(2), userShadowAccount: userAccount }); HTLCMintLib.userMintLock(storageData, params); } /// @notice request exchange RC20 token with WRC20 on wanchain /// @param xHash hash of HTLC random number /// @param smgID ID of storeman /// @param tokenPairID token pair ID of cross chain token /// @param value exchange value /// @param userAccount address of user, used to receive WRC20 token /// @param r signature /// @param s signature function smgMintLock(bytes32 xHash, bytes32 smgID, uint tokenPairID, uint value, address userAccount, bytes r, bytes32 s) external notHalted nonReentrant { uint curveID; bytes memory PK; (curveID, PK) = acquireReadySmgInfo(smgID); bytes32 mHash = sha256(abi.encode(xHash, tokenPairID, value, userAccount)); verifySignature(curveID, mHash, PK, r, s); HTLCMintLib.HTLCSmgMintLockParams memory params = HTLCMintLib.HTLCSmgMintLockParams({ xHash: xHash, smgID: smgID, tokenPairID: tokenPairID, value: value, lockedTime: lockedTime, userShadowAccount: userAccount }); HTLCMintLib.smgMintLock(storageData, params); } /// @notice request exchange RC20 token with WRC20 on wanchain /// @param x HTLC random number function userMintRedeem(bytes32 x) external notHalted nonReentrant { HTLCMintLib.userMintRedeem(storageData, x); } /// @notice request exchange RC20 token with WRC20 on wanchain /// @param x HTLC random number function smgMintRedeem(bytes32 x) external notHalted nonReentrant { HTLCMintLib.smgMintRedeem(storageData, x); } /// @notice request exchange RC20 token with WRC20 on wanchain /// @param xHash hash of HTLC random number function smgMintRevoke(bytes32 xHash) external notHalted nonReentrant { HTLCMintLib.smgMintRevoke(storageData, xHash); } /// @notice request exchange RC20 token with WRC20 on wanchain /// @param xHash hash of HTLC random number function userMintRevoke(bytes32 xHash) external payable notHalted nonReentrant { HTLCMintLib.userMintRevoke(storageData, xHash); } /// @notice request exchange RC20 token with WRC20 on wanchain /// @param xHash hash of HTLC random number /// @param smgID ID of storeman /// @param tokenPairID token pair ID of cross chain token /// @param value exchange value /// @param userAccount account of user, used to receive original chain token function userBurnLock(bytes32 xHash, bytes32 smgID, uint tokenPairID, uint value, bytes userAccount) external payable notHalted nonReentrant onlyReadySmg(smgID) onlyMeaningfulValue(value) { HTLCBurnLib.HTLCUserBurnLockParams memory params = HTLCBurnLib.HTLCUserBurnLockParams({ xHash: xHash, smgID: smgID, tokenPairID: tokenPairID, value: value, lockedTime: lockedTime.mul(2), userOrigAccount: userAccount }); HTLCBurnLib.userBurnLock(storageData, params); } /// @notice request exchange RC20 token with WRC20 on wanchain /// @param xHash hash of HTLC random number /// @param smgID ID of storeman /// @param tokenPairID token pair ID of cross chain token /// @param value exchange value /// @param userAccount address of user, used to receive WRC20 token /// @param r signature /// @param s signature function smgBurnLock(bytes32 xHash, bytes32 smgID, uint tokenPairID, uint value, address userAccount, bytes r, bytes32 s) external notHalted nonReentrant { uint curveID; bytes memory PK; (curveID, PK) = acquireReadySmgInfo(smgID); bytes32 mHash = sha256(abi.encode(xHash, tokenPairID, value, userAccount)); verifySignature(curveID, mHash, PK, r, s); HTLCBurnLib.HTLCSmgBurnLockParams memory params = HTLCBurnLib.HTLCSmgBurnLockParams({ xHash: xHash, smgID: smgID, tokenPairID: tokenPairID, value: value, lockedTime: lockedTime, userOrigAccount: userAccount }); HTLCBurnLib.smgBurnLock(storageData, params); } /// @notice request exchange RC20 token with WRC20 on wanchain /// @param x HTLC random number function userBurnRedeem(bytes32 x) external notHalted nonReentrant { HTLCBurnLib.userBurnRedeem(storageData, x); } /// @notice request exchange RC20 token with WRC20 on wanchain /// @param x HTLC random number function smgBurnRedeem(bytes32 x) external notHalted nonReentrant { HTLCBurnLib.smgBurnRedeem(storageData, x); } /// @notice request exchange RC20 token with WRC20 on wanchain /// @param xHash hash of HTLC random number function smgBurnRevoke(bytes32 xHash) external notHalted nonReentrant { HTLCBurnLib.smgBurnRevoke(storageData, xHash); } /// @notice request exchange RC20 token with WRC20 on wanchain /// @param xHash hash of HTLC random number function userBurnRevoke(bytes32 xHash) external payable notHalted nonReentrant { HTLCBurnLib.userBurnRevoke(storageData, xHash); } */ /// @notice request exchange RC20 token with WRC20 on wanchain /// @param smgID ID of storeman /// @param tokenPairID token pair ID of cross chain token /// @param value exchange value /// @param userAccount account of user, used to receive shadow chain token function userFastMint(bytes32 smgID, uint tokenPairID, uint value, bytes userAccount) external payable notHalted // nonReentrant onlyReadySmg(smgID) onlyMeaningfulValue(value) { RapidityLib.RapidityUserMintParams memory params = RapidityLib.RapidityUserMintParams({ smgID: smgID, tokenPairID: tokenPairID, value: value, userShadowAccount: userAccount }); RapidityLib.userFastMint(storageData, params); } /// @notice request exchange RC20 token with WRC20 on wanchain /// @param uniqueID fast cross chain random number /// @param smgID ID of storeman /// @param tokenPairID token pair ID of cross chain token /// @param value exchange value /// @param userAccount address of user, used to receive WRC20 token /// @param r signature /// @param s signature function smgFastMint(bytes32 uniqueID, bytes32 smgID, uint tokenPairID, uint value, address userAccount, bytes r, bytes32 s) external notHalted nonReentrant { uint curveID; bytes memory PK; // (curveID, PK) = acquireExistSmgInfo(smgID); (curveID, PK) = acquireReadySmgInfo(smgID); bytes32 mHash = sha256(abi.encode(uniqueID, tokenPairID, value, userAccount)); verifySignature(curveID, mHash, PK, r, s); RapidityLib.RapiditySmgMintParams memory params = RapidityLib.RapiditySmgMintParams({ uniqueID: uniqueID, smgID: smgID, tokenPairID: tokenPairID, value: value, userShadowAccount: userAccount }); RapidityLib.smgFastMint(storageData, params); } /// @notice request exchange RC20 token with WRC20 on wanchain /// @param smgID ID of storeman /// @param tokenPairID token pair ID of cross chain token /// @param value exchange value /// @param userAccount account of user, used to receive original chain token function userFastBurn(bytes32 smgID, uint tokenPairID, uint value, bytes userAccount) external payable notHalted nonReentrant onlyReadySmg(smgID) onlyMeaningfulValue(value) { RapidityLib.RapidityUserBurnParams memory params = RapidityLib.RapidityUserBurnParams({ smgID: smgID, tokenPairID: tokenPairID, value: value, userOrigAccount: userAccount }); RapidityLib.userFastBurn(storageData, params); } /// @notice request exchange RC20 token with WRC20 on wanchain /// @param uniqueID fast cross chain random number /// @param smgID ID of storeman /// @param tokenPairID token pair ID of cross chain token /// @param value exchange value /// @param userAccount address of user, used to receive original token/coin /// @param r signature /// @param s signature function smgFastBurn(bytes32 uniqueID, bytes32 smgID, uint tokenPairID, uint value, address userAccount, bytes r, bytes32 s) external notHalted nonReentrant { uint curveID; bytes memory PK; // (curveID, PK) = acquireExistSmgInfo(smgID); (curveID, PK) = acquireReadySmgInfo(smgID); bytes32 mHash = sha256(abi.encode(uniqueID, tokenPairID, value, userAccount)); verifySignature(curveID, mHash, PK, r, s); RapidityLib.RapiditySmgBurnParams memory params = RapidityLib.RapiditySmgBurnParams({ uniqueID: uniqueID, smgID: smgID, tokenPairID: tokenPairID, value: value, userOrigAccount: userAccount }); RapidityLib.smgFastBurn(storageData, params); } /// @notice lock storeman debt /// @param xHash hash of HTLC random number /// @param srcSmgID ID of src storeman /// @param destSmgID ID of dst storeman /// @param r signature /// @param s signature function srcDebtLock(bytes32 xHash, bytes32 srcSmgID, bytes32 destSmgID, bytes r, bytes32 s) external notHalted onlyReadySmg(destSmgID) { uint curveID; bytes memory PK; (curveID, PK) = acquireUnregisteredSmgInfo(srcSmgID); bytes32 mHash = sha256(abi.encode(xHash, destSmgID)); verifySignature(curveID, mHash, PK, r, s); HTLCDebtLib.HTLCDebtLockParams memory params = HTLCDebtLib.HTLCDebtLockParams({ xHash: xHash, srcSmgID: srcSmgID, destSmgID: destSmgID, lockedTime: lockedTime.mul(2) }); HTLCDebtLib.srcDebtLock(storageData, params); } /// @notice lock storeman debt /// @param xHash hash of HTLC random number /// @param srcSmgID ID of src storeman /// @param destSmgID ID of dst storeman /// @param r signature /// @param s signature function destDebtLock(bytes32 xHash, bytes32 srcSmgID, bytes32 destSmgID, bytes r, bytes32 s) external notHalted { uint curveID; bytes memory PK; (curveID, PK) = acquireReadySmgInfo(destSmgID); bytes32 mHash = sha256(abi.encode(xHash, srcSmgID)); verifySignature(curveID, mHash, PK, r, s); HTLCDebtLib.HTLCDebtLockParams memory params = HTLCDebtLib.HTLCDebtLockParams({ xHash: xHash, srcSmgID: srcSmgID, destSmgID: destSmgID, lockedTime: lockedTime }); HTLCDebtLib.destDebtLock(storageData, params); } /// @notice redeem debt, destination storeman group takes over the debt of source storeman group /// @param x HTLC random number function srcDebtRedeem(bytes32 x) external notHalted { HTLCDebtLib.srcDebtRedeem(storageData, x); } /// @notice redeem debt, destination storeman group takes over the debt of source storeman group /// @param x HTLC random number function destDebtRedeem(bytes32 x) external notHalted { HTLCDebtLib.destDebtRedeem(storageData, x); } /// @notice source storeman group revoke the debt on debt chain /// @param xHash hash of HTLC random number function destDebtRevoke(bytes32 xHash) external notHalted { HTLCDebtLib.destDebtRevoke(storageData, xHash); } /// @notice source storeman group revoke the debt on asset chain /// @param xHash hash of HTLC random number function srcDebtRevoke(bytes32 xHash) external notHalted { HTLCDebtLib.srcDebtRevoke(storageData, xHash); } /// @notice get the fee of the storeman group should get /// @param smgID ID of storemanGroup /// @return fee original coin the storeman group should get function getStoremanFee(bytes32 smgID) external view returns(uint fee) { fee = storageData.mapStoremanFee[smgID]; } /// @notice get the fee of the storeman group should get /// @param origChainID ID of token original chain /// @param shadowChainID ID of token shadow chain /// @param lockFee Coin the storeman group should get while storeman redeem user lock /// @param revokeFee Coin the storeman group should get while user revoke its lock function setFees(uint origChainID, uint shadowChainID, uint lockFee, uint revokeFee) external onlyOwner { storageData.mapLockFee[origChainID][shadowChainID] = lockFee; storageData.mapRevokeFee[origChainID][shadowChainID] = revokeFee; } /// @notice get the fee of the storeman group should get /// @param origChainID Original chain ID /// @param shadowChainID Shadow Chain ID /// @return lockFee Coin the storeman group should get while storeman redeem user lock /// @return revokeFee Coin the storeman group should get while user revoke its lock function getFees(uint origChainID, uint shadowChainID) external view returns(uint lockFee, uint revokeFee) { lockFee = storageData.mapLockFee[origChainID][shadowChainID]; revokeFee = storageData.mapRevokeFee[origChainID][shadowChainID]; } /// @notice get the fee of the storeman group should get /// @param time Coin the storeman group should get while storeman redeem user lock function setLockedTime(uint time) external onlyOwner { lockedTime = time; } /// @notice get the fee of the storeman group should get /// @param xHash hash of HTLC random number /// @return leftLockTime left time of locked transaction function getLeftLockedTime(bytes32 xHash) external view returns (uint leftLockedTime) { leftLockedTime = storageData.htlcTxData.getLeftLockedTime(xHash); } /// @notice update the initialized state value of this contract /// @param tokenManager address of the token manager /// @param smgAdminProxy address of the storeman group admin /// @param smgFeeProxy address of the proxy to store fee for storeman group /// @param quota address of the quota /// @param sigVerifier address of the signature verifier function setPartners(address tokenManager, address smgAdminProxy, address smgFeeProxy, address quota, address sigVerifier) external onlyOwner { require(tokenManager != address(0) && smgAdminProxy != address(0) && quota != address(0) && sigVerifier != address(0), "Parameter is invalid"); storageData.smgAdminProxy = IStoremanGroup(smgAdminProxy); storageData.tokenManager = ITokenManager(tokenManager); storageData.quota = IQuota(quota); storageData.smgFeeProxy = smgFeeProxy; storageData.sigVerifier = ISignatureVerifier(sigVerifier); } /// @notice get the initialized state value of this contract /// @return tokenManager address of the token manager /// @return smgAdminProxy address of the storeman group admin /// @return smgFeeProxy address of the proxy to store fee for storeman group /// @return quota address of the quota /// @return sigVerifier address of the signature verifier function getPartners() external view returns(address tokenManager, address smgAdminProxy, address smgFeeProxy, address quota, address sigVerifier) { tokenManager = address(storageData.tokenManager); smgAdminProxy = address(storageData.smgAdminProxy); smgFeeProxy = storageData.smgFeeProxy; quota = address(storageData.quota); sigVerifier = address(storageData.sigVerifier); } /// @notice get the fee of the storeman group should get /// @param timeout Timeout for storeman group receiver withdraw fee, uint second function setWithdrawFeeTimeout(uint timeout) external onlyOwner { smgFeeReceiverTimeout = timeout; } /// @notice storeman group withdraw the fee to receiver account /// @param smgID ID of the storeman group /// @param receiver account of the receiver /// @param r signature /// @param s signature function smgWithdrawFee(bytes32 smgID, uint timeStamp, address receiver, bytes r, bytes32 s) external nonReentrant { require(now < timeStamp.add(smgFeeReceiverTimeout), "The receiver address expired"); uint curveID; bytes memory PK; (,,,,,curveID,,PK,,,) = storageData.smgAdminProxy.getStoremanGroupConfig(smgID); verifySignature(curveID, sha256(abi.encode(timeStamp, receiver)), PK, r, s); uint fee = storageData.mapStoremanFee[smgID]; require(fee > 0, "Fee is null"); delete storageData.mapStoremanFee[smgID]; receiver.transfer(fee); emit SmgWithdrawFeeLogger(smgID, now, receiver, fee); } /// @notice convert bytes to bytes32 /// @param b bytes array /// @param offset offset of array to begin convert // function bytesToBytes32(bytes b, uint offset) private pure returns (bytes32) { // bytes32 out; // for (uint i = 0; i < 32; i++) { // out |= bytes32(b[offset + i] & 0xFF) >> (i * 8); // } // return out; // } function bytesToBytes32(bytes memory b, uint offset) private pure returns (bytes32 result) { assembly { result := mload(add(add(b, offset), 32)) } } /// @notice verify signature /// @param curveID ID of elliptic curve /// @param message message to be verified /// @param r Signature info r /// @param s Signature info s function verifySignature(uint curveID, bytes32 message, bytes PK, bytes r, bytes32 s) private // view { bytes32 PKx = bytesToBytes32(PK, 0); bytes32 PKy = bytesToBytes32(PK, 32); bytes32 Rx = bytesToBytes32(r, 0); bytes32 Ry = bytesToBytes32(r, 32); require(storageData.sigVerifier.verify(curveID, s, PKx, PKy, Rx, Ry, message), "Signature verification failed"); } // /// @notice get the detailed quota info. of this storeman group // /// @param smgID ID of storemanGroup // /// @param tokenPairID token pair ID of cross chain token // /// @return _quota storemanGroup's total quota // /// @return mintBridgeQuota inbound, the amount which storeman group can handle // /// @return BurnBridgeQuota outbound, the amount which storeman group can handle // /// @return _receivable amount of original token to be received, equals to amount of WAN token to be minted // /// @return _payable amount of WAN token to be burnt // /// @return _debt amount of original token has been exchanged to the wanchain // function queryStoremanGroupQuota(bytes32 smgID, uint tokenPairID) // external // view // returns(uint, uint, uint, uint, uint, uint) // { // return storageData.quotaData.queryQuotaInfo(smgID, tokenPairID); // } }
request exchange RC20 token with WRC20 on wanchain xHash hash of HTLC random number smgID ID of storeman tokenPairID token pair ID of cross chain token value exchange value userAccount account of user, used to receive original chain token
function userBurnLock(bytes32 xHash, bytes32 smgID, uint tokenPairID, uint value, bytes userAccount) external payable notHalted nonReentrant onlyReadySmg(smgID) onlyMeaningfulValue(value) { HTLCBurnLib.HTLCUserBurnLockParams memory params = HTLCBurnLib.HTLCUserBurnLockParams({ xHash: xHash, smgID: smgID, tokenPairID: tokenPairID, value: value, lockedTime: lockedTime.mul(2), userOrigAccount: userAccount }); HTLCBurnLib.userBurnLock(storageData, params); }
1,814,134
//Address: 0x621ad3562f5141c4a0e7cad958b8b524d356332b //Contract name: SaleAuction //Balance: 0 Ether //Verification Date: 1/28/2018 //Transacion Count: 39 // CODE STARTS HERE pragma solidity ^0.4.18; /** * @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 OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() 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 transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /// @title Interface for contracts conforming to ERC-721: Deed Standard /// @author William Entriken (https://phor.net), et al. /// @dev Specification at https://github.com/ethereum/EIPs/pull/841 (DRAFT) interface ERC721 { // COMPLIANCE WITH ERC-165 (DRAFT) ///////////////////////////////////////// /// @dev ERC-165 (draft) interface signature for itself // bytes4 internal constant INTERFACE_SIGNATURE_ERC165 = // 0x01ffc9a7 // bytes4(keccak256('supportsInterface(bytes4)')); /// @dev ERC-165 (draft) interface signature for ERC721 // bytes4 internal constant INTERFACE_SIGNATURE_ERC721 = // 0xda671b9b // bytes4(keccak256('ownerOf(uint256)')) ^ // bytes4(keccak256('countOfDeeds()')) ^ // bytes4(keccak256('countOfDeedsByOwner(address)')) ^ // bytes4(keccak256('deedOfOwnerByIndex(address,uint256)')) ^ // bytes4(keccak256('approve(address,uint256)')) ^ // bytes4(keccak256('takeOwnership(uint256)')); /// @notice Query a contract to see if it supports a certain interface /// @dev Returns `true` the interface is supported and `false` otherwise, /// returns `true` for INTERFACE_SIGNATURE_ERC165 and /// INTERFACE_SIGNATURE_ERC721, see ERC-165 for other interface signatures. function supportsInterface(bytes4 _interfaceID) external pure returns (bool); // PUBLIC QUERY FUNCTIONS ////////////////////////////////////////////////// /// @notice Find the owner of a deed /// @param _deedId The identifier for a deed we are inspecting /// @dev Deeds assigned to zero address are considered destroyed, and /// queries about them do throw. /// @return The non-zero address of the owner of deed `_deedId`, or `throw` /// if deed `_deedId` is not tracked by this contract function ownerOf(uint256 _deedId) external view returns (address _owner); /// @notice Count deeds tracked by this contract /// @return A count of the deeds tracked by this contract, where each one of /// them has an assigned and queryable owner function countOfDeeds() public view returns (uint256 _count); /// @notice Count all deeds assigned to an owner /// @dev Throws if `_owner` is the zero address, representing destroyed deeds. /// @param _owner An address where we are interested in deeds owned by them /// @return The number of deeds owned by `_owner`, possibly zero function countOfDeedsByOwner(address _owner) public view returns (uint256 _count); /// @notice Enumerate deeds assigned to an owner /// @dev Throws if `_index` >= `countOfDeedsByOwner(_owner)` or if /// `_owner` is the zero address, representing destroyed deeds. /// @param _owner An address where we are interested in deeds owned by them /// @param _index A counter between zero and `countOfDeedsByOwner(_owner)`, /// inclusive /// @return The identifier for the `_index`th deed assigned to `_owner`, /// (sort order not specified) function deedOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _deedId); // TRANSFER MECHANISM ////////////////////////////////////////////////////// /// @dev This event emits when ownership of any deed changes by any /// mechanism. This event emits when deeds are created (`from` == 0) and /// destroyed (`to` == 0). Exception: during contract creation, any /// transfers may occur without emitting `Transfer`. event Transfer(address indexed from, address indexed to, uint256 indexed deedId); /// @dev This event emits on any successful call to /// `approve(address _spender, uint256 _deedId)`. Exception: does not emit /// if an owner revokes approval (`_to` == 0x0) on a deed with no existing /// approval. event Approval(address indexed owner, address indexed approved, uint256 indexed deedId); /// @notice Approve a new owner to take your deed, or revoke approval by /// setting the zero address. You may `approve` any number of times while /// the deed is assigned to you, only the most recent approval matters. /// @dev Throws if `msg.sender` does not own deed `_deedId` or if `_to` == /// `msg.sender`. /// @param _deedId The deed you are granting ownership of function approve(address _to, uint256 _deedId) external; /// @notice Become owner of a deed for which you are currently approved /// @dev Throws if `msg.sender` is not approved to become the owner of /// `deedId` or if `msg.sender` currently owns `_deedId`. /// @param _deedId The deed that is being transferred function takeOwnership(uint256 _deedId) external; // SPEC EXTENSIONS ///////////////////////////////////////////////////////// /// @notice Transfer a deed to a new owner. /// @dev Throws if `msg.sender` does not own deed `_deedId` or if /// `_to` == 0x0. /// @param _to The address of the new owner. /// @param _deedId The deed you are transferring. function transfer(address _to, uint256 _deedId) external; } /// @title The internal clock auction functionality. /// Inspired by CryptoKitties' clock auction contract ClockAuctionBase { // Address of the ERC721 contract this auction is linked to. ERC721 public deedContract; // Fee per successful auction in 1/1000th of a percentage. uint256 public fee; // Total amount of ether yet to be paid to auction beneficiaries. uint256 public outstandingEther = 0 ether; // Amount of ether yet to be paid per beneficiary. mapping (address => uint256) public addressToEtherOwed; /// @dev Represents a deed auction. /// Care has been taken to ensure the auction fits in /// two 256-bit words. struct Auction { address seller; uint128 startPrice; uint128 endPrice; uint64 duration; uint64 startedAt; } mapping (uint256 => Auction) identifierToAuction; // Events event AuctionCreated(address indexed seller, uint256 indexed deedId, uint256 startPrice, uint256 endPrice, uint256 duration); event AuctionSuccessful(address indexed buyer, uint256 indexed deedId, uint256 totalPrice); event AuctionCancelled(uint256 indexed deedId); /// @dev Modifier to check whether the value can be stored in a 64 bit uint. modifier fitsIn64Bits(uint256 _value) { require (_value == uint256(uint64(_value))); _; } /// @dev Modifier to check whether the value can be stored in a 128 bit uint. modifier fitsIn128Bits(uint256 _value) { require (_value == uint256(uint128(_value))); _; } function ClockAuctionBase(address _deedContractAddress, uint256 _fee) public { deedContract = ERC721(_deedContractAddress); // Contract must indicate support for ERC721 through its interface signature. require(deedContract.supportsInterface(0xda671b9b)); // Fee must be between 0 and 100%. require(0 <= _fee && _fee <= 100000); fee = _fee; } /// @dev Checks whether the given auction is active. /// @param auction The auction to check for activity. function _activeAuction(Auction storage auction) internal view returns (bool) { return auction.startedAt > 0; } /// @dev Put the deed into escrow, thereby taking ownership of it. /// @param _deedId The identifier of the deed to place into escrow. function _escrow(uint256 _deedId) internal { // Throws if the transfer fails deedContract.takeOwnership(_deedId); } /// @dev Create the auction. /// @param _deedId The identifier of the deed to create the auction for. /// @param auction The auction to create. function _createAuction(uint256 _deedId, Auction auction) internal { // Add the auction to the auction mapping. identifierToAuction[_deedId] = auction; // Trigger auction created event. AuctionCreated(auction.seller, _deedId, auction.startPrice, auction.endPrice, auction.duration); } /// @dev Bid on an auction. /// @param _buyer The address of the buyer. /// @param _value The value sent by the sender (in ether). /// @param _deedId The identifier of the deed to bid on. function _bid(address _buyer, uint256 _value, uint256 _deedId) internal { Auction storage auction = identifierToAuction[_deedId]; // The auction must be active. require(_activeAuction(auction)); // Calculate the auction's current price. uint256 price = _currentPrice(auction); // Make sure enough funds were sent. require(_value >= price); address seller = auction.seller; if (price > 0) { uint256 totalFee = _calculateFee(price); uint256 proceeds = price - totalFee; // Assign the proceeds to the seller. // We do not send the proceeds directly, as to prevent // malicious sellers from denying auctions (and burning // the buyer's gas). _assignProceeds(seller, proceeds); } AuctionSuccessful(_buyer, _deedId, price); // The bid was won! _winBid(seller, _buyer, _deedId, price); // Remove the auction (we do this at the end, as // winBid might require some additional information // that will be removed when _removeAuction is // called. As we do not transfer funds here, we do // not have to worry about re-entry attacks. _removeAuction(_deedId); } /// @dev Perform the bid win logic (in this case: transfer the deed). /// @param _seller The address of the seller. /// @param _winner The address of the winner. /// @param _deedId The identifier of the deed. /// @param _price The price the auction was bought at. function _winBid(address _seller, address _winner, uint256 _deedId, uint256 _price) internal { _transfer(_winner, _deedId); } /// @dev Cancel an auction. /// @param _deedId The identifier of the deed for which the auction should be cancelled. /// @param auction The auction to cancel. function _cancelAuction(uint256 _deedId, Auction auction) internal { // Remove the auction _removeAuction(_deedId); // Transfer the deed back to the seller _transfer(auction.seller, _deedId); // Trigger auction cancelled event. AuctionCancelled(_deedId); } /// @dev Remove an auction. /// @param _deedId The identifier of the deed for which the auction should be removed. function _removeAuction(uint256 _deedId) internal { delete identifierToAuction[_deedId]; } /// @dev Transfer a deed owned by this contract to another address. /// @param _to The address to transfer the deed to. /// @param _deedId The identifier of the deed. function _transfer(address _to, uint256 _deedId) internal { // Throws if the transfer fails deedContract.transfer(_to, _deedId); } /// @dev Assign proceeds to an address. /// @param _to The address to assign proceeds to. /// @param _value The proceeds to assign. function _assignProceeds(address _to, uint256 _value) internal { outstandingEther += _value; addressToEtherOwed[_to] += _value; } /// @dev Calculate the current price of an auction. function _currentPrice(Auction storage _auction) internal view returns (uint256) { require(now >= _auction.startedAt); uint256 secondsPassed = now - _auction.startedAt; if (secondsPassed >= _auction.duration) { return _auction.endPrice; } else { // Negative if the end price is higher than the start price! int256 totalPriceChange = int256(_auction.endPrice) - int256(_auction.startPrice); // Calculate the current price based on the total change over the entire // auction duration, and the amount of time passed since the start of the // auction. int256 currentPriceChange = totalPriceChange * int256(secondsPassed) / int256(_auction.duration); // Calculate the final price. Note this once again // is representable by a uint256, as the price can // never be negative. int256 price = int256(_auction.startPrice) + currentPriceChange; // This never throws. assert(price >= 0); return uint256(price); } } /// @dev Calculate the fee for a given price. /// @param _price The price to calculate the fee for. function _calculateFee(uint256 _price) internal view returns (uint256) { // _price is guaranteed to fit in a uint128 due to the createAuction entry // modifiers, so this cannot overflow. return _price * fee / 100000; } } contract ClockAuction is ClockAuctionBase, Pausable { function ClockAuction(address _deedContractAddress, uint256 _fee) ClockAuctionBase(_deedContractAddress, _fee) public {} /// @notice Update the auction fee. /// @param _fee The new fee. function setFee(uint256 _fee) external onlyOwner { require(0 <= _fee && _fee <= 100000); fee = _fee; } /// @notice Get the auction for the given deed. /// @param _deedId The identifier of the deed to get the auction for. /// @dev Throws if there is no auction for the given deed. function getAuction(uint256 _deedId) external view returns ( address seller, uint256 startPrice, uint256 endPrice, uint256 duration, uint256 startedAt ) { Auction storage auction = identifierToAuction[_deedId]; // The auction must be active require(_activeAuction(auction)); return ( auction.seller, auction.startPrice, auction.endPrice, auction.duration, auction.startedAt ); } /// @notice Create an auction for a given deed. /// Must previously have been given approval to take ownership of the deed. /// @param _deedId The identifier of the deed to create an auction for. /// @param _startPrice The starting price of the auction. /// @param _endPrice The ending price of the auction. /// @param _duration The duration in seconds of the dynamic pricing part of the auction. function createAuction(uint256 _deedId, uint256 _startPrice, uint256 _endPrice, uint256 _duration) public fitsIn128Bits(_startPrice) fitsIn128Bits(_endPrice) fitsIn64Bits(_duration) whenNotPaused { // Get the owner of the deed to be auctioned address deedOwner = deedContract.ownerOf(_deedId); // Caller must either be the deed contract or the owner of the deed // to prevent abuse. require( msg.sender == address(deedContract) || msg.sender == deedOwner ); // The duration of the auction must be at least 60 seconds. require(_duration >= 60); // Throws if placing the deed in escrow fails (the contract requires // transfer approval prior to creating the auction). _escrow(_deedId); // Auction struct Auction memory auction = Auction( deedOwner, uint128(_startPrice), uint128(_endPrice), uint64(_duration), uint64(now) ); _createAuction(_deedId, auction); } /// @notice Cancel an auction /// @param _deedId The identifier of the deed to cancel the auction for. function cancelAuction(uint256 _deedId) external whenNotPaused { Auction storage auction = identifierToAuction[_deedId]; // The auction must be active. require(_activeAuction(auction)); // The auction can only be cancelled by the seller require(msg.sender == auction.seller); _cancelAuction(_deedId, auction); } /// @notice Bid on an auction. /// @param _deedId The identifier of the deed to bid on. function bid(uint256 _deedId) external payable whenNotPaused { // Throws if the bid does not succeed. _bid(msg.sender, msg.value, _deedId); } /// @dev Returns the current price of an auction. /// @param _deedId The identifier of the deed to get the currency price for. function getCurrentPrice(uint256 _deedId) external view returns (uint256) { Auction storage auction = identifierToAuction[_deedId]; // The auction must be active. require(_activeAuction(auction)); return _currentPrice(auction); } /// @notice Withdraw ether owed to a beneficiary. /// @param beneficiary The address to withdraw the auction balance for. function withdrawAuctionBalance(address beneficiary) external { // The sender must either be the beneficiary or the core deed contract. require( msg.sender == beneficiary || msg.sender == address(deedContract) ); uint256 etherOwed = addressToEtherOwed[beneficiary]; // Ensure ether is owed to the beneficiary. require(etherOwed > 0); // Set ether owed to 0 delete addressToEtherOwed[beneficiary]; // Subtract from total outstanding balance. etherOwed is guaranteed // to be less than or equal to outstandingEther, so this cannot // underflow. outstandingEther -= etherOwed; // Transfer ether owed to the beneficiary (not susceptible to re-entry // attack, as the ether owed is set to 0 before the transfer takes place). beneficiary.transfer(etherOwed); } /// @notice Withdraw (unowed) contract balance. function withdrawFreeBalance() external { // Calculate the free (unowed) balance. This never underflows, as // outstandingEther is guaranteed to be less than or equal to the // contract balance. uint256 freeBalance = this.balance - outstandingEther; address deedContractAddress = address(deedContract); require( msg.sender == owner || msg.sender == deedContractAddress ); deedContractAddress.transfer(freeBalance); } } contract SaleAuction is ClockAuction { function SaleAuction(address _deedContractAddress, uint256 _fee) ClockAuction(_deedContractAddress, _fee) public {} /// @dev Allows other contracts to check whether this is the expected contract. bool public isSaleAuction = true; }
Returns the current price of an auction. _deedId The identifier of the deed to get the currency price for. The auction must be active.
function getCurrentPrice(uint256 _deedId) external view returns (uint256) { Auction storage auction = identifierToAuction[_deedId]; require(_activeAuction(auction)); return _currentPrice(auction); }
1,772,251
// File: contracts/lib/ERC20.sol pragma solidity ^0.4.24; /** * @title ERC20 * @dev A standard interface for tokens. * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md */ contract ERC20 { /// @dev Returns the total token supply function totalSupply() public view returns (uint256 supply); /// @dev Returns the account balance of the account with address _owner function balanceOf(address _owner) public view returns (uint256 balance); /// @dev Transfers _value number of tokens to address _to function transfer(address _to, uint256 _value) public returns (bool success); /// @dev Transfers _value number of tokens from address _from to address _to function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /// @dev Allows _spender to withdraw from the msg.sender's account up to the _value amount function approve(address _spender, uint256 _value) public returns (bool success); /// @dev Returns the amount which _spender is still allowed to withdraw from _owner function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } // File: contracts/FundsForwarder.sol interface IGivethBridge { function donate(uint64 giverId, uint64 receiverId) external payable; function donate(uint64 giverId, uint64 receiverId, address token, uint _amount) external payable; } interface IFundsForwarderFactory { function bridge() external returns (address); function escapeHatchCaller() external returns (address); function escapeHatchDestination() external returns (address); } interface IMolochDao { function approvedToken() external returns (address); function members(address member) external returns (address, uint256, bool, uint256); function ragequit(uint sharesToBurn) external; } interface IWEth { function withdraw(uint wad) external; function balanceOf(address guy) external returns (uint); } contract FundsForwarder { uint64 public receiverId; uint64 public giverId; IFundsForwarderFactory public fundsForwarderFactory; string private constant ERROR_ERC20_APPROVE = "ERROR_ERC20_APPROVE"; string private constant ERROR_BRIDGE_CALL = "ERROR_BRIDGE_CALL"; string private constant ERROR_ZERO_BRIDGE = "ERROR_ZERO_BRIDGE"; string private constant ERROR_DISALLOWED = "RECOVER_DISALLOWED"; string private constant ERROR_TOKEN_TRANSFER = "RECOVER_TOKEN_TRANSFER"; string private constant ERROR_ALREADY_INITIALIZED = "INIT_ALREADY_INITIALIZED"; uint private constant MAX_UINT = uint(-1); event Forwarded(address to, address token, uint balance); event EscapeHatchCalled(address token, uint amount); constructor() public { /// @dev From AragonOS's Autopetrified contract // Immediately petrify base (non-proxy) instances of inherited contracts on deploy. // This renders them uninitializable (and unusable without a proxy). fundsForwarderFactory = IFundsForwarderFactory(address(-1)); } /** * Fallback function to receive ETH donations */ function() public payable {} /** * @dev Initialize can only be called once. * @notice msg.sender MUST be the _fundsForwarderFactory Contract * Its address must be a contract with three public getters: * - bridge(): Returns the bridge address * - escapeHatchCaller(): Returns the escapeHatchCaller address * - escapeHatchDestination(): Returns the escashouldpeHatchDestination address * @param _giverId The adminId of the liquidPledging pledge admin who is donating * @param _receiverId The adminId of the liquidPledging pledge admin receiving the donation */ function initialize(uint64 _giverId, uint64 _receiverId) public { /// @dev onlyInit method from AragonOS's Initializable contract require(fundsForwarderFactory == address(0), ERROR_ALREADY_INITIALIZED); /// @dev Setting fundsForwarderFactory, serves as calling initialized() fundsForwarderFactory = IFundsForwarderFactory(msg.sender); /// @dev Make sure that the fundsForwarderFactory is a contract and has a bridge method require(fundsForwarderFactory.bridge() != address(0), ERROR_ZERO_BRIDGE); receiverId = _receiverId; giverId = _giverId; } /** * Transfer tokens/eth to the bridge. Transfer the entire balance of the contract * @param _token the token to transfer. 0x0 for ETH */ function forward(address _token) public { IGivethBridge bridge = IGivethBridge(fundsForwarderFactory.bridge()); require(bridge != address(0), ERROR_ZERO_BRIDGE); uint balance; bool result; /// @dev Logic for ether if (_token == address(0)) { balance = address(this).balance; /// @dev Call donate() with two arguments, for tokens /// Low level .call must be used due to function overloading /// keccak250("donate(uint64,uint64)") = bde60ac9 /* solium-disable-next-line security/no-call-value */ result = address(bridge).call.value(balance)( 0xbde60ac9, giverId, receiverId ); /// @dev Logic for tokens } else { ERC20 token = ERC20(_token); balance = token.balanceOf(this); /// @dev Since the bridge is a trusted contract, the max allowance /// will be set on the first token transfer. Then it's skipped /// Numbers for DAI First tx | n+1 txs /// approve(_, balance) 66356 51356 /// approve(_, MAX_UINT) 78596 39103 /// +12240 -12253 /// Worth it if forward is called more than once for each token if (token.allowance(address(this), bridge) < balance) { require(token.approve(bridge, MAX_UINT), ERROR_ERC20_APPROVE); } /// @dev Call donate() with four arguments, for tokens /// Low level .call must be used due to function overloading /// keccak256("donate(uint64,uint64,address,uint256)") = 4c4316c7 /* solium-disable-next-line security/no-low-level-calls */ result = address(bridge).call( 0x4c4316c7, giverId, receiverId, token, balance ); } require(result, ERROR_BRIDGE_CALL); emit Forwarded(bridge, _token, balance); } /** * Transfer multiple tokens/eth to the bridge. Simplies UI interactions * @param _tokens the array of tokens to transfer. 0x0 for ETH */ function forwardMultiple(address[] _tokens) public { uint tokensLength = _tokens.length; for (uint i = 0; i < tokensLength; i++) { forward(_tokens[i]); } } /** * Transfer tokens from a Moloch DAO by calling ragequit on all shares * @param _molochDao Address of a Moloch DAO * @param _convertWeth Flag to indicate that this DAO uses WETH */ function forwardMoloch(address _molochDao, bool _convertWeth) public { IMolochDao molochDao = IMolochDao(_molochDao); (,uint shares,,) = molochDao.members(address(this)); molochDao.ragequit(shares); address approvedToken = molochDao.approvedToken(); if (_convertWeth) { IWEth weth = IWEth(approvedToken); weth.withdraw(weth.balanceOf(address(this))); forward(address(0)); } else { forward(molochDao.approvedToken()); } } /** * @notice Send funds to recovery address (escapeHatchDestination). * The `escapeHatch()` should only be called as a last resort if a * security issue is uncovered or something unexpected happened * @param _token Token balance to be sent to recovery vault. * * @dev Only the escapeHatchCaller can trigger this function * @dev The escapeHatchCaller address must not have control over escapeHatchDestination * @dev Function extracted from the Escapable contract (by Jordi Baylina and Adrià Massanet) * Instead of storing the caller, destination and owner addresses, * it fetches them from the parent contract. */ function escapeHatch(address _token) public { /// @dev Serves as the original contract's onlyEscapeHatchCaller require(msg.sender == fundsForwarderFactory.escapeHatchCaller(), ERROR_DISALLOWED); address escapeHatchDestination = fundsForwarderFactory.escapeHatchDestination(); uint256 balance; if (_token == 0x0) { balance = address(this).balance; escapeHatchDestination.transfer(balance); } else { ERC20 token = ERC20(_token); balance = token.balanceOf(this); require(token.transfer(escapeHatchDestination, balance), ERROR_TOKEN_TRANSFER); } emit EscapeHatchCalled(_token, balance); } } // File: contracts/lib/IsContract.sol /* * SPDX-License-Identitifer: MIT * Credit to @aragonOS */ contract IsContract { /* * NOTE: this should NEVER be used for authentication * (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize). * * This is only intended to be used as a sanity check that an address is actually a contract, * RATHER THAN an address not being a contract. */ function isContract(address _target) internal view returns (bool) { if (_target == address(0)) { return false; } uint256 size; assembly { size := extcodesize(_target) } return size > 0; } } // File: contracts/lib/Owned.sol /// @title Owned /// @author Adrià Massanet <adria@codecontext.io> /// @notice The Owned contract has an owner address, and provides basic /// authorization control functions, this simplifies & the implementation of /// user permissions; this contract has three work flows for a change in /// ownership, the first requires the new owner to validate that they have the /// ability to accept ownership, the second allows the ownership to be /// directly transfered without requiring acceptance, and the third allows for /// the ownership to be removed to allow for decentralization contract Owned { address public owner; address public newOwnerCandidate; event OwnershipRequested(address indexed by, address indexed to); event OwnershipTransferred(address indexed from, address indexed to); event OwnershipRemoved(); /// @dev The constructor sets the `msg.sender` as the`owner` of the contract constructor() public { owner = msg.sender; } /// @dev `owner` is the only address that can call a function with this /// modifier modifier onlyOwner() { require (msg.sender == owner,"err_ownedNotOwner"); _; } /// @dev In this 1st option for ownership transfer `proposeOwnership()` must /// be called first by the current `owner` then `acceptOwnership()` must be /// called by the `newOwnerCandidate` /// @notice `onlyOwner` Proposes to transfer control of the contract to a /// new owner /// @param _newOwnerCandidate The address being proposed as the new owner function proposeOwnership(address _newOwnerCandidate) public onlyOwner { newOwnerCandidate = _newOwnerCandidate; emit OwnershipRequested(msg.sender, newOwnerCandidate); } /// @notice Can only be called by the `newOwnerCandidate`, accepts the /// transfer of ownership function acceptOwnership() public { require(msg.sender == newOwnerCandidate,"err_ownedNotCandidate"); address oldOwner = owner; owner = newOwnerCandidate; newOwnerCandidate = 0x0; emit OwnershipTransferred(oldOwner, owner); } /// @dev In this 2nd option for ownership transfer `changeOwnership()` can /// be called and it will immediately assign ownership to the `newOwner` /// @notice `owner` can step down and assign some other address to this role /// @param _newOwner The address of the new owner function changeOwnership(address _newOwner) public onlyOwner { require(_newOwner != 0x0,"err_ownedInvalidAddress"); address oldOwner = owner; owner = _newOwner; newOwnerCandidate = 0x0; emit OwnershipTransferred(oldOwner, owner); } /// @dev In this 3rd option for ownership transfer `removeOwnership()` can /// be called and it will immediately assign ownership to the 0x0 address; /// it requires a 0xdece be input as a parameter to prevent accidental use /// @notice Decentralizes the contract, this operation cannot be undone /// @param _dac `0xdac` has to be entered for this function to work function removeOwnership(address _dac) public onlyOwner { require(_dac == 0xdac,"err_ownedInvalidDac"); owner = 0x0; newOwnerCandidate = 0x0; emit OwnershipRemoved(); } } // File: contracts/lib/Escapable.sol /* Copyright 2016, Jordi Baylina Contributor: Adrià Massanet <adria@codecontext.io> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /// @dev `Escapable` is a base level contract built off of the `Owned` /// contract; it creates an escape hatch function that can be called in an /// emergency that will allow designated addresses to send any ether or tokens /// held in the contract to an `escapeHatchDestination` as long as they were /// not blacklisted contract Escapable is Owned { address public escapeHatchCaller; address public escapeHatchDestination; mapping (address=>bool) private escapeBlacklist; // Token contract addresses /// @notice The Constructor assigns the `escapeHatchDestination` and the /// `escapeHatchCaller` /// @param _escapeHatchCaller The address of a trusted account or contract /// to call `escapeHatch()` to send the ether in this contract to the /// `escapeHatchDestination` it would be ideal that `escapeHatchCaller` /// cannot move funds out of `escapeHatchDestination` /// @param _escapeHatchDestination The address of a safe location (usu a /// Multisig) to send the ether held in this contract; if a neutral address /// is required, the WHG Multisig is an option: /// 0x8Ff920020c8AD673661c8117f2855C384758C572 constructor(address _escapeHatchCaller, address _escapeHatchDestination) public { escapeHatchCaller = _escapeHatchCaller; escapeHatchDestination = _escapeHatchDestination; } /// @dev The addresses preassigned as `escapeHatchCaller` or `owner` /// are the only addresses that can call a function with this modifier modifier onlyEscapeHatchCallerOrOwner { require ( (msg.sender == escapeHatchCaller)||(msg.sender == owner), "err_escapableInvalidCaller" ); _; } /// @notice Creates the blacklist of tokens that are not able to be taken /// out of the contract; can only be done at the deployment, and the logic /// to add to the blacklist will be in the constructor of a child contract /// @param _token the token contract address that is to be blacklisted function blacklistEscapeToken(address _token) internal { escapeBlacklist[_token] = true; emit EscapeHatchBlackistedToken(_token); } /// @notice Checks to see if `_token` is in the blacklist of tokens /// @param _token the token address being queried /// @return False if `_token` is in the blacklist and can't be taken out of /// the contract via the `escapeHatch()` function isTokenEscapable(address _token) public view returns (bool) { return !escapeBlacklist[_token]; } /// @notice The `escapeHatch()` should only be called as a last resort if a /// security issue is uncovered or something unexpected happened /// @param _token to transfer, use 0x0 for ether function escapeHatch(address _token) public onlyEscapeHatchCallerOrOwner { require(escapeBlacklist[_token]==false,"err_escapableBlacklistedToken"); uint256 balance; /// @dev Logic for ether if (_token == 0x0) { balance = address(this).balance; escapeHatchDestination.transfer(balance); emit EscapeHatchCalled(_token, balance); return; } /// @dev Logic for tokens ERC20 token = ERC20(_token); balance = token.balanceOf(this); require(token.transfer(escapeHatchDestination, balance),"err_escapableTransfer"); emit EscapeHatchCalled(_token, balance); } /// @notice Changes the address assigned to call `escapeHatch()` /// @param _newEscapeHatchCaller The address of a trusted account or /// contract to call `escapeHatch()` to send the value in this contract to /// the `escapeHatchDestination`; it would be ideal that `escapeHatchCaller` /// cannot move funds out of `escapeHatchDestination` function changeHatchEscapeCaller(address _newEscapeHatchCaller) public onlyEscapeHatchCallerOrOwner { escapeHatchCaller = _newEscapeHatchCaller; } event EscapeHatchBlackistedToken(address token); event EscapeHatchCalled(address token, uint amount); } // File: contracts/FundsForwarderFactory.sol contract FundsForwarderFactory is Escapable, IsContract { address public bridge; address public childImplementation; string private constant ERROR_NOT_A_CONTRACT = "ERROR_NOT_A_CONTRACT"; string private constant ERROR_HATCH_CALLER = "ERROR_HATCH_CALLER"; string private constant ERROR_HATCH_DESTINATION = "ERROR_HATCH_DESTINATION"; event NewFundForwarder(address indexed _giver, uint64 indexed _receiverId, address fundsForwarder); event BridgeChanged(address newBridge); event ChildImplementationChanged(address newChildImplementation); /** * @notice Create a new factory for deploying Giveth FundForwarders * @dev Requires a deployed bridge * @param _bridge Bridge address * @param _escapeHatchCaller The address of a trusted account or contract to * call `escapeHatch()` to send the ether in this contract to the * `escapeHatchDestination` it would be ideal if `escapeHatchCaller` cannot move * funds out of `escapeHatchDestination` * @param _escapeHatchDestination The address of a safe location (usually a * Multisig) to send the value held in this contract in an emergency */ constructor( address _bridge, address _escapeHatchCaller, address _escapeHatchDestination, address _childImplementation ) Escapable(_escapeHatchCaller, _escapeHatchDestination) public { require(isContract(_bridge), ERROR_NOT_A_CONTRACT); bridge = _bridge; // Set the escapeHatch params to the same as in the bridge Escapable bridgeInstance = Escapable(_bridge); require(_escapeHatchCaller == bridgeInstance.escapeHatchCaller(), ERROR_HATCH_CALLER); require(_escapeHatchDestination == bridgeInstance.escapeHatchDestination(), ERROR_HATCH_DESTINATION); // Set the owner to the same as in the bridge changeOwnership(bridgeInstance.owner()); // Deploy FundsForwarder if (_childImplementation == address(0)) { childImplementation = new FundsForwarder(); } else { childImplementation = _childImplementation; } } /** * @notice Change the bridge address. * @param _bridge New bridge address */ function changeBridge(address _bridge) external onlyEscapeHatchCallerOrOwner { bridge = _bridge; emit BridgeChanged(_bridge); } /** * @notice Change the childImplementation address. * @param _childImplementation New childImplementation address */ function changeChildImplementation(address _childImplementation) external onlyEscapeHatchCallerOrOwner { childImplementation = _childImplementation; emit ChildImplementationChanged(_childImplementation); } /** * @param _giverId The adminId of the liquidPledging pledge admin who is donating * @param _receiverId The adminId of the liquidPledging pledge admin receiving the donation */ function newFundsForwarder(uint64 _giverId, uint64 _receiverId) public { address fundsForwarder = _deployMinimal(childImplementation); FundsForwarder(fundsForwarder).initialize(_giverId, _receiverId); // Store a registry of fundForwarders as events emit NewFundForwarder(_giverId, _receiverId, fundsForwarder); } /** * @notice Deploys a minimal forwarding proxy that is not upgradable * From ZepelinOS https://github.com/zeppelinos/zos/blob/v2.4.0/packages/lib/contracts/upgradeability/ProxyFactory.sol */ function _deployMinimal(address _logic) internal returns (address proxy) { // Adapted from https://github.com/optionality/clone-factory/blob/32782f82dfc5a00d103a7e61a17a5dedbd1e8e9d/contracts/CloneFactory.sol bytes20 targetBytes = bytes20(_logic); assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), targetBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) proxy := create(0, clone, 0x37) } } }
_giverId The adminId of the liquidPledging pledge admin who is donating _receiverId The adminId of the liquidPledging pledge admin receiving the donation/ Store a registry of fundForwarders as events
function newFundsForwarder(uint64 _giverId, uint64 _receiverId) public { address fundsForwarder = _deployMinimal(childImplementation); FundsForwarder(fundsForwarder).initialize(_giverId, _receiverId); emit NewFundForwarder(_giverId, _receiverId, fundsForwarder); }
2,572,930
./partial_match/1/0x645BA45dBe3c6942c812A46f9EE8115C89B524EC/sources/VersionManager.sol
IModuleRegistry Interface for the registry of authorised modules./
interface IModuleRegistry { function registerModule(address _module, bytes32 _name) external; function deregisterModule(address _module) external; function registerUpgrader(address _upgrader, bytes32 _name) external; function deregisterUpgrader(address _upgrader) external; function recoverToken(address _token) external; function moduleInfo(address _module) external view returns (bytes32); function upgraderInfo(address _upgrader) external view returns (bytes32); function isRegisteredModule(address _module) external view returns (bool); function isRegisteredModule(address[] calldata _modules) external view returns (bool); function isRegisteredUpgrader(address _upgrader) external view returns (bool); } }
11,030,946
pragma solidity ^0.4.24; import "zeppelin-solidity/contracts/ownership/Ownable.sol"; import "zeppelin-solidity/contracts/math/SafeMath.sol"; import "../contracts/CircuitBreakable.sol"; import "../contracts/oraclizeAPI.sol"; /// @title LibraryDemo - This Dapp maintains employee salary database and calculated bonus /// @notice Library demo is smartcontract which demos usgae of ethereum packages and Oracle contract LibraryDemo is Ownable, usingOraclize, CircuitBreakable { using SafeMath for uint256; uint public electricChargeAllowanceUSD; mapping (uint256 => Employee) employees; struct Employee { uint256 empId; uint256 salary; } event LogNewElectricChargePrice(string price); event LogNewOraclizeQuery(string description); constructor() public { update(); // First check at contract creation... } /// @notice Oraclize query callback where the result of the query is obtained. /// @dev Its 2 step process - sending the query and receiving back the result through call back /// and there will be delay in seconds. function __callback(bytes32 myid, string memory result) public { require(msg.sender == oraclize_cbAddress()); emit LogNewElectricChargePrice(result); uint256 electricChargePriceUSD = parseInt(result); //Calculate Allowance for 10 Kw/hr/day for 22 working days per month electricChargeAllowanceUSD = electricChargePriceUSD.mul(10).mul(22); } /// @notice Oraclize query is constructed and emitted here function update() public payable { emit LogNewOraclizeQuery("Oraclize query was sent, standing by for the answer..."); oraclize_query("URL", "xml(https://www.fueleconomy.gov/ws/rest/fuelprices).fuelPrices.electric"); } /// @notice add employee /// @param _empId Employee Id /// @param _salary salary /// @return return successful addition function addEmployee(uint256 _empId, uint256 _salary) onlyOwner stopInEmergency public returns(bool) { employees[_empId] = Employee({empId:_empId, salary:_salary}); return true; } /// @notice calulate the bonus of the employee /// @param _empId Employee Id /// @param _percent Percentage for calculation /// @return return calculated bonus value function calulateBonus(uint256 _empId, uint256 _percent) onlyOwner stopInEmergency public view returns(uint256) { require(employees[_empId].salary > 0); uint256 bonus = employees[_empId].salary.mul(_percent).div(100); return bonus; } /// @notice Add Calculated electric car allowance to Salary /// @param _empId Employee Id /// @return return calculated new Salary function addElectriCarAllowanceToSalary(uint256 _empId) onlyOwner stopInEmergency public returns(uint256) { require(employees[_empId].salary > 0); employees[_empId].salary = employees[_empId].salary.add(electricChargeAllowanceUSD); return employees[_empId].salary; } }
add employee _empId Employee Id _salary salary return return successful addition
function addEmployee(uint256 _empId, uint256 _salary) onlyOwner stopInEmergency public returns(bool) { return true; }
5,467,446
// File: @openzeppelin/upgrades/contracts/Initializable.sol pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ 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 use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: @openzeppelin/upgrades/contracts/cryptography/ECDSA.sol pragma solidity ^0.5.2; /** * @title Elliptic 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 * * Source https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/79dd498b16b957399f84b9aa7e720f98f9eb83e3/contracts/cryptography/ECDSA.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 implementation from an openzeppelin version. */ library OpenZeppelinUpgradesECDSA { /** * @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 signature bytes signature, the signature is generated using web3.eth.sign() */ 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); } /** * toEthSignedMessageHash * @dev prefix a bytes32 value with "\x19Ethereum Signed Message:" * 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(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // File: @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol pragma solidity ^0.5.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 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. */ contract Context is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts-ethereum-package/contracts/access/Roles.sol pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } // File: @openzeppelin/contracts-ethereum-package/contracts/access/roles/WhitelistAdminRole.sol pragma solidity ^0.5.0; /** * @title WhitelistAdminRole * @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts. */ contract WhitelistAdminRole is Initializable, Context { using Roles for Roles.Role; event WhitelistAdminAdded(address indexed account); event WhitelistAdminRemoved(address indexed account); Roles.Role private _whitelistAdmins; function initialize(address sender) public initializer { if (!isWhitelistAdmin(sender)) { _addWhitelistAdmin(sender); } } modifier onlyWhitelistAdmin() { require(isWhitelistAdmin(_msgSender()), "WhitelistAdminRole: caller does not have the WhitelistAdmin role"); _; } function isWhitelistAdmin(address account) public view returns (bool) { return _whitelistAdmins.has(account); } function addWhitelistAdmin(address account) public onlyWhitelistAdmin { _addWhitelistAdmin(account); } function renounceWhitelistAdmin() public { _removeWhitelistAdmin(_msgSender()); } function _addWhitelistAdmin(address account) internal { _whitelistAdmins.add(account); emit WhitelistAdminAdded(account); } function _removeWhitelistAdmin(address account) internal { _whitelistAdmins.remove(account); emit WhitelistAdminRemoved(account); } uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/access/roles/WhitelistedRole.sol pragma solidity ^0.5.0; /** * @title WhitelistedRole * @dev Whitelisted accounts have been approved by a WhitelistAdmin to perform certain actions (e.g. participate in a * crowdsale). This role is special in that the only accounts that can add it are WhitelistAdmins (who can also remove * it), and not Whitelisteds themselves. */ contract WhitelistedRole is Initializable, Context, WhitelistAdminRole { using Roles for Roles.Role; event WhitelistedAdded(address indexed account); event WhitelistedRemoved(address indexed account); Roles.Role private _whitelisteds; modifier onlyWhitelisted() { require(isWhitelisted(_msgSender()), "WhitelistedRole: caller does not have the Whitelisted role"); _; } function initialize(address sender) public initializer { WhitelistAdminRole.initialize(sender); } function isWhitelisted(address account) public view returns (bool) { return _whitelisteds.has(account); } function addWhitelisted(address account) public onlyWhitelistAdmin { _addWhitelisted(account); } function removeWhitelisted(address account) public onlyWhitelistAdmin { _removeWhitelisted(account); } function renounceWhitelisted() public { _removeWhitelisted(_msgSender()); } function _addWhitelisted(address account) internal { _whitelisteds.add(account); emit WhitelistedAdded(account); } function _removeWhitelisted(address account) internal { _whitelisteds.remove(account); emit WhitelistedRemoved(account); } uint256[50] private ______gap; } // File: contracts/access/roles/WhitelistedRoleMeta.sol pragma solidity ^0.5.0; /** * @title WhitelistedRoleMeta * @dev Add meta transaction capabilities to the WhitelistedRole contract. */ contract WhitelistedRoleMeta is WhitelistedRole { function initialize(address sender) public initializer { WhitelistAdminRole.initialize(sender); } function addSignedWhitelisted(address account, bytes memory signature) public { address signer = getWhitelistedRoleActionSigner('addSignedWhitelisted', account, signature); require(signer != address(0), "Invalid signature"); require(isWhitelistAdmin(signer), "signer is not an admin"); _addWhitelisted(account); } function addSignedWhitelistAdmin(address account, bytes memory signature) public { address signer = getWhitelistedRoleActionSigner('addSignedWhitelistAdmin', account, signature); require(signer != address(0), "Invalid signature"); require(isWhitelistAdmin(signer), "signer is not an admin"); _addWhitelistAdmin(account); } function getWhitelistedRoleActionSigner(string memory action, address account, bytes memory _signature) private view returns (address) { bytes32 msgHash = OpenZeppelinUpgradesECDSA.toEthSignedMessageHash( keccak256( abi.encodePacked( action, account, address(this) ) ) ); return OpenZeppelinUpgradesECDSA.recover(msgHash, _signature); } } // File: contracts/utils/ReentrancyGuardEmber.sol pragma solidity ^0.5.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. * * This is the exact same contract implemented by the openzeppelin team here: * https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/master/contracts/utils/ReentrancyGuard.sol * The contract name clashes with the version used in the set protocol dependency * and had to be renamed to be used in this project. */ contract ReentrancyGuardEmber is Initializable { // counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; function initialize() public initializer { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @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() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call"); } uint256[50] private ______gap; } // File: openzeppelin-solidity/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: set-protocol-contract-utils/contracts/lib/CommonMath.sol /* Copyright 2018 Set Labs 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. */ pragma solidity 0.5.7; library CommonMath { using SafeMath for uint256; uint256 public constant SCALE_FACTOR = 10 ** 18; uint256 public constant MAX_UINT_256 = 2 ** 256 - 1; /** * Returns scale factor equal to 10 ** 18 * * @return 10 ** 18 */ function scaleFactor() internal pure returns (uint256) { return SCALE_FACTOR; } /** * Calculates and returns the maximum value for a uint256 * * @return The maximum value for uint256 */ function maxUInt256() internal pure returns (uint256) { return MAX_UINT_256; } /** * Increases a value by the scale factor to allow for additional precision * during mathematical operations */ function scale( uint256 a ) internal pure returns (uint256) { return a.mul(SCALE_FACTOR); } /** * Divides a value by the scale factor to allow for additional precision * during mathematical operations */ function deScale( uint256 a ) internal pure returns (uint256) { return a.div(SCALE_FACTOR); } /** * @dev Performs the power on a specified value, reverts on overflow. */ function safePower( uint256 a, uint256 pow ) internal pure returns (uint256) { require(a > 0); uint256 result = 1; for (uint256 i = 0; i < pow; i++){ uint256 previousResult = result; // Using safemath multiplication prevents overflows result = previousResult.mul(a); } return result; } /** * @dev Performs division where if there is a modulo, the value is rounded up */ function divCeil(uint256 a, uint256 b) internal pure returns(uint256) { return a.mod(b) > 0 ? a.div(b).add(1) : a.div(b); } /** * Checks for rounding errors and returns value of potential partial amounts of a principal * * @param _principal Number fractional amount is derived from * @param _numerator Numerator of fraction * @param _denominator Denominator of fraction * @return uint256 Fractional amount of principal calculated */ function getPartialAmount( uint256 _principal, uint256 _numerator, uint256 _denominator ) internal pure returns (uint256) { // Get remainder of partial amount (if 0 not a partial amount) uint256 remainder = mulmod(_principal, _numerator, _denominator); // Return if not a partial amount if (remainder == 0) { return _principal.mul(_numerator).div(_denominator); } // Calculate error percentage uint256 errPercentageTimes1000000 = remainder.mul(1000000).div(_numerator.mul(_principal)); // Require error percentage is less than 0.1%. require( errPercentageTimes1000000 < 1000, "CommonMath.getPartialAmount: Rounding error exceeds bounds" ); return _principal.mul(_numerator).div(_denominator); } /* * Gets the rounded up log10 of passed value * * @param _value Value to calculate ceil(log()) on * @return uint256 Output value */ function ceilLog10( uint256 _value ) internal pure returns (uint256) { // Make sure passed value is greater than 0 require ( _value > 0, "CommonMath.ceilLog10: Value must be greater than zero." ); // Since log10(1) = 0, if _value = 1 return 0 if (_value == 1) return 0; // Calcualte ceil(log10()) uint256 x = _value - 1; uint256 result = 0; if (x >= 10 ** 64) { x /= 10 ** 64; result += 64; } if (x >= 10 ** 32) { x /= 10 ** 32; result += 32; } if (x >= 10 ** 16) { x /= 10 ** 16; result += 16; } if (x >= 10 ** 8) { x /= 10 ** 8; result += 8; } if (x >= 10 ** 4) { x /= 10 ** 4; result += 4; } if (x >= 100) { x /= 100; result += 2; } if (x >= 10) { result += 1; } return result + 1; } } // File: set-protocol-contracts/contracts/lib/IERC20.sol /* Copyright 2018 Set Labs 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. */ pragma solidity 0.5.7; /** * @title IERC20 * @author Set Protocol * * Interface for using ERC20 Tokens. This interface is needed to interact with tokens that are not * fully ERC20 compliant and return something other than true on successful transfers. */ interface IERC20 { function balanceOf( address _owner ) external view returns (uint256); function allowance( address _owner, address _spender ) external view returns (uint256); function transfer( address _to, uint256 _quantity ) external; function transferFrom( address _from, address _to, uint256 _quantity ) external; function approve( address _spender, uint256 _quantity ) external returns (bool); function totalSupply() external returns (uint256); } // File: set-protocol-contracts/contracts/lib/ERC20Wrapper.sol /* Copyright 2018 Set Labs 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. */ pragma solidity 0.5.7; /** * @title ERC20Wrapper * @author Set Protocol * * This library contains functions for interacting wtih ERC20 tokens, even those not fully compliant. * For all functions we will only accept tokens that return a null or true value, any other values will * cause the operation to revert. */ library ERC20Wrapper { // ============ Internal Functions ============ /** * Check balance owner's balance of ERC20 token * * @param _token The address of the ERC20 token * @param _owner The owner who's balance is being checked * @return uint256 The _owner's amount of tokens */ function balanceOf( address _token, address _owner ) external view returns (uint256) { return IERC20(_token).balanceOf(_owner); } /** * Checks spender's allowance to use token's on owner's behalf. * * @param _token The address of the ERC20 token * @param _owner The token owner address * @param _spender The address the allowance is being checked on * @return uint256 The spender's allowance on behalf of owner */ function allowance( address _token, address _owner, address _spender ) internal view returns (uint256) { return IERC20(_token).allowance(_owner, _spender); } /** * Transfers tokens from an address. Handle's tokens that return true or null. * If other value returned, reverts. * * @param _token The address of the ERC20 token * @param _to The address to transfer to * @param _quantity The amount of tokens to transfer */ function transfer( address _token, address _to, uint256 _quantity ) external { IERC20(_token).transfer(_to, _quantity); // Check that transfer returns true or null require( checkSuccess(), "ERC20Wrapper.transfer: Bad return value" ); } /** * Transfers tokens from an address (that has set allowance on the proxy). * Handle's tokens that return true or null. If other value returned, reverts. * * @param _token The address of the ERC20 token * @param _from The address to transfer from * @param _to The address to transfer to * @param _quantity The number of tokens to transfer */ function transferFrom( address _token, address _from, address _to, uint256 _quantity ) external { IERC20(_token).transferFrom(_from, _to, _quantity); // Check that transferFrom returns true or null require( checkSuccess(), "ERC20Wrapper.transferFrom: Bad return value" ); } /** * Grants spender ability to spend on owner's behalf. * Handle's tokens that return true or null. If other value returned, reverts. * * @param _token The address of the ERC20 token * @param _spender The address to approve for transfer * @param _quantity The amount of tokens to approve spender for */ function approve( address _token, address _spender, uint256 _quantity ) internal { IERC20(_token).approve(_spender, _quantity); // Check that approve returns true or null require( checkSuccess(), "ERC20Wrapper.approve: Bad return value" ); } /** * Ensure's the owner has granted enough allowance for system to * transfer tokens. * * @param _token The address of the ERC20 token * @param _owner The address of the token owner * @param _spender The address to grant/check allowance for * @param _quantity The amount to see if allowed for */ function ensureAllowance( address _token, address _owner, address _spender, uint256 _quantity ) internal { uint256 currentAllowance = allowance(_token, _owner, _spender); if (currentAllowance < _quantity) { approve( _token, _spender, CommonMath.maxUInt256() ); } } // ============ Private Functions ============ /** * Checks the return value of the previous function up to 32 bytes. Returns true if the previous * function returned 0 bytes or 1. */ function checkSuccess( ) private pure returns (bool) { // default to failure uint256 returnValue = 0; assembly { // check number of bytes returned from last function call switch returndatasize // no bytes returned: assume success case 0x0 { returnValue := 1 } // 32 bytes returned case 0x20 { // copy 32 bytes into scratch space returndatacopy(0x0, 0x0, 0x20) // load those bytes into returnValue returnValue := mload(0x0) } // not sure what was returned: dont mark as success default { } } // check if returned value is one or nothing return returnValue == 1; } } // File: interfaces/IWETH.sol /* Copyright 2018 Set Labs 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. */ pragma solidity 0.5.7; /** * @title IWETH * @author Set Protocol * * Interface for Wrapped Ether. This interface allows for interaction for wrapped ether's deposit and withdrawal * functionality. */ interface IWETH { function deposit() external payable; function withdraw( uint256 wad ) external; } // File: interfaces/IVault.sol pragma solidity 0.5.7; /** * @title IVault * @author Ember Fund * * Interface for Vaults. This interface allows for interaction for Vault's deposit and withdrawal * functionality. */ interface IVault { function deposit(uint amount) external; function withdraw(uint shares) external; } // File: contracts/utils/ChiGasSaver.sol pragma solidity ^0.5.7; pragma experimental ABIEncoderV2; interface ChiGasSaver { function freeFromUpTo(address from, uint256 value) external returns (uint256 freed); function approve(address spender, uint256 amount) external returns (bool); function allowance(address _owner, address _spender) view external returns (uint256 remaining); } // File: contracts/SmartWalletVault.sol /* Copyright 2018 Ember Fund 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. */ pragma solidity ^0.5.0; /** * @title SmartWallet * @author Ember Fund * * Implementation of the Ember Fund smart wallet adding meta transaction capabilities for issuing and redeeming rebalancing sets. * The smart wallet is owned by an EOA that can white list accounts facilitating the management of any ERC20 tokens stored in the smart wallet. */ contract SmartWalletVault is Initializable, ReentrancyGuardEmber, WhitelistedRoleMeta { using SafeMath for uint256; // Nonces to prevent replay attacks mapping(uint256 => bool) private nonces; uint16 public constant version = 3; // Gas token saver ChiGasSaver public constant chiGasSaver = ChiGasSaver(0x0000000000004946c0e9F43F4Dee607b0eF1fA1c); modifier discountChiGasSaver { uint256 gasStart = gasleft(); _; uint256 gasSpent = 21000 + gasStart - gasleft() + 16 * msg.data.length; uint256 allowance = chiGasSaver.allowance(msg.sender, address(this)); uint256 chiTokensToSpend = (gasSpent + 14154) / 41947; if (allowance < chiTokensToSpend) { chiGasSaver.approve(address(this), chiTokensToSpend); } chiGasSaver.freeFromUpTo(msg.sender, chiTokensToSpend); } mapping(address => address) public depositTokenAddressToYVault; mapping(address => address) public yVaultToDepositTokenAddress; /** * Initialize the smart contract with an owner. */ function initialize(address _owner) public initializer { WhitelistedRoleMeta.initialize(_owner); ReentrancyGuardEmber.initialize(); // Add more deposit to vault mapping to support more vaults // USDT 0xdAC17F958D2ee523a2206206994597C13D831ec7 // yEarn USDT 0x2f08119C6f07c006695E079AAFc638b8789FAf18 depositTokenAddressToYVault[0xdAC17F958D2ee523a2206206994597C13D831ec7] = 0x2f08119C6f07c006695E079AAFc638b8789FAf18; yVaultToDepositTokenAddress[0x2f08119C6f07c006695E079AAFc638b8789FAf18] = 0xdAC17F958D2ee523a2206206994597C13D831ec7; } function() external payable { } // Prod addresses // address constant public transfersProxy = 0x882d80D3a191859d64477eb78Cca46599307ec1C; // address payable constant public rebalancingSetExchangeIssuanceModule = 0xde697AC56b1bD9C0987c08911020f2341e274813; // address payable constant public rebalancingSetIssuanceModule = 0xDA6786379FF88729264d31d472FA917f5E561443; // address payable constant public cTokenaddressToAddressWhiteList = 0x5BA020a8835ed40936941562bdF42D66F65fc00f; function getTransfersProxy() public view returns (address) { return 0x882d80D3a191859d64477eb78Cca46599307ec1C; } function getRebalancingSetExchangeIssuanceModule() public view returns (address payable) { return 0xde697AC56b1bD9C0987c08911020f2341e274813; } function getRebalancingSetIssuanceModule() public view returns (address payable) { return 0xDA6786379FF88729264d31d472FA917f5E561443; } function getCTokenaddressToAddressWhiteList() public view returns (address payable) { return 0x5BA020a8835ed40936941562bdF42D66F65fc00f; } function getWrappedEthInstance() public view returns (IWETH) { return IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); } /** * Withdraw all ERC20 tokens from this contract to the caller address. Only callable by the smart contract owner. */ function withdrawAllAdmin(address [] calldata _tokenAddresses) external nonReentrant onlyWhitelistAdmin { for (uint i=0; i<_tokenAddresses.length; i++) { uint256 tokenBalance = ERC20Wrapper.balanceOf(_tokenAddresses[i], address(this)); ERC20Wrapper.transfer( _tokenAddresses[i], msg.sender, tokenBalance ); } } /** * Withdraw an ERC20 token to the owner's account. */ function withdrawERC20(address _tokenAddress, address _to, uint256 _withdrawalAmount) external nonReentrant onlyWhitelisted { uint256 tokenBalance = ERC20Wrapper.balanceOf(_tokenAddress, address(this)); require(tokenBalance >= _withdrawalAmount, "Withdrawal amount is too high"); require(this.isWhitelistAdmin(_to), "You can only withdraw to an owner address"); ERC20Wrapper.transfer( _tokenAddress, _to, _withdrawalAmount ); } /** * Withdraw ETH to the owner's account. */ function withdrawETH(address payable _to, uint256 _withdrawalAmount) external nonReentrant onlyWhitelisted { uint256 ethBalance = address(this).balance; require(ethBalance >= _withdrawalAmount, "Withdrawal amount is too high"); require(this.isWhitelistAdmin(_to), "You can only withdraw to an owner address"); _to.transfer(_withdrawalAmount); } function _checkReplayAttack( uint256 _nonce ) private nonReentrant { require(!nonces[_nonce], "Replay attack detected."); nonces[_nonce] = true; } /** * Get the signer of vault deposit. */ function getVaultDepositSigner(address _vaultAddress, address _tokenDepositAddress, uint256 _nonce, bytes memory _signature) private view returns (address) { bytes32 msgHash = OpenZeppelinUpgradesECDSA.toEthSignedMessageHash( keccak256( abi.encodePacked( _vaultAddress, _tokenDepositAddress, _nonce, address(this) ) ) ); return OpenZeppelinUpgradesECDSA.recover(msgHash, _signature); } function vaultDeposit( address _vaultAddress, address _tokenDepositAddress, uint256 _amount, uint256 _nonce, bytes memory _signature ) public nonReentrant discountChiGasSaver { _checkReplayAttack(_nonce); require(depositTokenAddressToYVault[_tokenDepositAddress] == _vaultAddress, "Deposit token and vault not supported"); address signer = getVaultDepositSigner(_vaultAddress, _tokenDepositAddress, _nonce, _signature); require(signer != address(0), "Invalid signature"); require(isWhitelistAdmin(signer), "signer is not an admin"); uint256 tokenDepositBalance = ERC20Wrapper.balanceOf(_tokenDepositAddress, address(this)); require(tokenDepositBalance >= _amount, "Token deposit balance is too low"); // Approve the vault to spend the SMA's owner's deposit token's // Required for certain stable coins (USDT for example) ERC20Wrapper.approve(_tokenDepositAddress, _vaultAddress, 0); ERC20Wrapper.approve(_tokenDepositAddress, _vaultAddress, _amount); // Deposit tokens to the vault IVault(_vaultAddress).deposit(_amount); } /** * Get the signer of a vault withdrawal. */ function getVaultWithdrawalSigner(address _vaultAddress, address payable _to, uint256 _nonce, bytes memory _signature) private view returns (address) { bytes32 msgHash = OpenZeppelinUpgradesECDSA.toEthSignedMessageHash( keccak256( abi.encodePacked( _vaultAddress, _to, _nonce, address(this) ) ) ); return OpenZeppelinUpgradesECDSA.recover(msgHash, _signature); } function vaultWithdraw( address _vaultAddress, uint shares, address payable _to, uint256 _nonce, bytes memory _signature ) public nonReentrant discountChiGasSaver { _checkReplayAttack(_nonce); address depositTokenAddress = yVaultToDepositTokenAddress[_vaultAddress]; require(depositTokenAddress != address(0), "Vault not supported"); address signer = getVaultWithdrawalSigner(_vaultAddress, _to, _nonce, _signature); require(signer != address(0), "Invalid signature"); require(isWhitelistAdmin(signer), "signer is not an admin"); // Get current balance of the deposit token before withdrawal uint256 depositTokenBalanceBeforeWithdrawal = ERC20Wrapper.balanceOf(depositTokenAddress, address(this)); // Withdraw shares of the vault to deposit token IVault(_vaultAddress).withdraw(shares); // Compute how many deposit tokens were withdrawn uint256 depositTokenWithdrawn = ERC20Wrapper.balanceOf(depositTokenAddress, address(this)).sub(depositTokenBalanceBeforeWithdrawal); require(depositTokenWithdrawn > 0, "No token withdrawn"); // Transfer withdrawn tokens to address passed as parameter ERC20Wrapper.transfer( depositTokenAddress, _to, depositTokenWithdrawn ); } }
Withdraw ETH to the owner's account./
function withdrawETH(address payable _to, uint256 _withdrawalAmount) external nonReentrant onlyWhitelisted { uint256 ethBalance = address(this).balance; require(ethBalance >= _withdrawalAmount, "Withdrawal amount is too high"); require(this.isWhitelistAdmin(_to), "You can only withdraw to an owner address"); _to.transfer(_withdrawalAmount); }
7,692,780
/** *Submitted for verification at Etherscan.io on 2021-07-19 */ /// // GasBack Technology // https://gasback.tech/ // // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @dev Implementation of the {IBEP20} 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 {BEP20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-BEP20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of BEP20 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 {IBEP20-approve}. */ pragma solidity >=0.6.0 <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 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; } } pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @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(_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 { 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 virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity >=0.6.4; interface IBEP20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8); /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the token name. */ function name() external view returns (string memory); /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address); /** * @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 BEP20 is Context, IBEP20, Ownable { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor(string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the bep token owner. */ function getOwner() external override view returns (address) { return owner(); } /** * @dev Returns the name of the token. */ function name() public override view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public override view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. */ function decimals() public override view returns (uint8) { return _decimals; } /** * @dev See {BEP20-totalSupply}. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @dev See {BEP20-balanceOf}. */ function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } /** * @dev See {BEP20-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 override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {BEP20-allowance}. */ function allowance(address owner, address spender) public override view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {BEP20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {BEP20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {BEP20}; * * 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 override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, 'BEP20: transfer amount exceeds allowance') ); 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 {BEP20-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(_msgSender(), spender, _allowances[_msgSender()][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 {BEP20-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(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, 'BEP20: decreased allowance below zero')); return true; } /** * @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing * the total supply. * * Requirements * * - `msg.sender` must be the token owner */ function mint(uint256 amount) public onlyOwner returns (bool) { _mint(_msgSender(), amount); 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), 'BEP20: transfer from the zero address'); require(recipient != address(0), 'BEP20: transfer to the zero address'); _balances[sender] = _balances[sender].sub(amount, 'BEP20: transfer amount exceeds balance'); _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), 'BEP20: mint to the zero address'); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(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 { require(account != address(0), 'BEP20: burn from the zero address'); _balances[account] = _balances[account].sub(amount, 'BEP20: burn amount exceeds balance'); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @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 amount) internal { require(owner != address(0), 'BEP20: approve from the zero address'); require(spender != address(0), 'BEP20: approve to the zero address'); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `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, _msgSender(), _allowances[account][_msgSender()].sub(amount, 'BEP20: burn amount exceeds allowance')); } } // GasFuel contract GasBackFuel is BEP20('GasFuel', 'GASF') { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } pragma solidity >=0.6.0 <0.8.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. */ 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; } } pragma solidity >=0.6.2 <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; // 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); } 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); } } } } /** * @title SafeBEP20 * @dev Wrappers around BEP20 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 SafeBEP20 for IBEP20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeBEP20 { using SafeMath for uint256; using Address for address; function safeTransfer(IBEP20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IBEP20 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 * {IBEP20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IBEP20 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), "SafeBEP20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IBEP20 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(IBEP20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeBEP20: 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(IBEP20 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, "SafeBEP20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeBEP20: BEP20 operation did not succeed"); } } } // MasterChef is the Owner of GasBackFuel and has super powers. // He keeps track of rewards and the most recent TX Gas Price. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once governance is sufficiently // distributed and the community can be shown to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MasterChef is Ownable { using SafeMath for uint256; using SafeBEP20 for IBEP20; // Most recent GasPrice, used for tracking on Web dApp uint256 public latestGasPrice = 0; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of Gas // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accGasPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accGasPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IBEP20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. Gas to distribute per block. uint256 lastRewardBlock; // Last block number that Gas distribution occurs. uint256 accGasPerShare; // Accumulated Gas per share, times 1e12. See below. uint16 depositFeeBP; // Deposit fee in basis points } // The GasBackFuel Token GasBackFuel public gasback; // Dev address. address public devaddr; // Gas tokens created per block. uint256 public gasbackPerBlock; // Bonus muliplier for early gasback makers. uint256 public constant BONUS_MULTIPLIER = 1; // Treasury address address public treasuryAddress; // Ensure we can't add same pool twice mapping (address => bool) private poolIsAdded; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( GasBackFuel _gasback, address _devaddr, address _treasuryAddress, uint256 _gasbackPerBlock, uint256 _startBlock ) public { gasback = _gasback; devaddr = _devaddr; treasuryAddress = _treasuryAddress; gasbackPerBlock = _gasbackPerBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. function add(uint256 _allocPoint, IBEP20 _lpToken, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner { require(_depositFeeBP <= 10000, "add: invalid deposit fee basis points"); if (_withUpdate) { massUpdatePools(); } // EDIT: Don't add same pool twice, fixed in code with check require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accGasPerShare: 0, depositFeeBP: _depositFeeBP })); } // Update the given pool's Gas allocation point and deposit fee. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner { require(_depositFeeBP <= 10000, "set: invalid deposit fee basis points"); if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].depositFeeBP = _depositFeeBP; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } // View function to see pending Gass on frontend. function pendingGas(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accGasPerShare = pool.accGasPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 gasbackReward = multiplier.mul(gasbackPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accGasPerShare = accGasPerShare.add(gasbackReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accGasPerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { // Added to set recent latestGasPrice latestGasPrice = tx.gasprice; PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0 || pool.allocPoint == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 gasbackReward = multiplier.mul(gasbackPerBlock).mul(pool.allocPoint).div(totalAllocPoint); gasback.mint(devaddr, gasbackReward.div(10)); gasback.mint(address(this), gasbackReward); pool.accGasPerShare = pool.accGasPerShare.add(gasbackReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for Gas allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accGasPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeGasTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if(pool.depositFeeBP > 0){ uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000); pool.lpToken.safeTransfer(treasuryAddress, depositFee); user.amount = user.amount.add(_amount).sub(depositFee); }else{ user.amount = user.amount.add(_amount); } } user.rewardDebt = user.amount.mul(pool.accGasPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accGasPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeGasTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accGasPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Safe gasback transfer function, just in case if rounding error causes pool to not have enough Gas. function safeGasTransfer(address _to, uint256 _amount) internal { uint256 gasbackBal = gasback.balanceOf(address(this)); if (_amount > gasbackBal) { gasback.transfer(_to, gasbackBal); } else { gasback.transfer(_to, _amount); } } function dev(address _devaddr) public onlyOwner { devaddr = _devaddr; } function setTreasuryAddress(address _treasuryAddress) public onlyOwner { treasuryAddress = _treasuryAddress; } function updateEmissionRate(uint256 _gasbackPerBlock) public onlyOwner { massUpdatePools(); gasbackPerBlock = _gasbackPerBlock; } }
Update reward variables of the given pool to be up-to-date. Added to set recent latestGasPrice
function updatePool(uint256 _pid) public { latestGasPrice = tx.gasprice; PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0 || pool.allocPoint == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 gasbackReward = multiplier.mul(gasbackPerBlock).mul(pool.allocPoint).div(totalAllocPoint); gasback.mint(devaddr, gasbackReward.div(10)); gasback.mint(address(this), gasbackReward); pool.accGasPerShare = pool.accGasPerShare.add(gasbackReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; }
2,179,022
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; import {ERC20} from "@rari-capital/solmate/src/tokens/ERC20.sol"; import {SafeTransferLib} from "@rari-capital/solmate/src/utils/SafeTransferLib.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {IAaveV2StablecoinCellar} from "./interfaces/IAaveV2StablecoinCellar.sol"; import {IAaveIncentivesController} from "./interfaces/IAaveIncentivesController.sol"; import {IStakedTokenV2} from "./interfaces/IStakedTokenV2.sol"; import {ICurveSwaps} from "./interfaces/ICurveSwaps.sol"; import {ISushiSwapRouter} from "./interfaces/ISushiSwapRouter.sol"; import {IGravity} from "./interfaces/IGravity.sol"; import {ILendingPool} from "./interfaces/ILendingPool.sol"; import {MathUtils} from "./utils/MathUtils.sol"; /** * @title Sommelier Aave V2 Stablecoin Cellar * @notice Dynamic ERC4626 that adapts strategies to always get the best yield for stablecoins on Aave. * @author Brian Le */ contract AaveV2StablecoinCellar is IAaveV2StablecoinCellar, ERC20, Ownable { using SafeTransferLib for ERC20; using MathUtils for uint256; /** * @notice The asset that makes up the cellar's holding pool. Will change whenever the cellar * rebalances into a new strategy. * @dev The cellar denotes its inactive assets in this token. While it waits in the holding pool * to be entered into a strategy, it is used to pay for withdraws from those redeeming their * shares. */ ERC20 public asset; /** * @notice An interest-bearing derivative of the current asset returned by Aave for lending * assets. Represents cellar's portion of active assets earning yield in a lending * strategy. */ ERC20 public assetAToken; /** * @notice The decimals of precision used by the current asset. * @dev Some stablecoins (eg. USDC and USDT) don't use the standard 18 decimals of precision. * This is used for converting between decimals when performing calculations in the cellar. */ uint8 public assetDecimals; /** * @notice Mapping from a user's address to all their deposits and balances. * @dev Used in determining which of a user's shares are active (entered into a strategy earning * yield vs inactive (waiting in the holding pool to be entered into a strategy and not * earning yield). */ mapping(address => UserDeposit[]) public userDeposits; /** * @notice Mapping from user's address to the index of first non-zero deposit in `userDeposits`. * @dev Saves gas when looping through all user's deposits. */ mapping(address => uint256) public currentDepositIndex; /** * @notice Last time all inactive assets were entered into a strategy and made active. */ uint256 public lastTimeEnteredStrategy; /** * @notice The value fees are divided by to get a percentage. Represents maximum percent (100%). */ uint256 public constant DENOMINATOR = 100_00; /** * @notice The percentage of platform fees (1%) taken off of active assets over a year. */ uint256 public constant PLATFORM_FEE = 1_00; /** * @notice The percentage of performance fees (5%) taken off of cellar gains. */ uint256 public constant PERFORMANCE_FEE = 5_00; /** * @notice Timestamp of last time platform fees were accrued. */ uint256 public lastTimeAccruedPlatformFees; /** * @notice Amount of active assets in cellar last time performance fees were accrued. */ uint256 public lastActiveAssets; /** * @notice Normalized income index for the current asset on Aave recorded last time performance * fees were accrued. */ uint256 public lastNormalizedIncome; /** * @notice Amount of platform fees that have been accrued awaiting transfer. * @dev Fees are taken in shares and redeemed for assets at the time they are transferred from * the cellar to Cosmos to be distributed. */ uint256 public accruedPlatformFees; /** * @notice Amount of performance fees that have been accrued awaiting transfer. * @dev Fees are taken in shares and redeemed for assets at the time they are transferred from * the cellar to Cosmos to be distributed. */ uint256 public accruedPerformanceFees; /** * @notice Cosmos address of the fee distributor as a hex value. * @dev The Gravity contract expects a 32-byte value formatted in a specific way. */ bytes32 public constant feesDistributor = hex"000000000000000000000000b813554b423266bbd4c16c32fa383394868c1f55"; /** * @notice Maximum amount of assets that can be managed by the cellar. Denominated in the same * units as the current asset. * @dev Limited to $5m until after security audits. */ uint256 public maxLiquidity; /** * @notice Whether or not the contract is paused in case of an emergency. */ bool public isPaused; /** * @notice Whether or not the contract is permanently shutdown in case of an emergency. */ bool public isShutdown; // ======================================== IMMUTABLES ======================================== // Curve Registry Exchange contract ICurveSwaps public immutable curveRegistryExchange; // 0xD1602F68CC7C4c7B59D686243EA35a9C73B0c6a2 // SushiSwap Router V2 contract ISushiSwapRouter public immutable sushiswapRouter; // 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F // Aave Lending Pool V2 contract ILendingPool public immutable lendingPool; // 0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9 // Aave Incentives Controller V2 contract IAaveIncentivesController public immutable incentivesController; // 0xd784927Ff2f95ba542BfC824c8a8a98F3495f6b5 // Cosmos Gravity Bridge contract IGravity public immutable gravityBridge; // 0x69592e6f9d21989a043646fE8225da2600e5A0f7 IStakedTokenV2 public immutable stkAAVE; // 0x4da27a545c0c5B758a6BA100e3a049001de870f5 ERC20 public immutable AAVE; // 0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9 ERC20 public immutable WETH; // 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 /** * @dev Owner of the cellar will be the Gravity contract controlled by Steward: * https://github.com/cosmos/gravity-bridge/blob/main/solidity/contracts/Gravity.sol * https://github.com/PeggyJV/steward * @param _asset current asset managed by the cellar * @param _curveRegistryExchange Curve registry exchange * @param _sushiswapRouter Sushiswap V2 router address * @param _lendingPool Aave V2 lending pool address * @param _incentivesController _incentivesController * @param _gravityBridge Cosmos Gravity Bridge address * @param _stkAAVE stkAAVE address * @param _AAVE AAVE address * @param _WETH WETH address */ constructor( ERC20 _asset, ICurveSwaps _curveRegistryExchange, ISushiSwapRouter _sushiswapRouter, ILendingPool _lendingPool, IAaveIncentivesController _incentivesController, IGravity _gravityBridge, IStakedTokenV2 _stkAAVE, ERC20 _AAVE, ERC20 _WETH ) ERC20("Sommelier Aave V2 Stablecoin Cellar LP Token", "aave2-CLR-S", 18) Ownable() { curveRegistryExchange = _curveRegistryExchange; sushiswapRouter = _sushiswapRouter; lendingPool = _lendingPool; incentivesController = _incentivesController; gravityBridge = _gravityBridge; stkAAVE = _stkAAVE; AAVE = _AAVE; WETH = _WETH; // Initialize asset. _updateStrategy(address(_asset)); // Initialize starting point for platform fee accrual to time when cellar was created. // Otherwise it would incorrectly calculate how much platform fees to take when accrueFees // is called for the first time. lastTimeAccruedPlatformFees = block.timestamp; } // =============================== DEPOSIT/WITHDRAWAL OPERATIONS =============================== /** * @notice Deposits assets and mints the shares to receiver. * @param assets amount of assets to deposit * @param receiver address receiving the shares * @return shares amount of shares minted */ function deposit(uint256 assets, address receiver) external returns (uint256 shares) { // In the case where a user tries to deposit more than their balance, the desired behavior // is to deposit what they have instead of reverting. uint256 maxDepositable = asset.balanceOf(msg.sender); if (assets > maxDepositable) assets = maxDepositable; (, shares) = _deposit(assets, 0, receiver); } /** * @notice Mints shares to receiver by depositing assets. * @param shares amount of shares to mint * @param receiver address receiving the shares * @return assets amount of assets deposited */ function mint(uint256 shares, address receiver) external returns (uint256 assets) { // In the case where a user tries to mint more shares than possible, the desired behavior // is to mint as many shares as their balance allows instead of reverting. uint256 maxMintable = previewDeposit(asset.balanceOf(msg.sender)); if (shares > maxMintable) shares = maxMintable; (assets, ) = _deposit(0, shares, receiver); } function _deposit(uint256 assets, uint256 shares, address receiver) internal returns (uint256, uint256) { // In case of an emergency or contract vulnerability, we don't want users to be able to // deposit more assets into a compromised contract. if (isPaused) revert ContractPaused(); if (isShutdown) revert ContractShutdown(); // Must calculate before assets are transferred in. shares > 0 ? assets = previewMint(shares) : shares = previewDeposit(assets); // Check for rounding error on `deposit` since we round down in previewDeposit. No need to // check for rounding error if `mint`, previewMint rounds up. if (shares == 0) revert ZeroShares(); // Check if security restrictions still apply. Enforce them if they do. if (maxLiquidity != type(uint256).max) { if (assets + totalAssets() > maxLiquidity) revert LiquidityRestricted(maxLiquidity); if (assets > maxDeposit(receiver)) revert DepositRestricted(50_000 * 10**assetDecimals); } // Transfers assets into the cellar. asset.safeTransferFrom(msg.sender, address(this), assets); // Mint user tokens that represents their share of the cellar's assets. _mint(receiver, shares); // Store the user's deposit data. This will be used later on when the user wants to withdraw // their assets or transfer their shares. UserDeposit[] storage deposits = userDeposits[receiver]; deposits.push(UserDeposit({ // Always store asset amounts with 18 decimals of precision regardless of the asset's // decimals. This is so we can still use this data even after rebalancing to different // asset. assets: uint112(assets.changeDecimals(assetDecimals, decimals)), shares: uint112(shares), timeDeposited: uint32(block.timestamp) })); emit Deposit( msg.sender, receiver, address(asset), assets, shares ); return (assets, shares); } /** * @notice Withdraws assets to receiver by redeeming shares from owner. * @param assets amount of assets being withdrawn * @param receiver address of account receiving the assets * @param owner address of the owner of the shares being redeemed * @return shares amount of shares redeemed */ function withdraw( uint256 assets, address receiver, address owner ) external returns (uint256 shares) { // This is done to avoid the possibility of an overflow if `assets` was set to a very high // number (like 2**256 – 1) when trying to change decimals. If a user tries to withdraw // more than their balance, the desired behavior is to withdraw as much as possible. uint256 maxWithdrawable = previewRedeem(balanceOf[owner]); if (assets > maxWithdrawable) assets = maxWithdrawable; // Ensures proceeding calculations are done with a standard 18 decimals of precision. Will // change back to the using the asset's usual decimals of precision when transferring assets // after all calculations are done. assets = assets.changeDecimals(assetDecimals, decimals); (, shares) = _withdraw(assets, receiver, owner); } /** * @notice Redeems shares from owner to withdraw assets to receiver. * @param shares amount of shares redeemed * @param receiver address of account receiving the assets * @param owner address of the owner of the shares being redeemed * @return assets amount of assets sent to receiver */ function redeem( uint256 shares, address receiver, address owner ) external returns (uint256 assets) { // This is done to avoid the possibility of an overflow if `shares` was set to a very high // number (like 2**256 – 1) when trying to change decimals. If a user tries to redeem more // than their balance, the desired behavior is to redeem as much as possible. uint256 maxRedeemable = maxRedeem(owner); if (shares > maxRedeemable) shares = maxRedeemable; (assets, ) = _withdraw(_convertToAssets(shares), receiver, owner); } /// @dev `assets` must be passed in with 18 decimals of precision. Should extend/truncate decimals of /// the amount passed in if necessary to ensure this is true. function _withdraw( uint256 assets, address receiver, address owner ) internal returns (uint256, uint256) { if (balanceOf[owner] == 0) revert ZeroShares(); if (assets == 0) revert ZeroAssets(); // Tracks the total amount of shares being redeemed for the amount of assets withdrawn. uint256 shares; // Retrieve the user's deposits to begin looping through them, generally from oldest to // newest deposits. This may not be the case though if shares have been transferred to the // owner, which will be added to the end of the owner's deposits regardless of time // deposited. UserDeposit[] storage deposits = userDeposits[owner]; // Tracks the amount of assets left to withdraw. Updated at the end of each loop. uint256 leftToWithdraw = assets; // Saves gas by avoiding calling `_convertToAssets` on active shares during each loop. uint256 exchangeRate = _convertToAssets(1e18); for (uint256 i = currentDepositIndex[owner]; i < deposits.length; i++) { UserDeposit storage d = deposits[i]; // Whether or not deposited shares are active or inactive. bool isActive = d.timeDeposited <= lastTimeEnteredStrategy; // If shares are active, convert them to the amount of assets they're worth to see the // maximum amount of assets we can take from this deposit. uint256 dAssets = isActive ? uint256(d.shares).mulWadDown(exchangeRate) : d.assets; // Determine the amount of assets and shares to withdraw from this deposit. uint256 withdrawnAssets = MathUtils.min(leftToWithdraw, dAssets); uint256 withdrawnShares = uint256(d.shares).mulDivUp(withdrawnAssets, dAssets); // For active shares, deletes the deposit data we don't need anymore for a gas refund. if (isActive) { delete d.assets; delete d.timeDeposited; } else { d.assets -= uint112(withdrawnAssets); } // Take the shares we need from this deposit and add them to our total. d.shares -= uint112(withdrawnShares); shares += withdrawnShares; // Update the counter of assets we have left to withdraw. leftToWithdraw -= withdrawnAssets; // Finish if this is the last deposit or there is nothing left to withdraw. if (i == deposits.length - 1 || leftToWithdraw == 0) { // Store the user's next non-zero deposit to save gas on future looping. currentDepositIndex[owner] = d.shares != 0 ? i : i+1; break; } } // If the caller is not the owner of the shares, check to see if the owner has approved them // to spend their shares. if (msg.sender != owner) { uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares; } // Redeem shares for assets. _burn(owner, shares); // Determine the total amount of assets withdrawn. assets -= leftToWithdraw; // Convert assets decimals back to get ready for transfers. assets = assets.changeDecimals(decimals, assetDecimals); // Only withdraw from strategy if holding pool does not contain enough funds. _allocateAssets(assets); // Transfer assets to receiver from the cellar's holding pool. asset.safeTransfer(receiver, assets); emit Withdraw(receiver, owner, address(asset), assets, shares); // Returns the amount of assets withdrawn and amount of shares redeemed. The amount of // assets withdrawn may differ from the amount of assets specified when calling the function // if the user has less assets then they tried withdrawing. return (assets, shares); } // ================================== ACCOUNTING OPERATIONS ================================== /** * @dev The internal functions always use 18 decimals of precision while the public functions use * as many decimals as the current asset (aka they don't change the decimals). This is * because we want the user deposit data the cellar stores to be usable across different * assets regardless of the decimals used. This means the cellar will always perform * calculations and store data with a standard of 18 decimals of precision but will change * the decimals back when transferring assets outside the contract or returning data * through public view functions. */ /** * @notice Total amount of active asset entered into a strategy. */ function activeAssets() public view returns (uint256) { // The aTokens' value is pegged to the value of the corresponding asset at a 1:1 ratio. We // can find the amount of assets active in a strategy simply by taking balance of aTokens // cellar holds. return assetAToken.balanceOf(address(this)); } function _activeAssets() internal view returns (uint256) { uint256 assets = assetAToken.balanceOf(address(this)); return assets.changeDecimals(assetDecimals, decimals); } /** * @notice Total amount of inactive asset waiting in a holding pool to be entered into a strategy. */ function inactiveAssets() public view returns (uint256) { return asset.balanceOf(address(this)); } function _inactiveAssets() internal view returns (uint256) { uint256 assets = asset.balanceOf(address(this)); return assets.changeDecimals(assetDecimals, decimals); } /** * @notice Total amount of the asset that is managed by cellar. */ function totalAssets() public view returns (uint256) { return activeAssets() + inactiveAssets(); } function _totalAssets() internal view returns (uint256) { return _activeAssets() + _inactiveAssets(); } /** * @notice The amount of shares that the cellar would exchange for the amount of assets provided * ONLY if they are active. * @param assets amount of assets to convert * @return shares the assets can be exchanged for */ function convertToShares(uint256 assets) public view returns (uint256) { assets = assets.changeDecimals(assetDecimals, decimals); return _convertToShares(assets); } function _convertToShares(uint256 assets) internal view returns (uint256) { return totalSupply == 0 ? assets : assets.mulDivDown(totalSupply, _totalAssets()); } /** * @notice The amount of assets that the cellar would exchange for the amount of shares provided * ONLY if they are active. * @param shares amount of shares to convert * @return assets the shares can be exchanged for */ function convertToAssets(uint256 shares) public view returns (uint256) { uint256 assets = _convertToAssets(shares); return assets.changeDecimals(decimals, assetDecimals); } function _convertToAssets(uint256 shares) internal view returns (uint256) { return totalSupply == 0 ? shares : shares.mulDivDown(_totalAssets(), totalSupply); } /** * @notice Simulate the effects of depositing assets at the current block, given current on-chain * conditions. * @param assets amount of assets to deposit * @return shares that will be minted */ function previewDeposit(uint256 assets) public view returns (uint256) { return convertToShares(assets); } /** * @notice Simulate the effects of minting shares at the current block, given current on-chain * conditions. * @param shares amount of shares to mint * @return assets that will be deposited */ function previewMint(uint256 shares) public view returns (uint256) { uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero. uint256 assets = supply == 0 ? shares : shares.mulDivUp(_totalAssets(), supply); return assets.changeDecimals(decimals, assetDecimals); } /** * @notice Simulate the effects of withdrawing assets at the current block, given current * on-chain conditions. Assumes the shares being redeemed are all active. * @param assets amount of assets to withdraw * @return shares that will be redeemed */ function previewWithdraw(uint256 assets) public view returns (uint256) { uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero. return supply == 0 ? assets : assets.mulDivUp(supply, totalAssets()); } /** * @notice Simulate the effects of redeeming shares at the current block, given current on-chain * conditions. Assumes the shares being redeemed are all active. * @param shares amount of sharers to redeem * @return assets that can be withdrawn */ function previewRedeem(uint256 shares) public view returns (uint256) { return convertToAssets(shares); } // ======================================= STATE INFORMATION ===================================== /** * @notice Retrieve information on a user's deposits. * @param user address of the user * @return userActiveShares amount of active shares the user has * @return userInactiveShares amount of inactive shares the user has * @return userActiveAssets amount of active assets the user has * @return userInactiveAssets amount of inactive assets the user has */ function depositBalances(address user) public view returns ( uint256 userActiveShares, uint256 userInactiveShares, uint256 userActiveAssets, uint256 userInactiveAssets ) { // Retrieve the user's deposits to begin looping through them, generally from oldest to // newest deposits. This may not be the case though if shares have been transferred to the // user, which will be added to the end of the user's deposits regardless of time // deposited. UserDeposit[] storage deposits = userDeposits[user]; // Saves gas by avoiding calling `_convertToAssets` on active shares during each loop. uint256 exchangeRate = _convertToAssets(1e18); for (uint256 i = currentDepositIndex[user]; i < deposits.length; i++) { UserDeposit storage d = deposits[i]; // Determine whether or not deposit is active or inactive. if (d.timeDeposited <= lastTimeEnteredStrategy) { // Saves an extra SLOAD if active and cast type to uint256. uint256 dShares = d.shares; userActiveShares += dShares; userActiveAssets += dShares.mulWadDown(exchangeRate); // Convert shares to assets. } else { userInactiveShares += d.shares; userInactiveAssets += d.assets; } } // Return assets in their original units. userActiveAssets = userActiveAssets.changeDecimals(decimals, assetDecimals); userInactiveAssets = userInactiveAssets.changeDecimals(decimals, assetDecimals); } /** * @notice Returns the number of deposits for a user. Can be used off-chain to * make iterating through user stakes easier. * @param user address of the user * @return deposits the number of deposits for the user */ function numDeposits(address user) external view returns (uint256) { return userDeposits[user].length; } // =========================== DEPOSIT/WITHDRAWAL LIMIT OPERATIONS =========================== /** * @notice Total number of assets that can be deposited by owner into the cellar. * @dev Until after security audits, limits deposits to $50k per wallet. * @param owner address of account that would receive the shares * @return maximum amount of assets that can be deposited */ function maxDeposit(address owner) public view returns (uint256) { if (isShutdown || isPaused) return 0; if (maxLiquidity == type(uint256).max) return type(uint256).max; uint256 depositLimit = 50_000 * 10**assetDecimals; uint256 assets = previewRedeem(balanceOf[owner]); return depositLimit > assets ? depositLimit - assets : 0; } /** * @notice Total number of shares that can be minted for owner from the cellar. * @dev Until after security audits, limits mints to $50k of shares per wallet. * @param owner address of account that would receive the shares * @return maximum amount of shares that can be minted */ function maxMint(address owner) public view returns (uint256) { if (isShutdown || isPaused) return 0; if (maxLiquidity == type(uint256).max) return type(uint256).max; uint256 mintLimit = previewDeposit(50_000 * 10**assetDecimals); uint256 shares = balanceOf[owner]; return mintLimit > shares ? mintLimit - shares : 0; } /** * @notice Total number of assets that can be withdrawn from the cellar. * @param owner address of account that would holds the shares * @return maximum amount of assets that can be withdrawn */ function maxWithdraw(address owner) public view returns (uint256) { UserDeposit[] storage deposits = userDeposits[owner]; // Track max assets that can be withdrawn. uint256 assets; // Saves gas by avoiding calling `_convertToAssets` on active shares during each loop. uint256 exchangeRate = _convertToAssets(1e18); for (uint256 i = currentDepositIndex[owner]; i < deposits.length; i++) { UserDeposit storage d = deposits[i]; // Determine the amount of assets that can be withdrawn. Only redeem active shares for // assets, otherwise just withdrawn the original amount of assets that were deposited. assets += d.timeDeposited <= lastTimeEnteredStrategy ? uint256(d.shares).mulWadDown(exchangeRate) : d.assets; } // Return the maximum amount of assets that can be withdrawn in the assets original units. return assets.changeDecimals(decimals, assetDecimals); } /** * @notice Total number of shares that can be redeemed from the cellar. * @param owner address of account that would holds the shares * @return maximum amount of shares that can be redeemed */ function maxRedeem(address owner) public view returns (uint256) { return balanceOf[owner]; } // ====================================== FEE OPERATIONS ====================================== /** * @notice Take platform fees and performance fees off of cellar's active assets. */ function accrueFees() external { // When the contract is shutdown, there should be no reason to accrue fees because there // will be no active assets to accrue fees on. if (isShutdown) revert ContractShutdown(); // Platform fees taken each accrual = activeAssets * (elapsedTime * (2% / SECS_PER_YEAR)). uint256 elapsedTime = block.timestamp - lastTimeAccruedPlatformFees; uint256 platformFeeInAssets = (_activeAssets() * elapsedTime * PLATFORM_FEE) / DENOMINATOR / 365 days; // The cellar accrues fees as shares instead of assets. uint256 platformFees = _convertToShares(platformFeeInAssets); _mint(address(this), platformFees); // Update the tracker for total platform fees accrued that are still waiting to be // transferred. accruedPlatformFees += platformFees; emit AccruedPlatformFees(platformFees); // Begin accrual of performance fees. _accruePerformanceFees(true); } /** * @notice Accrue performance fees. * @param updateFeeData whether or not to update fee data */ function _accruePerformanceFees(bool updateFeeData) internal { // Retrieve the current normalized income per unit of asset for the current strategy on Aave. uint256 normalizedIncome = lendingPool.getReserveNormalizedIncome(address(asset)); // If this is the first time the cellar is accruing performance fees, it will skip the part // were we take fees and should just update the fee data to set a baseline for assessing the // current strategy's performance. if (lastActiveAssets != 0) { // An index value greater than 1e27 indicates positive performance for the strategy's // lending position, while a value less than that indicates negative performance. uint256 performanceIndex = normalizedIncome.mulDivDown(1e27, lastNormalizedIncome); // This is the amount the cellar's active assets have grown to solely from performance // on Aave since the last time performance fees were accrued. It does not include // changes from deposits and withdraws. uint256 updatedActiveAssets = lastActiveAssets.mulDivUp(performanceIndex, 1e27); // Determines whether performance has been positive or negative. if (performanceIndex >= 1e27) { // Fees taken each accrual = (updatedActiveAssets - lastActiveAssets) * 5% uint256 gain = updatedActiveAssets - lastActiveAssets; uint256 performanceFeeInAssets = gain.mulDivDown(PERFORMANCE_FEE, DENOMINATOR); // The cellar accrues fees as shares instead of assets. uint256 performanceFees = _convertToShares(performanceFeeInAssets); _mint(address(this), performanceFees); accruedPerformanceFees += performanceFees; emit AccruedPerformanceFees(performanceFees); } else { // This would only happen if the current stablecoin strategy on Aave performed // negatively. This should rarely happen, if ever, for this particular cellar. But // in case it does, this mechanism will burn performance fees to help offset losses // in proportion to those minted for previous gains. uint256 loss = lastActiveAssets - updatedActiveAssets; uint256 insuranceInAssets = loss.mulDivDown(PERFORMANCE_FEE, DENOMINATOR); // Cannot burn more performance fees than the cellar has accrued. uint256 insurance = MathUtils.min( _convertToShares(insuranceInAssets), accruedPerformanceFees ); _burn(address(this), insurance); accruedPerformanceFees -= insurance; emit BurntPerformanceFees(insurance); } } // There may be cases were we don't want to update fee data in this function, for example // when we accrue performance fees before rebalancing into a new strategy since the data // will be outdated after the rebalance to a new strategy. if (updateFeeData) { lastActiveAssets = _activeAssets(); lastNormalizedIncome = normalizedIncome; } } /** * @notice Transfer accrued fees to Cosmos to distribute. */ function transferFees() external onlyOwner { // Total up all the fees this cellar has accrued and determine how much they can be redeemed // for in assets. uint256 fees = accruedPerformanceFees + accruedPlatformFees; uint256 feeInAssets = previewRedeem(fees); // Redeem our fee shares for assets to transfer to Cosmos. _burn(address(this), fees); // Only withdraw assets from strategy if the holding pool does not contain enough funds. // Otherwise, all assets will come from the holding pool. _allocateAssets(feeInAssets); // Transfer assets to a fee distributor on Cosmos. asset.approve(address(gravityBridge), feeInAssets); gravityBridge.sendToCosmos(address(asset), feesDistributor, feeInAssets); emit TransferFees(accruedPlatformFees, accruedPerformanceFees); // Reset the tracker for fees accrued that are still waiting to be transferred. accruedPlatformFees = 0; accruedPerformanceFees = 0; } // ===================================== ADMIN OPERATIONS ===================================== /** * @notice Enters into the current Aave stablecoin strategy. */ function enterStrategy() external onlyOwner { // When the contract is shutdown, it shouldn't be allowed to enter back into a strategy with // the assets it just withdrew from Aave. if (isShutdown) revert ContractShutdown(); // Deposits all inactive assets in the holding pool into the current strategy. _depositToAave(address(asset), inactiveAssets()); // The cellar will use this when determining which of a user's shares are active vs inactive. lastTimeEnteredStrategy = block.timestamp; } /** * @notice Rebalances current assets into a new asset strategy. * @param route array of [initial token, pool, token, pool, token, ...] that specifies the swap route * @param swapParams multidimensional array of [i, j, swap type] where i and j are the correct values for the n'th pool in `_route` and swap type should be 1 for a stableswap `exchange`, 2 for stableswap `exchange_underlying`, 3 for a cryptoswap `exchange`, 4 for a cryptoswap `exchange_underlying` and 5 for Polygon factory metapools `exchange_underlying` * @param minAmountOut minimum amount received after the final swap */ function rebalance( address[9] memory route, uint256[3][4] memory swapParams, uint256 minAmountOut ) external onlyOwner { // If the contract is shutdown, cellar shouldn't be able to rebalance assets it recently // pulled out back into a new strategy. if (isShutdown) revert ContractShutdown(); // Retrieve the last token in the route and store it as the new asset. address newAsset; for (uint256 i; ; i += 2) { if (i == 8 || route[i+1] == address(0)) { newAsset = route[i]; break; } } // Doesn't make sense to rebalance into the same asset. if (newAsset == address(asset)) revert SameAsset(newAsset); // Accrue any final performance fees from the current strategy before rebalancing. Otherwise // those fees would be lost when we proceed to update fee data for the new strategy. Also we // don't want to update the fee data here because we will do that later on after we've // rebalanced into a new strategy. _accruePerformanceFees(false); // Pull all active assets entered into Aave back into the cellar so we can swap everything // into the new asset. _withdrawFromAave(address(asset), type(uint256).max); uint256 holdingPoolAssets = inactiveAssets(); // Approve Curve to swap the cellar's assets. asset.safeApprove(address(curveRegistryExchange), holdingPoolAssets); // Perform stablecoin swap using Curve. uint256 amountOut = curveRegistryExchange.exchange_multiple( route, swapParams, holdingPoolAssets, minAmountOut ); // Store this later for the event we will emit. address oldAsset = address(asset); // Updates state for our new strategy and check to make sure Aave supports it before // rebalancing. _updateStrategy(newAsset); // Rebalance our assets into a new strategy. _depositToAave(newAsset, amountOut); // Update fee data for next fee accrual with new strategy. lastActiveAssets = _activeAssets(); lastNormalizedIncome = lendingPool.getReserveNormalizedIncome(address(asset)); emit Rebalance(oldAsset, newAsset, amountOut); } /** * @notice Reinvest rewards back into cellar's current strategy. * @dev Must be called within 2 day unstake period 10 days after `claimAndUnstake` was run. * @param minAmountOut minimum amount of assets cellar should receive after swap */ function reinvest(uint256 minAmountOut) public onlyOwner { // Redeems the cellar's stkAAVe rewards for AAVE. stkAAVE.redeem(address(this), type(uint256).max); uint256 amountIn = AAVE.balanceOf(address(this)); // Approve the Sushiswap to swap AAVE. AAVE.safeApprove(address(sushiswapRouter), amountIn); // Specify the swap path from AAVE -> WETH -> current asset. address[] memory path = new address[](3); path[0] = address(AAVE); path[1] = address(WETH); path[2] = address(asset); // Perform a multihop swap using Sushiswap. uint256[] memory amounts = sushiswapRouter.swapExactTokensForTokens( amountIn, minAmountOut, path, address(this), block.timestamp + 60 ); uint256 amountOut = amounts[amounts.length - 1]; // In the case of a shutdown, we just may want to redeem any leftover rewards for // shareholders to claim but without entering them back into a strategy. if (!isShutdown) { // Take performance fee off of rewards. uint256 performanceFeeInAssets = amountOut.mulDivDown(PERFORMANCE_FEE, DENOMINATOR); uint256 performanceFees = convertToShares(performanceFeeInAssets); // Mint performance fees to cellar as shares. _mint(address(this), performanceFees); accruedPerformanceFees += performanceFees; // Reinvest rewards back into the current strategy. _depositToAave(address(asset), amountOut); } } /** * @notice Claim rewards from Aave and begin cooldown period to unstake them. * @return claimed amount of rewards claimed from Aave */ function claimAndUnstake() public onlyOwner returns (uint256 claimed) { // Necessary to do as `claimRewards` accepts a dynamic array as first param. address[] memory aToken = new address[](1); aToken[0] = address(assetAToken); // Claim all stkAAVE rewards. claimed = incentivesController.claimRewards(aToken, type(uint256).max, address(this)); // Begin the cooldown period for unstaking stkAAVE to later redeem for AAVE. stkAAVE.cooldown(); } /** * @notice Sweep tokens sent here that are not managed by the cellar. * @dev This may be used in case the wrong tokens are accidentally sent to this contract. * @param token address of token to transfer out of this cellar */ function sweep(address token) external onlyOwner { // Prevent sweeping of assets managed by the cellar and shares minted to the cellar as fees. if (token == address(asset) || token == address(assetAToken) || token == address(this)) revert ProtectedAsset(token); // Transfer out tokens in this cellar that shouldn't be here. uint256 amount = ERC20(token).balanceOf(address(this)); ERC20(token).safeTransfer(msg.sender, amount); emit Sweep(token, amount); } /** * @notice Removes initial liquidity restriction. */ function removeLiquidityRestriction() external onlyOwner { maxLiquidity = type(uint256).max; emit LiquidityRestrictionRemoved(); } /** * @notice Pause the contract to prevent deposits. * @param _isPaused whether the contract should be paused or unpaused */ function setPause(bool _isPaused) external onlyOwner { if (isShutdown) revert ContractShutdown(); isPaused = _isPaused; emit Pause(_isPaused); } /** * @notice Stops the contract - this is irreversible. Should only be used in an emergency, * for example an irreversible accounting bug or an exploit. */ function shutdown() external onlyOwner { if (isShutdown) revert AlreadyShutdown(); isShutdown = true; // Ensure contract is not paused. isPaused = false; // Withdraw everything from Aave. The check is necessary to prevent a revert happening if we // try to withdraw from Aave without any assets entered into a strategy which would prevent // the contract from being able to be shutdown in this case. if (activeAssets() > 0) _withdrawFromAave(address(asset), type(uint256).max); emit Shutdown(); } // ========================================== HELPERS ========================================== /** * @notice Update state variables related to the current strategy. * @param newAsset address of the new asset being managed by the cellar */ function _updateStrategy(address newAsset) internal { // Retrieve the aToken that will represent the cellar's new strategy on Aave. (, , , , , , , address aTokenAddress, , , , ) = lendingPool.getReserveData(newAsset); // If the address is not null, it is supported by Aave. if (aTokenAddress == address(0)) revert TokenIsNotSupportedByAave(newAsset); // Update state related to the current strategy. asset = ERC20(newAsset); assetDecimals = ERC20(newAsset).decimals(); assetAToken = ERC20(aTokenAddress); // Update the decimals max liquidity is denoted in if restrictions are still in place. if (maxLiquidity != type(uint256).max) maxLiquidity = 5_000_000 * 10**assetDecimals; } /** * @notice Ensures there is enough assets in the contract available for a transfer. * @dev Only withdraws from strategy if needed. * @param assets The amount of assets to allocate */ function _allocateAssets(uint256 assets) internal { uint256 holdingPoolAssets = inactiveAssets(); if (assets > holdingPoolAssets) { _withdrawFromAave(address(asset), assets - holdingPoolAssets); } } /** * @notice Deposits cellar holdings into an Aave lending pool. * @param token the address of the token * @param amount the amount of tokens to deposit */ function _depositToAave(address token, uint256 amount) internal { ERC20(token).safeApprove(address(lendingPool), amount); // Deposit tokens to Aave protocol. lendingPool.deposit(token, amount, address(this), 0); emit DepositToAave(token, amount); } /** * @notice Withdraws assets from Aave. * @param token the address of the token * @param amount the amount of tokens to withdraw * @return withdrawnAmount the withdrawn amount from Aave */ function _withdrawFromAave(address token, uint256 amount) internal returns (uint256) { // Withdraw tokens from Aave protocol uint256 withdrawnAmount = lendingPool.withdraw(token, amount, address(this)); emit WithdrawFromAave(token, withdrawnAmount); return withdrawnAmount; } // ================================= SHARE TRANSFER OPERATIONS ================================= /** * @dev Modified versions of Solmate's ERC20 transfer and transferFrom functions to work with the * cellar's active vs inactive shares mechanic. */ /** * @notice Transfers shares from one account to another. * @dev If the sender specifies to only transfer active shares and does not have enough active * shares to transfer to meet the amount specified, the default behavior is to not to * revert but transfer as many active shares as the sender has to the receiver. * @param from address that is sending shares * @param to address that is receiving shares * @param amount amount of shares to transfer * @param onlyActive whether to only transfer active shares */ function transferFrom( address from, address to, uint256 amount, bool onlyActive ) public returns (bool) { // If the sender is not the owner of the shares, check to see if the owner has approved them // to spend their shares. if (from != msg.sender) { uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount; } // Retrieve the deposits from sender then begin looping through deposits, generally from // oldest to newest deposits. This may not be the case though if shares have been // transferred to the sender, as they will be added to the end of the sender's deposits // regardless of time deposited. UserDeposit[] storage depositsFrom = userDeposits[from]; // Tracks the amount of shares left to transfer; updated at the end of each loop. uint256 leftToTransfer = amount; for (uint256 i = currentDepositIndex[from]; i < depositsFrom.length; i++) { UserDeposit storage dFrom = depositsFrom[i]; // If we only want to transfer active shares, skips this deposit if it is inactive. bool isActive = dFrom.timeDeposited <= lastTimeEnteredStrategy; if (onlyActive && !isActive) continue; // Saves an extra SLOAD if active and cast type to uint256. uint256 dFromShares = dFrom.shares; // Determine the amount of assets and shares to transfer from this deposit. uint256 transferredShares = MathUtils.min(leftToTransfer, dFromShares); uint256 transferredAssets = uint256(dFrom.assets).mulDivUp(transferredShares, dFromShares); // For active shares, deletes the deposit data we don't need anymore for a gas refund. if (isActive) { delete dFrom.assets; delete dFrom.timeDeposited; } else { dFrom.assets -= uint112(transferredAssets); } // Taken shares from this deposit to transfer. dFrom.shares -= uint112(transferredShares); // Transfer a new deposit to the end of receiver's list of deposits. userDeposits[to].push(UserDeposit({ assets: isActive ? 0 : uint112(transferredAssets), shares: uint112(transferredShares), timeDeposited: isActive ? 0 : dFrom.timeDeposited })); // Update the counter of assets left to transfer. leftToTransfer -= transferredShares; if (i == depositsFrom.length - 1 || leftToTransfer == 0) { // Only store the index for the next non-zero deposit to save gas on looping if // inactive deposits weren't skipped. if (!onlyActive) currentDepositIndex[from] = dFrom.shares != 0 ? i : i+1; break; } } // Determine the total amount of shares transferred. amount -= leftToTransfer; // Will revert here if sender is trying to transfer more shares then they have, so no need // for an explicit check. balanceOf[from] -= amount; // Cannot overflow because the sum of all user balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(from, to, amount); return true; } /// @dev For compatibility with ERC20 standard. function transferFrom(address from, address to, uint256 amount) public override returns (bool) { // Defaults to only transferring active shares. return transferFrom(from, to, amount, true); } function transfer(address to, uint256 amount) public override returns (bool) { // Defaults to only transferring active shares. return transferFrom(msg.sender, to, amount, true); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC20.sol) /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol) /// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it. abstract contract ERC20 { /*/////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); /*/////////////////////////////////////////////////////////////// METADATA STORAGE //////////////////////////////////////////////////////////////*/ string public name; string public symbol; uint8 public immutable decimals; /*/////////////////////////////////////////////////////////////// ERC20 STORAGE //////////////////////////////////////////////////////////////*/ uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; /*/////////////////////////////////////////////////////////////// EIP-2612 STORAGE //////////////////////////////////////////////////////////////*/ bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); uint256 internal immutable INITIAL_CHAIN_ID; bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR; mapping(address => uint256) public nonces; /*/////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ constructor( string memory _name, string memory _symbol, uint8 _decimals ) { name = _name; symbol = _symbol; decimals = _decimals; INITIAL_CHAIN_ID = block.chainid; INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator(); } /*/////////////////////////////////////////////////////////////// ERC20 LOGIC //////////////////////////////////////////////////////////////*/ function approve(address spender, uint256 amount) public virtual returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function transfer(address to, uint256 amount) public virtual returns (bool) { balanceOf[msg.sender] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(msg.sender, to, amount); return true; } function transferFrom( address from, address to, uint256 amount ) public virtual returns (bool) { uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount; balanceOf[from] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(from, to, amount); return true; } /*/////////////////////////////////////////////////////////////// EIP-2612 LOGIC //////////////////////////////////////////////////////////////*/ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual { require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED"); // Unchecked because the only math done is incrementing // the owner's nonce which cannot realistically overflow. unchecked { 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); require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER"); allowance[recoveredAddress][spender] = value; } emit Approval(owner, spender, value); } function DOMAIN_SEPARATOR() public view virtual returns (bytes32) { return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator(); } function computeDomainSeparator() internal view virtual returns (bytes32) { return keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256("1"), block.chainid, address(this) ) ); } /*/////////////////////////////////////////////////////////////// INTERNAL MINT/BURN LOGIC //////////////////////////////////////////////////////////////*/ function _mint(address to, uint256 amount) internal virtual { totalSupply += amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(address(0), to, amount); } function _burn(address from, uint256 amount) internal virtual { balanceOf[from] -= amount; // Cannot underflow because a user's balance // will never be larger than the total supply. unchecked { totalSupply -= amount; } emit Transfer(from, address(0), amount); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; import {ERC20} from "../tokens/ERC20.sol"; /// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/SafeTransferLib.sol) /// @author Modified from Gnosis (https://github.com/gnosis/gp-v2-contracts/blob/main/src/contracts/libraries/GPv2SafeERC20.sol) /// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer. library SafeTransferLib { /*/////////////////////////////////////////////////////////////// ETH OPERATIONS //////////////////////////////////////////////////////////////*/ function safeTransferETH(address to, uint256 amount) internal { bool callStatus; assembly { // Transfer the ETH and store if it succeeded or not. callStatus := call(gas(), to, amount, 0, 0, 0, 0) } require(callStatus, "ETH_TRANSFER_FAILED"); } /*/////////////////////////////////////////////////////////////// ERC20 OPERATIONS //////////////////////////////////////////////////////////////*/ function safeTransferFrom( ERC20 token, address from, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000) // Begin with the function selector. mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "from" argument. mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 68), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 100 because the calldata length is 4 + 32 * 3. callStatus := call(gas(), token, 0, freeMemoryPointer, 100, 0, 0) } require(didLastOptionalReturnCallSucceed(callStatus), "TRANSFER_FROM_FAILED"); } function safeTransfer( ERC20 token, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000) // Begin with the function selector. mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 68 because the calldata length is 4 + 32 * 2. callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0) } require(didLastOptionalReturnCallSucceed(callStatus), "TRANSFER_FAILED"); } function safeApprove( ERC20 token, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000) // Begin with the function selector. mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 68 because the calldata length is 4 + 32 * 2. callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0) } require(didLastOptionalReturnCallSucceed(callStatus), "APPROVE_FAILED"); } /*/////////////////////////////////////////////////////////////// INTERNAL HELPER LOGIC //////////////////////////////////////////////////////////////*/ function didLastOptionalReturnCallSucceed(bool callStatus) private pure returns (bool success) { assembly { // Get how many bytes the call returned. let returnDataSize := returndatasize() // If the call reverted: if iszero(callStatus) { // Copy the revert message into memory. returndatacopy(0, 0, returnDataSize) // Revert with the same message. revert(0, returnDataSize) } switch returnDataSize case 32 { // Copy the return data into memory. returndatacopy(0, 0, returnDataSize) // Set success to whether it returned true. success := iszero(iszero(mload(0))) } case 0 { // There was no return data. success := 1 } default { // It returned some malformed input. success := 0 } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _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); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; /// @title interface for AaveV2StablecoinCellar interface IAaveV2StablecoinCellar { // ======================================= EVENTS ======================================= /** * @notice Emitted when assets are deposited into cellar. * @param caller the address of the caller * @param token the address of token the cellar receives * @param owner the address of the owner of shares * @param assets the amount of assets being deposited * @param shares the amount of shares minted to owner */ event Deposit( address indexed caller, address indexed owner, address indexed token, uint256 assets, uint256 shares ); /** * @notice Emitted when assets are withdrawn from cellar. * @param receiver the address of the receiver of the withdrawn assets * @param owner the address of the owner of the shares * @param token the address of the token withdrawn * @param assets the amount of assets being withdrawn * @param shares the amount of shares burned from owner */ event Withdraw( address indexed receiver, address indexed owner, address indexed token, uint256 assets, uint256 shares ); /** * @notice Emitted on deposit to Aave. * @param token the address of the token * @param amount the amount of tokens to deposit */ event DepositToAave( address indexed token, uint256 amount ); /** * @notice Emitted on withdraw from Aave. * @param token the address of the token * @param amount the amount of tokens to withdraw */ event WithdrawFromAave( address indexed token, uint256 amount ); /** * @notice Emitted on rebalance of Aave strategy. * @param oldAsset the address of the asset for the old strategy * @param newAsset the address of the asset for the new strategy * @param assets the amount of the new assets that has been deposited to Aave after rebalance */ event Rebalance( address indexed oldAsset, address indexed newAsset, uint256 assets ); /** * @notice Emitted when platform fees accrued. * @param fees amount of fees accrued in shares */ event AccruedPlatformFees(uint256 fees); /** * @notice Emitted when performance fees accrued. * @param fees amount of fees accrued in shares */ event AccruedPerformanceFees(uint256 fees); /** * @notice Emitted when performance fees burnt as insurance. * @param fees amount of fees burnt in shares */ event BurntPerformanceFees(uint256 fees); /** * @notice Emitted when platform fees are transferred to Cosmos. * @param platformFees amount of platform fees transferred * @param performanceFees amount of performance fees transferred */ event TransferFees(uint256 platformFees, uint256 performanceFees); /** * @notice Emitted when liquidity restriction removed. */ event LiquidityRestrictionRemoved(); /** * @notice Emitted when tokens accidentally sent to cellar are recovered. * @param token the address of the token * @param amount amount transferred out */ event Sweep(address indexed token, uint256 amount); /** * @notice Emitted when cellar is paused. * @param isPaused whether the contract is paused */ event Pause(bool isPaused); /** * @notice Emitted when cellar is shutdown. */ event Shutdown(); // ======================================= ERRORS ======================================= /** * @notice Attempted an action with zero assets. */ error ZeroAssets(); /** * @notice Attempted an action with zero shares. */ error ZeroShares(); /** * @notice Attempted deposit more liquidity over the liquidity limit. * @param maxLiquidity the max liquidity */ error LiquidityRestricted(uint256 maxLiquidity); /** * @notice Attempted deposit more than the per wallet limit. * @param maxDeposit the max deposit */ error DepositRestricted(uint256 maxDeposit); /** * @notice Current asset is updated to an asset not supported by Aave. * @param unsupportedToken address of the unsupported token */ error TokenIsNotSupportedByAave(address unsupportedToken); /** * @notice Attempted to sweep an asset that is managed by the cellar. * @param token address of the token that can't be sweeped */ error ProtectedAsset(address token); /** * @notice Attempted rebalance into the same asset. * @param asset address of the asset */ error SameAsset(address asset); /** * @notice Attempted action was prevented due to contract being shutdown. */ error ContractShutdown(); /** * @notice Attempted action was prevented due to contract being paused. */ error ContractPaused(); /** * @notice Attempted to shutdown the contract when it was already shutdown. */ error AlreadyShutdown(); // ======================================= STRUCTS ======================================= /** * @notice Stores user deposit data. * @param assets amount of assets deposited * @param shares amount of shares that were minted for their deposit * @param timeDeposited timestamp of when the user deposited */ struct UserDeposit { uint112 assets; uint112 shares; uint32 timeDeposited; } // ================================= DEPOSIT/WITHDRAWAL OPERATIONS ================================= function deposit(uint256 assets, address receiver) external returns (uint256); function mint(uint256 shares, address receiver) external returns (uint256); function withdraw( uint256 assets, address receiver, address owner ) external returns (uint256 shares); function redeem( uint256 shares, address receiver, address owner ) external returns (uint256 assets); // ==================================== ACCOUNTING OPERATIONS ==================================== function activeAssets() external view returns (uint256); function inactiveAssets() external view returns (uint256); function totalAssets() external view returns (uint256); function convertToShares(uint256 assets) external view returns (uint256); function convertToAssets(uint256 shares) external view returns (uint256); function previewDeposit(uint256 assets) external view returns (uint256); function previewMint(uint256 shares) external view returns (uint256); function previewWithdraw(uint256 assets) external view returns (uint256); function previewRedeem(uint256 shares) external view returns (uint256); // ======================================= STATE INFORMATION ===================================== function depositBalances(address user) external view returns ( uint256 userActiveShares, uint256 userInactiveShares, uint256 userActiveAssets, uint256 userInactiveAssets ); function numDeposits(address user) external view returns (uint256); // ============================ DEPOSIT/WITHDRAWAL LIMIT OPERATIONS ============================ function maxDeposit(address owner) external view returns (uint256); function maxMint(address owner) external view returns (uint256); function maxWithdraw(address owner) external view returns (uint256); function maxRedeem(address owner) external view returns (uint256); // ======================================= FEE OPERATIONS ======================================= function accrueFees() external; function transferFees() external; // ======================================= ADMIN OPERATIONS ======================================= function enterStrategy() external; function rebalance( address[9] memory route, uint256[3][4] memory swapParams, uint256 minAmountOut ) external; function reinvest(uint256 minAmountOut) external; function claimAndUnstake() external returns (uint256 claimed); function sweep(address token) external; function removeLiquidityRestriction() external; function setPause(bool _isPaused) external; function shutdown() external; // ================================== SHARE TRANSFER OPERATIONS ================================== function transferFrom( address from, address to, uint256 amount, bool onlyActive ) external returns (bool); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; interface IAaveIncentivesController { event RewardsAccrued(address indexed user, uint256 amount); event RewardsClaimed( address indexed user, address indexed to, address indexed claimer, uint256 amount ); event ClaimerSet(address indexed user, address indexed claimer); /* * @dev Returns the configuration of the distribution for a certain asset * @param asset The address of the reference asset of the distribution * @return The asset index, the emission per second and the last updated timestamp **/ function getAssetData(address asset) external view returns ( uint256, uint256, uint256 ); /* * LEGACY ************************** * @dev Returns the configuration of the distribution for a certain asset * @param asset The address of the reference asset of the distribution * @return The asset index, the emission per second and the last updated timestamp **/ function assets(address asset) external view returns ( uint128, uint128, uint256 ); /** * @dev Whitelists an address to claim the rewards on behalf of another address * @param user The address of the user * @param claimer The address of the claimer */ function setClaimer(address user, address claimer) external; /** * @dev Returns the whitelisted claimer for a certain address (0x0 if not set) * @param user The address of the user * @return The claimer address */ function getClaimer(address user) external view returns (address); /** * @dev Configure assets for a certain rewards emission * @param assets The assets to incentivize * @param emissionsPerSecond The emission for each asset */ function configureAssets(address[] calldata assets, uint256[] calldata emissionsPerSecond) external; /** * @dev Called by the corresponding asset on any update that affects the rewards distribution * @param asset The address of the user * @param userBalance The balance of the user of the asset in the lending pool * @param totalSupply The total supply of the asset in the lending pool **/ function handleAction( address asset, uint256 userBalance, uint256 totalSupply ) external; /** * @dev Returns the total of rewards of an user, already accrued + not yet accrued * @param user The address of the user * @return The rewards **/ function getRewardsBalance(address[] calldata assets, address user) external view returns (uint256); /** * @dev Claims reward for an user, on all the assets of the lending pool, accumulating the pending rewards * @param amount Amount of rewards to claim * @param to Address that will be receiving the rewards * @return Rewards claimed **/ function claimRewards( address[] calldata assets, uint256 amount, address to ) external returns (uint256); /** * @dev Claims reward for an user on behalf, on all the assets of the lending pool, accumulating the pending rewards. The caller must * be whitelisted via "allowClaimOnBehalf" function by the RewardsAdmin role manager * @param amount Amount of rewards to claim * @param user Address to check and claim rewards * @param to Address that will be receiving the rewards * @return Rewards claimed **/ function claimRewardsOnBehalf( address[] calldata assets, uint256 amount, address user, address to ) external returns (uint256); /** * @dev returns the unclaimed rewards of the user * @param user the address of the user * @return the unclaimed user rewards */ function getUserUnclaimedRewards(address user) external view returns (uint256); /** * @dev returns the unclaimed rewards of the user * @param user the address of the user * @param asset The asset to incentivize * @return the user index for the asset */ function getUserAssetData(address user, address asset) external view returns (uint256); /** * @dev for backward compatibility with previous implementation of the Incentives controller */ function REWARD_TOKEN() external view returns (address); /** * @dev for backward compatibility with previous implementation of the Incentives controller */ function PRECISION() external view returns (uint8); /** * @dev Gets the distribution end timestamp of the emissions */ function DISTRIBUTION_END() external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.11; interface IStakedTokenV2 { function stake(address to, uint256 amount) external; function redeem(address to, uint256 amount) external; function cooldown() external; function claimRewards(address to, uint256 amount) external; function balanceOf(address account) external view returns (uint256); function stakersCooldowns(address account) external view returns (uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; interface ICurveSwaps { function exchange_multiple( address[9] memory _route, uint256[3][4] memory _swap_params, uint256 _amount, uint256 _expected ) external returns (uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; /** * @notice Partial interface for a SushiSwap Router contract **/ interface ISushiSwapRouter { function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; interface IGravity { function sendToCosmos(address _tokenContract, bytes32 _destination, uint256 _amount) external; } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; /** * @dev Partial interface for a Aave LendingPool contract, * which is the main point of interaction with an Aave protocol's market **/ interface ILendingPool { /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external returns (uint256); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve **/ function getReserveData(address asset) external view returns ( //stores the reserve configuration //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 configuration, //the liquidity index. Expressed in ray uint128 liquidityIndex, //variable borrow index. Expressed in ray uint128 variableBorrowIndex, //the current supply rate. Expressed in ray uint128 currentLiquidityRate, //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate, //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate, uint40 lastUpdateTimestamp, //tokens addresses address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress, //address of the interest rate strategy address interestRateStrategyAddress, //the id of the reserve. Represents the position in the list of the active reserves uint8 id ); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; library MathUtils { /** * @notice Used to change the decimals of precision used for an amount. */ function changeDecimals( uint256 amount, uint8 fromDecimals, uint8 toDecimals ) internal pure returns (uint256) { if (fromDecimals == toDecimals) { return amount; } else if (fromDecimals < toDecimals) { return amount * 10**(toDecimals - fromDecimals); } else { return ceilDiv(amount, 10**(fromDecimals - toDecimals)); } } // ===================================== OPENZEPPELIN'S MATH ===================================== function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } // ================================= SOLMATE's FIXEDPOINTMATHLIB ================================= uint256 public constant WAD = 1e18; // The scalar of ETH and most ERC20s. function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) { return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down. } function mulDivDown( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 z) { assembly { // Store x * y in z for now. z := mul(x, y) // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y)) if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) { revert(0, 0) } // Divide z by the denominator. z := div(z, denominator) } } function mulDivUp( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 z) { assembly { // Store x * y in z for now. z := mul(x, y) // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y)) if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) { revert(0, 0) } // First, divide z - 1 by the denominator and add 1. // We allow z - 1 to underflow if z is 0, because we multiply the // end result by 0 if z is zero, ensuring we return 0 if z is zero. z := mul(iszero(iszero(z)), add(div(sub(z, 1), denominator), 1)) } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } }
Stops the contract - this is irreversible. Should only be used in an emergency, for example an irreversible accounting bug or an exploit./ Ensure contract is not paused. Withdraw everything from Aave. The check is necessary to prevent a revert happening if we try to withdraw from Aave without any assets entered into a strategy which would prevent the contract from being able to be shutdown in this case.
function shutdown() external onlyOwner { if (isShutdown) revert AlreadyShutdown(); isShutdown = true; isPaused = false; if (activeAssets() > 0) _withdrawFromAave(address(asset), type(uint256).max); emit Shutdown(); }
265,758
pragma solidity ^ 0.4.24; /*** * __ __ ___ ___ ___ * \ \ / / / _ \ | _ \ / _ \ * \ V / | (_) | | _/ | (_) | * _|_|_ \___/ _|_|_ \___/ * _| """ |_|"""""|_| """ |_|"""""| * "`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-' * * https://a21.app */ interface IGameBuilder{ function buildGame (address _manager, string _name, string _title, uint256 _price, uint256 _timespan, uint8 _profitOfManager, uint8 _profitOfFirstPlayer, uint8 _profitOfWinner) payable external returns(address); } contract IGame { address public owner; address public creator; address public manager; uint256 public poolValue = 0; uint256 public round = 0; uint256 public totalBets = 0; uint256 public startTime = now; bytes32 public name; string public title; uint256 public price; uint256 public timespan; uint32 public gameType; /* profit divisions */ uint256 public profitOfSociety = 5; uint256 public profitOfManager = 1; uint256 public profitOfFirstPlayer = 15; uint256 public profitOfWinner = 40; function getGame() view public returns( address, uint256, address, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256); } /*** * ___ ___ _ * / \ |_ ) / | * | - | / / | | * |_|_| /___| _|_|_ * _|"""""|_|"""""|_|"""""| * "`-0-0-'"`-0-0-'"`-0-0-' */ contract Owned { modifier isActivated { require(activated == true, "its not ready yet."); _; } modifier isHuman { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } modifier limits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } modifier onlyOwner { require (msg.sender == owner, "OnlyOwner methods called by non-owner."); _; } address public owner; bool public activated = true; constructor() public{ owner = msg.sender; } function terminate() public onlyOwner { selfdestruct(owner); } function setIsActivated(bool _activated) public onlyOwner { activated = _activated; } } /** * @title NameFilter * @dev filter string */ library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } contract GameFactory is Owned { uint256 private constant MINIMUM_PRICE = 0.01 ether; uint256 private constant MAXIMUM_PRICE = 100 ether; uint256 private constant MINIMUM_TIMESPAN = 1 minutes; uint256 private constant MAXIMUM_TIMESPAN = 24 hours; using NameFilter for string; mapping(bytes32 => address) public games; mapping(uint256 => address) public builders; bytes32[] public names; address[] public addresses; address[] public approved; address[] public offlines; uint256 public fee = 0.2 ether; uint8 public numberOfEarlybirds = 10; uint256 public numberOfGames = 0; event onNewGame (address sender, bytes32 gameName, address gameAddress, uint256 fee, uint256 timestamp); function newGame (address _manager, string _name, string _title, uint256 _price, uint256 _timespan, uint8 _profitOfManager, uint8 _profitOfFirstPlayer, uint8 _profitOfWinner, uint256 _gameType) limits(msg.value) isActivated payable public { require(address(_manager)!=0x0, "invaild address"); require(_price >= MINIMUM_PRICE && _price <= MAXIMUM_PRICE, "price not in range (MINIMUM_PRICE, MAXIMUM_PRICE)"); require(_timespan >= MINIMUM_TIMESPAN && _timespan <= MAXIMUM_TIMESPAN, "timespan not in range(MINIMUM_TIMESPAN, MAXIMUM_TIMESPAN)"); bytes32 name = _name.nameFilter(); require(name[0] != 0, "invaild name"); require(checkName(name), "duplicate name"); require(_profitOfManager <=20, "[profitOfManager] don't take too much commission :)"); require(_profitOfFirstPlayer <=50, "[profitOfFirstPlayer] don't take too much commission :)"); require(_profitOfWinner <=100 && (_profitOfManager + _profitOfWinner + _profitOfFirstPlayer) <=100, "[profitOfWinner] don't take too much commission :)"); require(msg.value >= getTicketPrice(_profitOfManager), "fee is not enough"); address builderAddress = builders[_gameType]; require(address(builderAddress)!=0x0, "invaild game type"); IGameBuilder builder = IGameBuilder(builderAddress); address game = builder.buildGame(_manager, _name, _title, _price, _timespan, _profitOfManager, _profitOfFirstPlayer, _profitOfWinner); games[name] = game; names.push(name); addresses.push(game); numberOfGames ++; owner.transfer(msg.value); if(numberOfGames > numberOfEarlybirds){ // plus 10% fee everytime // might overflow? I wish as well, however, at that time no one can afford the fee. fee += (fee/10); } emit onNewGame(msg.sender, name, game, fee, now); } function checkName(bytes32 _name) view public returns(bool){ return address(games[_name]) == 0x0; } function addGame(address _addr) public payable onlyOwner { IGame game = IGame(_addr); require(checkName(game.name()), "duplicate name"); games[game.name()] = _addr; names.push(game.name()); addresses.push(_addr); approved.push(_addr); numberOfGames ++; } function addBuilder(uint256 _gameType, address _builderAddress) public payable onlyOwner { builders[_gameType] = _builderAddress; } function approveGame(address _addr) public payable onlyOwner { approved.push(_addr); } function offlineGame(address _addr) public payable onlyOwner { offlines.push(_addr); } function setFee(uint256 _fee) public payable onlyOwner { fee = _fee; } function getTicketPrice(uint8 _profitOfManager) view public returns(uint256){ // might overflow? I wish as well, however, at that time no one can afford the fee. return fee * _profitOfManager; } function getNames() view public returns(bytes32[]){ return names; } function getAddresses() view public returns(address[]){ return addresses; } function getGame(bytes32 _name) view public returns( address, uint256, address, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256) { require(!checkName(_name), "name not found!"); address gameAddress = games[_name]; IGame game = IGame(gameAddress); return game.getGame(); } function withdraw() public onlyOwner { owner.transfer(address(this).balance); } }
might overflow? I wish as well, however, at that time no one can afford the fee.
function getTicketPrice(uint8 _profitOfManager) view public returns(uint256){ return fee * _profitOfManager; }
5,449,830
./full_match/5/0x966471ABb6Afe5CC543f2714C443d9f072369078/sources/src/token/ERC1155/base/ERC1155BaseInternal.sol
wrap given element in array of length 1 element element to wrap return singleton array/
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; }
1,890,164
pragma solidity ^0.5.17; import "./ReentrancyGuard.sol"; import "../Escapable.sol"; import "../../../registry/AdminRole.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract TokenBank is ReentrancyGuard, AdminRole, Escapable { using EnumerableSet for EnumerableSet.AddressSet; // // CONSTANTS: // address internal constant VAULT = address(0xdead); address internal constant TOTAL = address(0xbabe); // // STORAGE: // // Address of the ERC20 token contract that stores tokens in the TokenBank: address internal token; // EnumerableSet of all accounts that have a balance in the TokenBank: EnumerableSet.AddressSet internal accounts; // Mapping of account => token balance in the TokenBank: mapping(address => uint256) internal tokenBalances; // Address to receive vault drain, set on construction: address internal drainVaultReceiver; // // EVENTS: // /// @dev Emit when a deposit is submitted to the TokenBank: event Deposit(address indexed depositor, uint256 depositAmount); /// @dev Emit when the TokenBank moves an amount of tokens to the Vault: event StoredInVault(address indexed account, uint256 amount); /// @dev Emit when an amount of tokens has been collected: event StoreUnclaimedInVault(uint256 amountToCollect); /// @dev Emit when an amount of tokens has been withdrawn to an account: event Withdraw(address indexed account, uint256 amount); /// @dev Emit when an amount of tokens has been drained from the Vault: event DrainVault(address indexed destination, uint256 amount); /// @dev Only allow addresses from the account holders set: modifier onlyAccountHolders(address addr) { require( EnumerableSet.contains(accounts, addr), "Address is not an account holder" ); _; } // // CONSTRUCTOR: // /// @notice Construct a TokenBank. /// @param _token The ERC20 token that the TokenBank can receive /// @param _admins A list of addresses that will be given the Admin role /// @param _drainVaultReceiver The address to receive Vault drains /// @param _escapeHatchCaller The address allowed to call the EscapeHatch /// @param _escapeHatchDestination The address to receive all tokens from calling the EscapeHatch constructor( address _token, address[] memory _admins, address _drainVaultReceiver, address _escapeHatchCaller, address payable _escapeHatchDestination ) public AdminRole(_admins) Escapable(_escapeHatchCaller, _escapeHatchDestination) { require(_token != address(0), "Deposit token cannot be zero adress"); require( _drainVaultReceiver != address(0), "Vault cannot be drained to zero address" ); token = _token; drainVaultReceiver = _drainVaultReceiver; } // // EXTERNAL FUNCTIONS: // /// @notice Deposit `amount` tokens on `wallet` account. function deposit(address wallet, uint256 amount) external onlyAdmin nonReentrant { require(wallet != address(0), "Cannot deposit from zero address"); require( wallet != VAULT && wallet != TOTAL, "Cannot deposit from reserved address" ); // Take a deposit of tokens from the depositor and transfer it to TokenBank: require( IERC20(token).transferFrom(wallet, address(this), amount), "Token transfer failed" ); // Add deposited amount to the depositor token balance: _addToBalance(wallet, amount); // Ensure depositor is in the account set: if (!EnumerableSet.contains(accounts, wallet)) { EnumerableSet.add(accounts, wallet); } emit Deposit(wallet, amount); } /// @notice Withdraw `amount` from `wallet` account and send it back to it's address. function withdraw(address wallet, uint256 amount) external onlyAdmin nonReentrant { require( tokenBalances[wallet] >= amount, "Address has insufficieant token balance to withdraw" ); // Remove the amount of tokens the account token balance: _subFromBalance(wallet, amount); // Transfer the token amount fro TokenBank to address: require( IERC20(token).transfer(wallet, amount), "Token transfer failed" ); emit Withdraw(wallet, amount); } /// @notice Move `amount` tokens from `wallet` account to the VAULT account. function storeInVault(address wallet, uint256 amount) external onlyAdmin nonReentrant returns (uint256 amountStored) { if (amount < tokenBalances[wallet]) { amountStored = amount; } else { amountStored = tokenBalances[wallet]; } // Move the tokens from the token account to the Vault: _internalTransfer(wallet, VAULT, amountStored); emit StoredInVault(wallet, amountStored); return amountStored; } /// @notice Move all tokens to the VAULT account. function storeAllInVault() external onlyAdmin nonReentrant { address[] memory accs = _getAccounts(); for (uint256 i = 0; i < accs.length; ++i) { address acc = accs[i]; uint256 bal = tokenBalances[acc]; _internalTransfer(acc, VAULT, bal); emit StoredInVault(acc, bal); } } /// @notice Move tokens sent manually (to this smart contract) to the VAULT account. function storeUnclaimedInVault() external onlyAdmin nonReentrant { uint256 amount = _unclaimedTokenBalance(); require(amount > 0, "No unclaimed token balance to store in Vault"); // Add all unclaimed tokens to the Vault: _addToBalance(VAULT, amount); emit StoreUnclaimedInVault(amount); } /// @notice Remove all tokens attributed to VAULT account and transfer them to drainVaultReceiver address. function drainVault() external onlyAdmin nonReentrant { uint256 vaultBalance = tokenBalances[VAULT]; // Remove all the tokens from Vault: _subFromBalance(VAULT, vaultBalance); // Transfer all the tokens from the TokenBank to the evac address: require( IERC20(token).transfer(drainVaultReceiver, vaultBalance), "Transfer failed" ); emit DrainVault(drainVaultReceiver, vaultBalance); } // // VIEW FUNCTIONS: // function getDepositToken() external view returns (address) { return token; } function getTokenBalance(address wallet) external view returns (uint256) { return tokenBalances[wallet]; } function isAccount(address wallet) external view returns (bool) { return accounts.contains(wallet); } function numAccounts() external view returns (uint256) { return accounts.length(); } function getAccounts() external view returns (address[] memory accountsList) { return _getAccounts(); } /// @dev getAccounts() implementation function _getAccounts() internal view returns (address[] memory accountsList) { return EnumerableSet.enumerate(accounts); } function getAccountsAndTokenBalances() external view returns (address[] memory, uint256[] memory) { uint256 len = accounts.length(); address[] memory accs = _getAccounts(); uint256[] memory balances = new uint256[](len); for (uint256 i = 0; i < len; ++i) { balances[i] = tokenBalances[accs[i]]; } return (accs, balances); } /// @return the token balance not claimed by Vault or any account in the TokenBank function unclaimedTokenBalance() external view returns (uint256) { return _unclaimedTokenBalance(); } /// @dev unclaimedTokenBalance() implementation function _unclaimedTokenBalance() internal view returns (uint256) { return SafeMath.sub( IERC20(token).balanceOf(address(this)), tokenBalances[TOTAL] ); } // // INTERNAL FUNCTIONS: // function _addToBalance(address _account, uint256 amount) internal { tokenBalances[_account] = SafeMath.add(tokenBalances[_account], amount); tokenBalances[TOTAL] = SafeMath.add(tokenBalances[TOTAL], amount); } function _subFromBalance(address _account, uint256 amount) internal { tokenBalances[_account] = SafeMath.sub(tokenBalances[_account], amount); tokenBalances[TOTAL] = SafeMath.sub(tokenBalances[TOTAL], amount); } function _internalTransfer( address from, address to, uint256 amount ) internal { _subFromBalance(from, amount); _addToBalance(to, amount); } }
Move all tokens to the VAULT account.
function storeAllInVault() external onlyAdmin nonReentrant { address[] memory accs = _getAccounts(); for (uint256 i = 0; i < accs.length; ++i) { address acc = accs[i]; uint256 bal = tokenBalances[acc]; _internalTransfer(acc, VAULT, bal); emit StoredInVault(acc, bal); } }
6,461,281
./full_match/11155111/0x030a616cBC1F4A759AAfc955Be24d935d0A67a0C/sources/contracts/GameFactory.sol
require(block.timestamp > lotteries[_id].endTime, "Lottery is not over");require(openLotteries.length > 0, "There are no lotteries to close");
function closeGame(uint256 _id) external onlyOwner { require(games[_id].status == Status.Open, "Lottery is not open"); uint32 callbackGasLimit; uint256 requestId; games[_id].status = Status.Closed; callbackGasLimit = games[_id].callbackGasLimit; requestId = requestRandomWords(); s_requests[requestId] = RequestStatus({ randomWords: new uint256[](0), exists: true, fulfilled: false }); games[_id].lastRequestId = requestId; removeGameArray(_id, openGames); drawGames.push(_id); emit GameStatusUpdated(_id, Status.Closed); }
3,814,898
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /** * @title iOVM_L2ToL1MessagePasser */ interface iOVM_L2ToL1MessagePasser { /********** * Events * **********/ event L2ToL1Message(uint256 _nonce, address _sender, bytes _data); /******************** * Public Functions * ********************/ function passMessageToL1(bytes calldata _message) external; }
iOVM_L2ToL1MessagePasser/
interface iOVM_L2ToL1MessagePasser { event L2ToL1Message(uint256 _nonce, address _sender, bytes _data); function passMessageToL1(bytes calldata _message) external; pragma solidity ^0.8.9; }
14,104,288
./full_match/80001/0x58c87A63fe29E3bA8b704DB0017cC00B7BFc749a/sources/_openzeppelin/contracts/token/ERC20/ERC20.sol
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"); return true; }
861,851
./full_match/1/0x666D080bD673679b927B7006bDbDF50925f27D9F/sources/contracts/MIRLStaking.sol
Deposit LP tokens to MirlStaking for MIRL allocation. pid The index of the pool. See `poolInfo`. amount LP token amount to deposit. Effects Interactions lpToken[pid].safeTransferFrom(msg.sender, amount);
function deposit(uint256 pid, uint256 amount) public { require(pid < poolInfo.length, 'pool id is not existed'); PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][msg.sender]; user.amount = user.amount.add(amount); user.rewardDebt = user.rewardDebt.add(int256(amount.mul(pool.accumulatedMirlPerShare) / ACC_SUSHI_PRECISION)); lpToken[pid].transferFrom(msg.sender, address(this), amount); poolInfo[pid].totalSupply = pool.totalSupply.add(amount); emit Deposit(msg.sender, pid, amount); }
9,625,481
//SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "./HugoNFTAbstractImpl.sol"; /** * @author SabaunT https://github.com/SabaunT. * @dev Management for attributes, traits and CIDs - all are named as meta-data. */ abstract contract HugoNFTMetadataManager is HugoNFTAbstractImpl { event AddNewAttribute(uint256 indexed newAttributeId, string attributeName, string newScript); event AddNewTrait(uint256 indexed attributeId, uint256 indexed traitId, string name); event UpdateAttributeCID(uint256 indexed attributeId, string ipfsCID); event TraitNameChanged(uint256 indexed attributeId, uint256 indexed traitId, string newName); /** * @dev Changes name of the trait in the particular attribute * * Emits {HugoNFTMetadataManager-TraitNameChanged} event * * Requirements: * - `attributeId` should have an id of existent attribute * - `traitId` should be > 0 and of valid range of ids of `attributeId`'s traits * - `newName` shouldn't be empty */ function changeTraitName(uint256 attributeId, uint256 traitId, string calldata newName) external override(AbstractHugoNFT) onlyRole(NFT_ADMIN_ROLE) { require(attributeId < currentAttributesAmount, "HugoNFT::invalid attribute id"); require(traitId != 0, "HugoNFT::invalid zero trait id"); require(bytes(newName).length > 0, "HugoNFT::new name shouldn't be an empty string"); Trait[] storage traitsOfAttr = _traitsOfAttribute[attributeId]; require(traitsOfAttr.length >= traitId, "HugoNFT::such trait does not exist"); Trait storage trait = traitsOfAttr[traitId - 1]; trait.name = newName; emit TraitNameChanged(attributeId, traitId, newName); } /** * @dev Adds a new attribute to NFT. * * Also should be provided attribute's traits, CID of the folder where the traits * of the attribute are stored and a new generation script, which can generate NFTs * with the added attribute. * * Emits: * 1. {HugoNFTMetadataManager-AddNewAttribute}, * 2. {HugoNFTMetadataManager-AddNewTrait}, * 3. {HugoNFTMetadataManager-UpdateAttributeCID}. * * Requirements: * - `attributeName` shouldn't be an empty string * - `newGenerationScript` shouldn't be an empty string * - `msg.sender` should have {HugoNFTStorage-NFT_ADMIN} role * All the other requirements are defined in functions called inside the current one. */ function addNewAttributeWithTraits( string calldata attributeName, uint256 amountOfTraits, string[] calldata names, string calldata cid, string calldata newGenerationScript ) external override(AbstractHugoNFT) onlyRole(NFT_ADMIN_ROLE) { require(bytes(attributeName).length > 0, "HugoNFT::attribute name is empty"); require( bytes(newGenerationScript).length > 0, "HugoNFT::empty nft generation script provided" ); uint256 newAttributeId = currentAttributesAmount; currentAttributesAmount += 1; _attributes[newAttributeId] = Attribute(newAttributeId, attributeName); addTraits(newAttributeId, amountOfTraits, names, cid); nftGenerationScripts.push(newGenerationScript); emit AddNewAttribute(newAttributeId, attributeName, newGenerationScript); } /** * @dev Updates multiple attribute's CIDs. * * If for some attribute it wasn't intended to update the CID, then * an empty string should be sent as an array member. * * Emits: * 1. {HugoNFTMetadataManager-UpdateAttributeCID}. * * Requirements: * - `CIDs` length should be equal to current (actual) amount of attributes * - `msg.sender` should have {HugoNFTStorage-NFT_ADMIN} role * All the other requirements are defined in functions called inside the current one. */ function updateMultipleAttributesCIDs(string[] calldata CIDs) external override(AbstractHugoNFT) onlyRole(NFT_ADMIN_ROLE) { require( CIDs.length == currentAttributesAmount, "HugoNFT::invalid CIDs array length" ); for (uint256 i = 0; i < CIDs.length; i++) { // empty CID string - don't update attributes CID data if (bytes(CIDs[i]).length == 0) continue; updateAttributeCID(i, CIDs[i]); } } /** * @dev The same as {HugoNFTMetadataManager-addTraitWithoutCID}, but updates CID. * * Trait ids in the attribute's traits data start from id = 1. * * Emits: * 1. {HugoNFTMetadataManager-AddNewTrait}, * 2. {HugoNFTMetadataManager-UpdateAttributeCID}. * * Requirements: * - `msg.sender` should have {HugoNFTStorage-NFT_ADMIN} role * All the other requirements are defined in functions called inside the current one. */ function addTrait( uint256 attributeId, uint256 traitId, string calldata name, string calldata cid ) external override(AbstractHugoNFT) onlyRole(NFT_ADMIN_ROLE) { addTraitWithoutCID(attributeId, traitId, name); updateAttributeCID(attributeId, cid); } /** * @dev Adds new traits to the attribute. * * We don't define trait ids. Instead we define only the number of traits we want * to add. Traits are added in a sequential order of their ids. So knowing * 1) the amount of traits currently stored for the attribute and 2) amount of traits * which is willed to add is enough to compute trait ids for new traits. * * Emits: * 1. {HugoNFTMetadataManager-AddNewTrait}, * 2. {HugoNFTMetadataManager-UpdateAttributeCID}. * * Requirements: * - `amountOfTraits` shouldn't be more then {HugoNFTStorage-MAX_ADDING_TRAITS} * - `amountOfTraits` should be equal to lengths of `names` and `rarities` arrays. * - `msg.sender` should have {HugoNFTStorage-NFT_ADMIN} role * All the other requirements are defined in functions called inside the current one. */ function addTraits( uint256 attributeId, uint256 amountOfTraits, string[] memory names, string memory cid ) public override(AbstractHugoNFT) onlyRole(NFT_ADMIN_ROLE) { require( amountOfTraits <= MAX_ADDING_TRAITS, "HugoNFT::adding traits number exceeds prohibited amount" ); require( amountOfTraits == names.length, "HugoNFT::num of traits isn't equal to traits names array length" ); uint256 startFromId = _traitsOfAttribute[attributeId].length; for (uint256 i = 0; i < amountOfTraits; i++) { addTraitWithoutCID(attributeId, startFromId + i + 1, names[i]); } updateAttributeCID(attributeId, cid); } /** * @dev Updates attribute's CID. * * Emits: * 1. {HugoNFTMetadataManager-UpdateAttributeCID}. * * Requirements: * - `attributeId` should have an id of existent attribute * - `ipfsCID` should have length of {HugoNFTStorage-IPFS_CID_BYTES_LENGTH}. * - `msg.sender` should have {HugoNFTStorage-NFT_ADMIN} role */ function updateAttributeCID(uint256 attributeId, string memory ipfsCID) public override(AbstractHugoNFT) onlyRole(NFT_ADMIN_ROLE) { require(attributeId < currentAttributesAmount, "HugoNFT::invalid attribute id"); require( bytes(ipfsCID).length == IPFS_CID_BYTES_LENGTH, "HugoNFT::invalid ipfs CID length" ); _CIDsOfAttribute[attributeId].push(ipfsCID); emit UpdateAttributeCID(attributeId, ipfsCID); } /** * @dev Adds provided trait to the attribute. * * Trait ids in the attribute's traits data start from id = 1. * * Emits: * 1. {HugoNFTMetadataManager-AddNewTrait}. * * Requirements: * - `attributeId` should have an id of existent attribute * - `traitId` should form a sequential order with already stored trait ids. * - `name` string shouldn't be empty. * - `msg.sender` should have {HugoNFTStorage-NFT_ADMIN} role */ function addTraitWithoutCID( uint256 attributeId, uint256 traitId, string memory name ) private onlyRole(NFT_ADMIN_ROLE) { require(attributeId < currentAttributesAmount, "HugoNFT::invalid attribute id"); // This kind of check has 2 pros: // 1. could check whether the id is valid by comparing it with array length // 2. trait id also tells about its position in Traits[] // But there is a con: we should add traits sequentially Trait[] storage tA = _traitsOfAttribute[attributeId]; require( tA.length + 1 == traitId, "HugoNFT::traits should be added sequentially by trait ids" ); require(bytes(name).length > 0, "HugoNFT::empty trait name"); Trait memory newTrait = Trait(attributeId, traitId, name); tA.push(newTrait); emit AddNewTrait(attributeId, traitId, name); } }
Updates attribute's CID. Emits: 1. {HugoNFTMetadataManager-UpdateAttributeCID}. Requirements: - `attributeId` should have an id of existent attribute - `ipfsCID` should have length of {HugoNFTStorage-IPFS_CID_BYTES_LENGTH}. - `msg.sender` should have {HugoNFTStorage-NFT_ADMIN} role/
function updateAttributeCID(uint256 attributeId, string memory ipfsCID) public override(AbstractHugoNFT) onlyRole(NFT_ADMIN_ROLE) { require(attributeId < currentAttributesAmount, "HugoNFT::invalid attribute id"); require( bytes(ipfsCID).length == IPFS_CID_BYTES_LENGTH, "HugoNFT::invalid ipfs CID length" ); _CIDsOfAttribute[attributeId].push(ipfsCID); emit UpdateAttributeCID(attributeId, ipfsCID); }
12,610,228
// SPDX-License-Identifier: MIT 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/proxy/utils/Initializable.sol@v4.3.2 /** * @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@v4.3.2 /** * @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/utils/StringsUpgradeable.sol@v4.3.2 /** * @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@v4.3.2 /** * @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@v4.3.2 /** * @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@v4.3.2 /** * @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/security/PausableUpgradeable.sol@v4.3.2 /** * @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/token/ERC20/IERC20Upgradeable.sol@v4.3.2 /** * @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/utils/AddressUpgradeable.sol@v4.3.2 /** * @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/token/ERC20/utils/SafeERC20Upgradeable.sol@v4.3.2 /** * @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 SafeERC20Upgradeable { using AddressUpgradeable for address; function safeTransfer( IERC20Upgradeable token, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20Upgradeable 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( IERC20Upgradeable token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, value) ); } function safeIncreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } function safeDecreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require( oldAllowance >= value, "SafeERC20: decreased allowance below zero" ); uint256 newAllowance = oldAllowance - value; _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(IERC20Upgradeable 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 require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } } } // File contracts/vault/IYieldAggregator.sol // Code and docs are CC-BY-NC-ND-3.0 interface IYieldAggregator { function deposit(uint256 _amount) external; } // File contracts/vault/Vault.sol // Code and docs are CC-BY-NC-ND-3.0 /** * @title Vault * @dev Contract in charge of holding usdc tokens and depositing them to Yield Aggregator * */ contract Vault is Initializable, AccessControlUpgradeable, PausableUpgradeable { bytes32 public constant BACKEND_ADMIN_ROLE = keccak256("BACKEND_ADMIN_ROLE"); using SafeERC20Upgradeable for IERC20Upgradeable; IERC20Upgradeable private usdcToken; /** * @notice Emitted when USDC tokens are moved to Yield Aggregator contract * @param amount_usdc is the amount of tokens being moved */ event FundsMovedToAggregator(uint256 amount_usdc); /** * @notice Emitted when USDC tokens are moved to Yield Aggregator contract * @param _depositant: account that is transferring usdc tokens to addres(this) * @param _amount: amount of usdc tokens to be transferred */ event DepositToVault(address _depositant, uint256 _amount); /** * @dev address of the Chainlink Defender */ address private backendAddress; /** * @dev address of the contract responsible for yielding */ address private yieldSourceAddress; /// @custom:oz-upgrades-unsafe-allow constructor constructor() initializer {} /** * @notice initialize init the contract with the following parameters * @dev this function is called only once during the contract initialization * @param _usdcTokenAddress USDC token contract address * @param _backendAddress address of the Chainlink Defender */ function initialize(address _usdcTokenAddress, address _backendAddress) external initializer { require( _usdcTokenAddress != address(0), "Vault: USDC token address cannot be address 0!" ); usdcToken = IERC20Upgradeable(_usdcTokenAddress); backendAddress = _backendAddress; AccessControlUpgradeable.__AccessControl_init(); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(BACKEND_ADMIN_ROLE, _backendAddress); __Pausable_init(); } /** * @notice Transfers "_amount" of USDC tokens to Vault Smart Contract * @param _amount is the amount of USDC tokens to be transferred by a caller */ function deposit(uint256 _amount) public whenNotPaused { // user approves Vault to transfer usdc tokens require( usdcToken.balanceOf(_msgSender()) >= _amount, "Vault: Not enough balance." ); // transfer usdc from user to vault usdcToken.safeTransferFrom(_msgSender(), address(this), _amount); emit DepositToVault(_msgSender(), _amount); } /** * @notice Transfers "amount_usdc" of tokens to Yield Aggregator contract * @param amount_usdc: Amount of USDC tokens to be transferred to Yield Aggregator */ function moveFundsToAggregator(uint256 amount_usdc) external onlyRole(BACKEND_ADMIN_ROLE) whenNotPaused { require( usdcToken.balanceOf(address(this)) >= amount_usdc, "Vault: Contract does not have enough balance." ); // approve to Yield Aggregator usdcToken.approve(yieldSourceAddress, amount_usdc); // call deposit from Yield Aggregator Contract IYieldAggregator(yieldSourceAddress).deposit(amount_usdc); emit FundsMovedToAggregator(amount_usdc); } /** * @notice used to change the address of the Chainnlink Defnder * @param _backendAddress new address of the Chainlink Defender */ function setBackendAddress(address _backendAddress) external onlyRole(DEFAULT_ADMIN_ROLE) { require( _backendAddress != address(0), "Vault: Backend contract address cannot be address 0!" ); revokeRole(BACKEND_ADMIN_ROLE, backendAddress); backendAddress = _backendAddress; grantRole(BACKEND_ADMIN_ROLE, backendAddress); } /** * @notice used to change the address of the contract responsible with yielding * @param _yieldSourceAddress new address of the contract responsible with yielding */ function setYieldSourceAddress(address _yieldSourceAddress) external onlyRole(BACKEND_ADMIN_ROLE) { require( _yieldSourceAddress != address(0), "Vault: Yield Source contract address cannot be address 0!" ); yieldSourceAddress = _yieldSourceAddress; } function pause() public onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); } function unpause() public onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } function version() public pure virtual returns (string memory) { return "1.0.0"; } } // File contracts/yield/IEthAnchorConversionPool.sol // Code and docs are CC-BY-NC-ND-3.0 interface IConversionPool { /** * @notice Deposit of USDC to Eth Anchor using USDC token * @param _amount amount of USDC to transfer to Eth Anchor */ function deposit(uint256 _amount) external; /** * @notice Retrieve USDC from Eth Anchor * @param _amount amount of aUSDC to retrieve from Eth Anchor */ function redeem(uint256 _amount) external; } // File contracts/vault/VaultV2.sol // Code and docs are CC-BY-NC-ND-3.0 /** * @title Vault * @dev Contract in charge of holding usdc tokens and depositing them to Yield Aggregator * */ contract Vault2 is Vault { /** * @dev address of the USDC token */ IERC20Upgradeable internal usdcToken; /** * @dev address of the USDC token */ IERC20Upgradeable internal aUsdcToken; /** * @dev address of the Chainlink Defender */ address internal backendAddress; IConversionPool conversionPool; /** * @notice initialize init the contract with the following parameters * @dev this function is called only once during the contract initialization * @param _usdcTokenAddress USDC token contract address * @param _backendAddress address of the Chainlink Defender */ function setUpVault( address _usdcTokenAddress, address _aUsdcTokenAddress, address _backendAddress, address _conversionPoolAddress ) external onlyRole(DEFAULT_ADMIN_ROLE) { require( _usdcTokenAddress != address(0), "Vault: USDC token address cannot be address 0!" ); usdcToken = IERC20Upgradeable(_usdcTokenAddress); aUsdcToken = IERC20Upgradeable(_aUsdcTokenAddress); conversionPool = IConversionPool(_conversionPoolAddress); backendAddress = _backendAddress; _setupRole(BACKEND_ADMIN_ROLE, _backendAddress); } function depositUsdcThroughConversionPool(uint256 amount_usdc) external onlyRole(BACKEND_ADMIN_ROLE) whenNotPaused { require( usdcToken.balanceOf(address(this)) >= amount_usdc, "Vault: Contract does not have enough balance of USDC." ); // approve to Conversion Pool usdcToken.approve(address(conversionPool), amount_usdc); // deposit to Conversion Pool conversionPool.deposit(amount_usdc); } function redeemAUsdcFromConversionPool(uint256 amount_ausdc) external onlyRole(BACKEND_ADMIN_ROLE) whenNotPaused { require( aUsdcToken.balanceOf(address(this)) >= amount_ausdc, "Vault: Contract does not have enough balance of aUSDC." ); // approve to Conversion Pool aUsdcToken.approve(address(conversionPool), amount_ausdc); // redeem from Conversion Pool conversionPool.redeem(amount_ausdc); } /** * @notice used to deposit USDC to a destination address using funds from smart contract * @param _account accout receiving the transference of USDC * @param _amount amount of USDC to be sent to _account */ function transfer(address _account, uint256 _amount) external onlyRole(BACKEND_ADMIN_ROLE) { require( _account != address(0), "Vault: Receiveing address cannot be 0." ); require( usdcToken.balanceOf(address(this)) >= _amount, "Vault: There is not enough funds to transfer" ); usdcToken.transfer(_account, _amount); } function version() public pure virtual override returns (string memory) { return "3.0.0"; } }
approve to Conversion Pool redeem from Conversion Pool
function redeemAUsdcFromConversionPool(uint256 amount_ausdc) external onlyRole(BACKEND_ADMIN_ROLE) whenNotPaused { require( aUsdcToken.balanceOf(address(this)) >= amount_ausdc, "Vault: Contract does not have enough balance of aUSDC." ); aUsdcToken.approve(address(conversionPool), amount_ausdc); conversionPool.redeem(amount_ausdc); }
14,868,743
/** *Submitted for verification at Etherscan.io on 2021-07-11 */ // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, 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/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 IERC721Receiver { /** * @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/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 IERC721Metadata is IERC721 { /** * @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/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; // 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: @openzeppelin/contracts/utils/Context.sol pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "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] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/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 ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/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 ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings 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. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).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}. 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 = ERC721.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 { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_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 = ERC721.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 = ERC721.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(ERC721.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(ERC721.ownerOf(tokenId), to, tokenId); } /** * @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 IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly 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` cannot be the zero address. * - `to` cannot be the zero address. * * 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 { } } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol pragma solidity ^0.8.0; /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @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 override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // File: @openzeppelin/contracts/security/Pausable.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 Pausable is Context { /** * @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. */ constructor () { _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()); } } // File: @openzeppelin/contracts/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 Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), 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 { 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 virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol pragma solidity ^0.8.0; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721Burnable is Context, ERC721 { /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } } // File: @openzeppelin/contracts/utils/math/SafeMath.sol pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: src/contracts/BitSig.sol pragma solidity ^0.8.0; // SPDX-License-Identifier: MIT /** * * , __ * /|/ \o () o * | __/ _|_ /\ __, * | \| | / \| / | * |(__/|_/|_//(__/|_/\_/|/ * /| * \| * **/ contract BitSig is ERC721Burnable, ERC721URIStorage, Pausable, Ownable { using SafeMath for uint256; uint256 public tokensMinted; mapping(uint256 => address) public tokenCreator; // Who created the token. mapping(uint256 => string) public tokenCreatorMessage; // Optional message that token creator can add to be on chain. mapping(uint256 => uint256) public tokenCreatorRoyalty; // Royalty given for token creator (0-100). mapping(uint256 => uint256) public signersRoyalty; // Royalty given to signers pool (0-100). mapping(uint256 => uint256) public VIPSignersRoyalty; // Royalty given to VIP Signers pool (0-100). mapping(uint256 => uint256) public maxNumberSigners; // Max number of signers for the token. mapping(uint256 => address[]) public VIPSigners; // VIP signers have their own reserved royalty pool. mapping(uint256 => uint256[]) public VIPSignerPercentages; // What percentage of the VIPSignersRoyalty each VIP signer gets. // This points to the latest known head of the signers ipfs linked list. // Not necessaily the latest, but the latest that the blockchain knows of. mapping(uint256 => string) public signersLink; // Link to something that shows proof of signers having been paid. // This is most likely a transaction hash but can be something else mapping(uint256 => string) public paidSignersProof; // Community links exist as a standalone decentrilized system to maintain the head // of the signers linked list. // Community members can sign and submit their versions of the signatures list. // The token owner can then accept one of those links as being the valid one. // Without this, if the centrilized system of keeping track of signatures goes down then // there will be no place for signers to add their off-chain signatures. mapping(uint256 => string[]) public signersCommunityLinks; // Have the signers be on-chain instead of off-chain on ipfs. // For use when there are less signers and higher security is needed. // A lot more expensive to store signers in contract. // onlyOwnerAddsOnChainSigs regulates if only the token owner can add on chain signers, or anybody can. mapping(uint256 => address[]) public onChainTokenSigners; mapping(uint256 => mapping(address => string)) public onChainTokenSignerMessage; mapping(uint256 => mapping(address => string)) public onChainTokenSignerSignatureHash; mapping(uint256 => bool) public onlyOwnerAddsOnChainSigs; // If false, anyone can sign the token on-chain. // External NFTs can be wrapped by BitSig NFTs. // The owner of the BitSig NFT must also own the external NFT to wrap it. // With this, a BitSig NFT can act as a signing layer over any existing NFT. mapping(uint256 => address) public wrappedNFTAddress; // Contract address of wrapped NFT mapping(uint256 => uint256) public wrappedNFTId; // Token ID of wrapped NFT mapping(bytes32 => uint256) public wrappedNFTs; // Hash of address and tokenID to BitSig tokenID // Events event SignersLinkSet (uint256 date, string indexed link, address indexed sender, uint256 indexed tokenId); event PaidSignersProofSet (uint256 date, string indexed proof, address indexed sender, uint256 indexed tokenId); event VIPSignersSet (uint256 date, address indexed sender, uint256 indexed tokenId); event SignersCommunityLinkAdd (uint256 date, string indexed link, address indexed sender, uint256 indexed tokenId); event AcceptedSignersCommunityLink (uint256 date, string indexed link, address indexed sender, uint256 indexed tokenId); event DeletedAllSignersCommunityLinks (uint256 date, address indexed sender, uint256 indexed tokenId); event OnlyOwnerAddsOnChainSigsSet (uint256 date, address indexed sender, uint256 indexed tokenId); event OnChainSignaturesAdded (uint256 date, address indexed sender, uint256 indexed tokenId); event ExternalNFTWrapped (uint256 date, uint256 indexed tokenId, address indexed externalTokenAddress, uint256 indexed externalTokenId); constructor() ERC721("BitSig", "BITSIG") {} function pause() public onlyOwner { _pause(); } function unpause() public onlyOwner { _unpause(); } function safeMint(uint256 _tokenId, uint256 _tokenCreatorRoyalty, uint256 _signersRoyalty, uint256 _VIPSignersRoyalty, uint256 _maxNumberSigners, bool _onlyOwnerAddsOnChainSigs, string memory tokenURI_, string memory _tokenCreatorMessage) public whenNotPaused { require(_tokenCreatorRoyalty >= 0 && _signersRoyalty >= 0 && _VIPSignersRoyalty >= 0, "Royalty must not be less than 0"); require(_signersRoyalty.add(_VIPSignersRoyalty).add(_tokenCreatorRoyalty) <= 100, "Royalties add up to over 100"); require(_maxNumberSigners >= 0, "Max number of signers must not be negative."); require(!_exists(_tokenId), "Token ID already exists."); tokensMinted+=1; tokenCreator[_tokenId] = msg.sender; tokenCreatorRoyalty[_tokenId] = _tokenCreatorRoyalty; signersRoyalty[_tokenId] = _signersRoyalty; VIPSignersRoyalty[_tokenId] = _VIPSignersRoyalty; maxNumberSigners[_tokenId] = _maxNumberSigners; onlyOwnerAddsOnChainSigs[_tokenId] = _onlyOwnerAddsOnChainSigs; tokenCreatorMessage[_tokenId] = _tokenCreatorMessage; _safeMint(msg.sender, _tokenId); _setTokenURI(_tokenId, tokenURI_); } // Minting can be done by another contract which can set the tokenCreator . function safeMint(uint256 _tokenId, address _tokenOwner, uint256 _tokenCreatorRoyalty, uint256 _signersRoyalty, uint256 _VIPSignersRoyalty, uint256 _maxNumberSigners, bool _onlyOwnerAddsOnChainSigs, string memory tokenURI_, string memory _tokenCreatorMessage) public whenNotPaused { require(_tokenCreatorRoyalty >= 0 && _signersRoyalty >= 0 && _VIPSignersRoyalty >= 0, "Royalty must not be less than 0"); require(_signersRoyalty.add(_VIPSignersRoyalty).add(_tokenCreatorRoyalty) <= 100, "Royalties add up to over 100"); require(_maxNumberSigners >= 0, "Max number of signers must not be negative."); require(!_exists(_tokenId), "Token ID already exists."); tokensMinted+=1; tokenCreatorRoyalty[_tokenId] = _tokenCreatorRoyalty; signersRoyalty[_tokenId] = _signersRoyalty; VIPSignersRoyalty[_tokenId] = _VIPSignersRoyalty; maxNumberSigners[_tokenId] = _maxNumberSigners; onlyOwnerAddsOnChainSigs[_tokenId] = _onlyOwnerAddsOnChainSigs; tokenCreatorMessage[_tokenId] = _tokenCreatorMessage; _safeMint(msg.sender, _tokenId); _setTokenURI(_tokenId, tokenURI_); tokenCreator[_tokenId] = _tokenOwner; safeTransferFrom(msg.sender, _tokenOwner, _tokenId); } function _beforeTokenTransfer(address from, address to, uint256 _tokenId) internal whenNotPaused override { super._beforeTokenTransfer(from, to, _tokenId); } function _burn(uint256 _tokenId) internal override(ERC721, ERC721URIStorage) { require(msg.sender == ownerOf(_tokenId)); super._burn(_tokenId); } function tokenURI(uint256 _tokenId) public view override(ERC721, ERC721URIStorage) returns (string memory) { return super.tokenURI(_tokenId); } // Holds the last known link to the "head" with the latest signers. The signing pages form a sort of linked list // where the latest one has the link of the previous. To ensure that the linked list of signer versions is the // right one, set the latest one here. Then the blockchain history can be used to verify that the linked list is // the correct one. function setLatestSignersLink(string memory _link, uint256 _tokenId) public whenNotPaused { require(_isApprovedOrOwner(msg.sender, _tokenId), "Only owner or approved address can modify."); signersLink[_tokenId] = _link; emit SignersLinkSet(block.timestamp, _link, msg.sender, _tokenId); } // Once the token is transfered, it won't hold value in the eyes of the community unless its new owner // submits the proof of the signers having been paid. function setPaidSignersProof(string memory _proof, uint256 _tokenId) public whenNotPaused { require(_isApprovedOrOwner(msg.sender, _tokenId), "Only owner or approved address can modify."); paidSignersProof[_tokenId] = _proof; emit PaidSignersProofSet(block.timestamp, _proof, msg.sender, _tokenId); } function setVIPSigners(address[] memory signers, uint256[] memory percentages, uint256 _tokenId) public whenNotPaused { require(_isApprovedOrOwner(msg.sender, _tokenId), "Only owner or approved address can modify."); require(signers.length == percentages.length, "Signers length doesn't match percentages length."); uint256 total = 0; // verify that percentages add up to 100 for (uint i = 0; i < percentages.length; i++) { require(percentages[i] >= 0, "Percentage is under 0"); total = total.add(percentages[i]); } require(total == 100, "Percentages don't add up to 100"); VIPSigners[_tokenId] = signers; VIPSignerPercentages[_tokenId] = percentages; emit VIPSignersSet(block.timestamp, msg.sender, _tokenId); } function addToSignersCommunityLink(string memory _link, uint256 _tokenId) public whenNotPaused { signersCommunityLinks[_tokenId].push(_link); emit SignersCommunityLinkAdd(block.timestamp, _link, msg.sender, _tokenId); } // Accepts one of the signers community links and deletes the rest. function acceptASignersCommunityLink(uint256 index, uint256 _tokenId) public whenNotPaused { require(_isApprovedOrOwner(msg.sender, _tokenId), "Only owner or approved address can modify."); require(index < signersCommunityLinks[_tokenId].length, "Index not valid"); signersLink[_tokenId] = signersCommunityLinks[_tokenId][index]; delete signersCommunityLinks[_tokenId]; emit AcceptedSignersCommunityLink(block.timestamp, signersLink[_tokenId], msg.sender, _tokenId); } function deleteAllSignersCommunityLinks(uint256 _tokenId) public whenNotPaused { require(_isApprovedOrOwner(msg.sender, _tokenId), "Only owner or approved address can modify."); delete signersCommunityLinks[_tokenId]; emit DeletedAllSignersCommunityLinks(block.timestamp, msg.sender, _tokenId); } // Sets if only the owner can add to the on chain signatures. function setOnlyOwnerAddsOnChainSigs(bool approvalNeeded, uint256 _tokenId) public whenNotPaused { require(_isApprovedOrOwner(msg.sender, _tokenId), "Only owner or approved address can modify."); onlyOwnerAddsOnChainSigs[_tokenId] = approvalNeeded; emit OnlyOwnerAddsOnChainSigsSet(block.timestamp, msg.sender, _tokenId); } function addOnChainSignatures(address[] memory signers, string[] memory messages, string[] memory signatureHashes, uint256 _tokenId) public whenNotPaused { if (onlyOwnerAddsOnChainSigs[_tokenId]) { require(_isApprovedOrOwner(msg.sender, _tokenId), "Only owner or approved address can add on chain signatures."); } require(onChainTokenSigners[_tokenId].length + signers.length <= maxNumberSigners[_tokenId], "Max number of signers exceeded."); require(signers.length == messages.length && signers.length == signatureHashes.length, "Length of arrays must be equal."); for (uint i=0; i < signers.length; i++) { bytes memory emptyStringTest = bytes(onChainTokenSignerSignatureHash[_tokenId][signers[i]]); if (emptyStringTest.length == 0) { onChainTokenSigners[_tokenId].push(signers[i]); onChainTokenSignerMessage[_tokenId][signers[i]] = messages[i]; onChainTokenSignerSignatureHash[_tokenId][signers[i]] = signatureHashes[i]; emit OnChainSignaturesAdded(block.timestamp, msg.sender, _tokenId); } } } // Wraps an external NFT. // Require that this NFT isn't in array of external NFTs already connected. // Require that the msg.sender is the owner of of the external token. function wrapExternalNFT(uint256 _tokenId, address _externalNftContractAddress, uint256 _externalTokenId ) public whenNotPaused { require(msg.sender == ownerOf(_tokenId), "Only owner can connect."); bytes32 tokenHash = keccak256(abi.encodePacked(_externalNftContractAddress, _externalTokenId)); require(wrappedNFTs[tokenHash] == 0, "External NFT is already connected to some BitSig token."); ERC721 token_contract = ERC721(_externalNftContractAddress); require(token_contract.ownerOf(_externalTokenId) == ownerOf(_tokenId), "Owner of external NFT must also own this NFT."); require(wrappedNFTAddress[_tokenId] == address(0) && wrappedNFTId[_tokenId] == 0, "Token must not already be connected."); wrappedNFTs[tokenHash] = _tokenId; wrappedNFTAddress[_tokenId] = _externalNftContractAddress; wrappedNFTId[_tokenId] = _externalTokenId; emit ExternalNFTWrapped(block.timestamp, _tokenId, _externalNftContractAddress, _externalTokenId); } function getOnChainSigners(uint256 _tokenId) public view returns (address[] memory) { return onChainTokenSigners[_tokenId]; } function getVIPSigners(uint256 _tokenId) public view returns (address[] memory) { return VIPSigners[_tokenId]; } function getVIPSignerPercentages(uint256 _tokenId) public view returns (uint256[] memory) { return VIPSignerPercentages[_tokenId]; } function getSignersCommunityLinks(uint256 _tokenId) public view returns (string[] memory) { return signersCommunityLinks[_tokenId]; } }
Holds the last known link to the "head" with the latest signers. The signing pages form a sort of linked list where the latest one has the link of the previous. To ensure that the linked list of signer versions is the right one, set the latest one here. Then the blockchain history can be used to verify that the linked list is the correct one.
function setLatestSignersLink(string memory _link, uint256 _tokenId) public whenNotPaused { require(_isApprovedOrOwner(msg.sender, _tokenId), "Only owner or approved address can modify."); signersLink[_tokenId] = _link; emit SignersLinkSet(block.timestamp, _link, msg.sender, _tokenId); }
2,172,462
// File: @openzeppelin/contracts/math/SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.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. */ 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; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/spec_interfaces/ISubscriptions.sol pragma solidity 0.6.12; /// @title Subscriptions contract interface interface ISubscriptions { event SubscriptionChanged(uint256 indexed vcId, address owner, string name, uint256 genRefTime, string tier, uint256 rate, uint256 expiresAt, bool isCertified, string deploymentSubset); event Payment(uint256 indexed vcId, address by, uint256 amount, string tier, uint256 rate); event VcConfigRecordChanged(uint256 indexed vcId, string key, string value); event VcCreated(uint256 indexed vcId); event VcOwnerChanged(uint256 indexed vcId, address previousOwner, address newOwner); /* * External functions */ /// Creates a new virtual chain /// @dev Called only by: an authorized subscription plan contract /// @dev the initial amount paid for the virtual chain must be large than minimumInitialVcPayment /// @param name is the virtual chain name /// @param tier is the virtual chain tier /// @param rate is the virtual chain tier rate as determined by the subscription plan /// @param amount is the amount paid for the virtual chain initial subscription /// @param owner is the virtual chain owner. The owner may change virtual chain properties or ser config records /// @param isCertified indicates the virtual is run by the certified committee /// @param deploymentSubset indicates the code deployment subset the virtual chain uses such as main or canary /// @return vcId is the virtual chain ID allocated to the new virtual chain /// @return genRefTime is the virtual chain genesis reference time that determines the first block committee function createVC(string calldata name, string calldata tier, uint256 rate, uint256 amount, address owner, bool isCertified, string calldata deploymentSubset) external returns (uint vcId, uint genRefTime); /// Extends the subscription of an existing virtual chain. /// @dev Called only by: an authorized subscription plan contract /// @dev assumes that the msg.sender approved the amount prior to the call /// @param vcId is the virtual chain ID /// @param amount is the amount paid for the virtual chain subscription extension /// @param tier is the virtual chain tier, must match the tier selected in the virtual creation /// @param rate is the virtual chain tier rate as determined by the subscription plan /// @param payer is the address paying for the subscription extension function extendSubscription(uint256 vcId, uint256 amount, string calldata tier, uint256 rate, address payer) external; /// Sets a virtual chain config record /// @dev may be called only by the virtual chain owner /// @param vcId is the virtual chain ID /// @param key is the name of the config record to update /// @param value is the config record value function setVcConfigRecord(uint256 vcId, string calldata key, string calldata value) external /* onlyVcOwner */; /// Returns the value of a virtual chain config record /// @param vcId is the virtual chain ID /// @param key is the name of the config record to query /// @return value is the config record value function getVcConfigRecord(uint256 vcId, string calldata key) external view returns (string memory); /// Transfers a virtual chain ownership to a new owner /// @dev may be called only by the current virtual chain owner /// @param vcId is the virtual chain ID /// @param owner is the address of the new owner function setVcOwner(uint256 vcId, address owner) external /* onlyVcOwner */; /// Returns the data of a virtual chain /// @dev does not include config records data /// @param vcId is the virtual chain ID /// @return name is the virtual chain name /// @return tier is the virtual chain tier /// @return rate is the virtual chain tier rate /// @return expiresAt the virtual chain subscription expiration time /// @return genRefTime is the virtual chain genesis reference time /// @return owner is the virtual chain owner. The owner may change virtual chain properties or ser config records /// @return deploymentSubset indicates the code deployment subset the virtual chain uses such as main or canary /// @return isCertified indicates the virtual is run by the certified committee function getVcData(uint256 vcId) external view returns ( string memory name, string memory tier, uint256 rate, uint expiresAt, uint256 genRefTime, address owner, string memory deploymentSubset, bool isCertified ); /* * Governance functions */ event SubscriberAdded(address subscriber); event SubscriberRemoved(address subscriber); event GenesisRefTimeDelayChanged(uint256 newGenesisRefTimeDelay); event MinimumInitialVcPaymentChanged(uint256 newMinimumInitialVcPayment); /// Adds a subscription plan contract to the authorized subscribers list /// @dev governance function called only by the functional manager /// @param addr is the address of the subscription plan contract function addSubscriber(address addr) external /* onlyFunctionalManager */; /// Removes a subscription plan contract to the authorized subscribers list /// @dev governance function called only by the functional manager /// @param addr is the address of the subscription plan contract function removeSubscriber(address addr) external /* onlyFunctionalManager */; /// Sets the delay between a virtual chain genesis reference time and the virtual chain creation time /// @dev governance function called only by the functional manager /// @dev the reference time delay allows the guardian to be ready with the virtual chain resources for the first block consensus /// @param newGenesisRefTimeDelay is the delay time in seconds function setGenesisRefTimeDelay(uint256 newGenesisRefTimeDelay) external /* onlyFunctionalManager */; /// Returns the genesis reference time delay /// @return genesisRefTimeDelay is the delay time in seconds function getGenesisRefTimeDelay() external view returns (uint256); /// Sets the minimum initial virtual chain payment /// @dev Prevents abuse of the guardian nodes resources /// @param newMinimumInitialVcPayment is the minimum payment required for the initial subscription function setMinimumInitialVcPayment(uint256 newMinimumInitialVcPayment) external /* onlyFunctionalManager */; /// Returns the minimum initial virtual chain payment /// @return minimumInitialVcPayment is the minimum payment required for the initial subscription function getMinimumInitialVcPayment() external view returns (uint256); /// Returns the settings of this contract /// @return genesisRefTimeDelay is the delay time in seconds /// @return minimumInitialVcPayment is the minimum payment required for the initial subscription function getSettings() external view returns( uint genesisRefTimeDelay, uint256 minimumInitialVcPayment ); /// Imports virtual chain subscription from a previous subscriptions contract /// @dev governance function called only by the initialization admin during migration /// @dev if the migrated vcId is larger or equal to the next virtual chain ID to allocate, increment the next virtual chain ID /// @param vcId is the virtual chain ID to migrate /// @param previousSubscriptionsContract is the address of the previous subscription contract function importSubscription(uint vcId, ISubscriptions previousSubscriptionsContract) external /* onlyInitializationAdmin */; } // File: contracts/spec_interfaces/IProtocol.sol pragma solidity 0.6.12; /// @title Protocol upgrades contract interface interface IProtocol { event ProtocolVersionChanged(string deploymentSubset, uint256 currentVersion, uint256 nextVersion, uint256 fromTimestamp); /* * External functions */ /// Checks whether a deployment subset exists /// @param deploymentSubset is the name of the deployment subset to query /// @return exists is a bool indicating the deployment subset exists function deploymentSubsetExists(string calldata deploymentSubset) external view returns (bool); /// Returns the current protocol version for a given deployment subset to query /// @dev an unexisting deployment subset returns protocol version 0 /// @param deploymentSubset is the name of the deployment subset /// @return currentVersion is the current protocol version of the deployment subset function getProtocolVersion(string calldata deploymentSubset) external view returns (uint256 currentVersion); /* * Governance functions */ /// Creates a new deployment subset /// @dev governance function called only by the functional manager /// @param deploymentSubset is the name of the new deployment subset /// @param initialProtocolVersion is the initial protocol version of the deployment subset function createDeploymentSubset(string calldata deploymentSubset, uint256 initialProtocolVersion) external /* onlyFunctionalManager */; /// Schedules a protocol version upgrade for the given deployment subset /// @dev governance function called only by the functional manager /// @param deploymentSubset is the name of the deployment subset /// @param nextVersion is the new protocol version to upgrade to, must be greater or equal to current version /// @param fromTimestamp is the time the new protocol version takes effect, must be in the future function setProtocolVersion(string calldata deploymentSubset, uint256 nextVersion, uint256 fromTimestamp) external /* onlyFunctionalManager */; } // File: contracts/spec_interfaces/IMigratableFeesWallet.sol pragma solidity 0.6.12; /// @title An interface for Fee wallets that support bucket migration. interface IMigratableFeesWallet { /// Accepts a bucket fees from a old fees wallet as part of a migration /// @dev Called by the old FeesWallet contract. /// @dev Part of the IMigratableFeesWallet interface. /// @dev assumes the caller approved the transfer of the amount prior to calling /// @param bucketStartTime is the start time of the bucket to migration, must be a bucket's valid start time /// @param amount is the amount to migrate (transfer) to the bucket function acceptBucketMigration(uint256 bucketStartTime, uint256 amount) external; } // File: contracts/spec_interfaces/IFeesWallet.sol pragma solidity 0.6.12; /// @title Fees Wallet contract interface, manages the fee buckets interface IFeesWallet { event FeesWithdrawnFromBucket(uint256 bucketId, uint256 withdrawn, uint256 total); event FeesAddedToBucket(uint256 bucketId, uint256 added, uint256 total); /* * External methods */ /// Top-ups the fee pool with the given amount at the given rate /// @dev Called by: subscriptions contract. (not enforced) /// @dev fills the rewards in 30 days buckets based on the monthlyRate /// @param amount is the amount to fill /// @param monthlyRate is the monthly rate /// @param fromTimestamp is the to start fill the buckets, determines the first bucket to fill and the amount filled in the first bucket. function fillFeeBuckets(uint256 amount, uint256 monthlyRate, uint256 fromTimestamp) external; /// Collect fees from the buckets since the last call and transfers the amount back. /// @dev Called by: only FeesAndBootstrapRewards contract /// @dev The amount to collect may be queried before collect by calling getOutstandingFees /// @return collectedFees the amount of fees collected and transferred function collectFees() external returns (uint256 collectedFees) /* onlyRewardsContract */; /// Returns the amount of fees that are currently available for withdrawal /// @param currentTime is the time to check the pending fees for /// @return outstandingFees is the amount of pending fees to collect at time currentTime function getOutstandingFees(uint256 currentTime) external view returns (uint256 outstandingFees); /* * General governance */ event EmergencyWithdrawal(address addr, address token); /// Migrates the fees of a bucket starting at startTimestamp. /// @dev governance function called only by the migration manager /// @dev Calls acceptBucketMigration in the destination contract. /// @param destination is the address of the new FeesWallet contract /// @param bucketStartTime is the start time of the bucket to migration, must be a bucket's valid start time function migrateBucket(IMigratableFeesWallet destination, uint256 bucketStartTime) external /* onlyMigrationManager */; /// Accepts a fees bucket balance from a old fees wallet as part of the fees wallet migration /// @dev Called by the old FeesWallet contract. /// @dev Part of the IMigratableFeesWallet interface. /// @dev assumes the caller approved the amount prior to calling /// @param bucketStartTime is the start time of the bucket to migration, must be a bucket's valid start time /// @param amount is the amount to migrate (transfer) to the bucket function acceptBucketMigration(uint256 bucketStartTime, uint256 amount) external; /// Emergency withdraw the contract funds /// @dev governance function called only by the migration manager /// @dev used in emergencies only, where migrateBucket is not a suitable solution /// @param erc20 is the erc20 address of the token to withdraw function emergencyWithdraw(address erc20) external /* onlyMigrationManager */; } // File: contracts/spec_interfaces/IManagedContract.sol pragma solidity 0.6.12; /// @title managed contract interface, used by the contracts registry to notify the contract on updates interface IManagedContract /* is ILockable, IContractRegistryAccessor, Initializable */ { /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() external; } // File: contracts/spec_interfaces/IContractRegistry.sol pragma solidity 0.6.12; /// @title Contract registry contract interface /// @dev The contract registry holds Orbs PoS contracts and managers lists /// @dev The contract registry updates the managed contracts on changes in the contract list /// @dev Governance functions restricted to managers access the registry to retrieve the manager address /// @dev The contract registry represents the source of truth for Orbs Ethereum contracts /// @dev By tracking the registry events or query before interaction, one can access the up to date contracts interface IContractRegistry { event ContractAddressUpdated(string contractName, address addr, bool managedContract); event ManagerChanged(string role, address newManager); event ContractRegistryUpdated(address newContractRegistry); /* * External functions */ /// Updates the contracts address and emits a corresponding event /// @dev governance function called only by the migrationManager or registryAdmin /// @param contractName is the contract name, used to identify it /// @param addr is the contract updated address /// @param managedContract indicates whether the contract is managed by the registry and notified on changes function setContract(string calldata contractName, address addr, bool managedContract) external /* onlyAdminOrMigrationManager */; /// Returns the current address of the given contracts /// @param contractName is the contract name, used to identify it /// @return addr is the contract updated address function getContract(string calldata contractName) external view returns (address); /// Returns the list of contract addresses managed by the registry /// @dev Managed contracts are updated on changes in the registry contracts addresses /// @return addrs is the list of managed contracts function getManagedContracts() external view returns (address[] memory); /// Locks all the managed contracts /// @dev governance function called only by the migrationManager or registryAdmin /// @dev When set all onlyWhenActive functions will revert function lockContracts() external /* onlyAdminOrMigrationManager */; /// Unlocks all the managed contracts /// @dev governance function called only by the migrationManager or registryAdmin function unlockContracts() external /* onlyAdminOrMigrationManager */; /// Updates a manager address and emits a corresponding event /// @dev governance function called only by the registryAdmin /// @dev the managers list is a flexible list of role to the manager's address /// @param role is the managers' role name, for example "functionalManager" /// @param manager is the manager updated address function setManager(string calldata role, address manager) external /* onlyAdmin */; /// Returns the current address of the given manager /// @param role is the manager name, used to identify it /// @return addr is the manager updated address function getManager(string calldata role) external view returns (address); /// Sets a new contract registry to migrate to /// @dev governance function called only by the registryAdmin /// @dev updates the registry address record in all the managed contracts /// @dev by tracking the emitted ContractRegistryUpdated, tools can track the up to date contracts /// @param newRegistry is the new registry contract function setNewContractRegistry(IContractRegistry newRegistry) external /* onlyAdmin */; /// Returns the previous contract registry address /// @dev used when the setting the contract as a new registry to assure a valid registry /// @return previousContractRegistry is the previous contract registry function getPreviousContractRegistry() external view returns (address); } // File: contracts/spec_interfaces/IContractRegistryAccessor.sol pragma solidity 0.6.12; interface IContractRegistryAccessor { /// Sets the contract registry address /// @dev governance function called only by an admin /// @param newRegistry is the new registry contract function setContractRegistry(IContractRegistry newRegistry) external /* onlyAdmin */; /// Returns the contract registry address /// @return contractRegistry is the contract registry address function getContractRegistry() external view returns (IContractRegistry contractRegistry); function setRegistryAdmin(address _registryAdmin) external /* onlyInitializationAdmin */; } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.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 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/WithClaimableRegistryManagement.sol pragma solidity 0.6.12; /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract WithClaimableRegistryManagement is Context { address private _registryAdmin; address private _pendingRegistryAdmin; event RegistryManagementTransferred(address indexed previousRegistryAdmin, address indexed newRegistryAdmin); /** * @dev Initializes the contract setting the deployer as the initial registryRegistryAdmin. */ constructor () internal { address msgSender = _msgSender(); _registryAdmin = msgSender; emit RegistryManagementTransferred(address(0), msgSender); } /** * @dev Returns the address of the current registryAdmin. */ function registryAdmin() public view returns (address) { return _registryAdmin; } /** * @dev Throws if called by any account other than the registryAdmin. */ modifier onlyRegistryAdmin() { require(isRegistryAdmin(), "WithClaimableRegistryManagement: caller is not the registryAdmin"); _; } /** * @dev Returns true if the caller is the current registryAdmin. */ function isRegistryAdmin() public view returns (bool) { return _msgSender() == _registryAdmin; } /** * @dev Leaves the contract without registryAdmin. It will not be possible to call * `onlyManager` functions anymore. Can only be called by the current registryAdmin. * * NOTE: Renouncing registryManagement will leave the contract without an registryAdmin, * thereby removing any functionality that is only available to the registryAdmin. */ function renounceRegistryManagement() public onlyRegistryAdmin { emit RegistryManagementTransferred(_registryAdmin, address(0)); _registryAdmin = address(0); } /** * @dev Transfers registryManagement of the contract to a new account (`newManager`). */ function _transferRegistryManagement(address newRegistryAdmin) internal { require(newRegistryAdmin != address(0), "RegistryAdmin: new registryAdmin is the zero address"); emit RegistryManagementTransferred(_registryAdmin, newRegistryAdmin); _registryAdmin = newRegistryAdmin; } /** * @dev Modifier throws if called by any account other than the pendingManager. */ modifier onlyPendingRegistryAdmin() { require(msg.sender == _pendingRegistryAdmin, "Caller is not the pending registryAdmin"); _; } /** * @dev Allows the current registryAdmin to set the pendingManager address. * @param newRegistryAdmin The address to transfer registryManagement to. */ function transferRegistryManagement(address newRegistryAdmin) public onlyRegistryAdmin { _pendingRegistryAdmin = newRegistryAdmin; } /** * @dev Allows the _pendingRegistryAdmin address to finalize the transfer. */ function claimRegistryManagement() external onlyPendingRegistryAdmin { _transferRegistryManagement(_pendingRegistryAdmin); _pendingRegistryAdmin = address(0); } /** * @dev Returns the current pendingRegistryAdmin */ function pendingRegistryAdmin() public view returns (address) { return _pendingRegistryAdmin; } } // File: contracts/Initializable.sol pragma solidity 0.6.12; contract Initializable { address private _initializationAdmin; event InitializationComplete(); /// Constructor /// Sets the initializationAdmin to the contract deployer /// The initialization admin may call any manager only function until initializationComplete constructor() public{ _initializationAdmin = msg.sender; } modifier onlyInitializationAdmin() { require(msg.sender == initializationAdmin(), "sender is not the initialization admin"); _; } /* * External functions */ /// Returns the initializationAdmin address function initializationAdmin() public view returns (address) { return _initializationAdmin; } /// Finalizes the initialization and revokes the initializationAdmin role function initializationComplete() external onlyInitializationAdmin { _initializationAdmin = address(0); emit InitializationComplete(); } /// Checks if the initialization was completed function isInitializationComplete() public view returns (bool) { return _initializationAdmin == address(0); } } // File: contracts/ContractRegistryAccessor.sol pragma solidity 0.6.12; contract ContractRegistryAccessor is IContractRegistryAccessor, WithClaimableRegistryManagement, Initializable { IContractRegistry private contractRegistry; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address constructor(IContractRegistry _contractRegistry, address _registryAdmin) public { require(address(_contractRegistry) != address(0), "_contractRegistry cannot be 0"); setContractRegistry(_contractRegistry); _transferRegistryManagement(_registryAdmin); } modifier onlyAdmin { require(isAdmin(), "sender is not an admin (registryManger or initializationAdmin)"); _; } modifier onlyMigrationManager { require(isMigrationManager(), "sender is not the migration manager"); _; } modifier onlyFunctionalManager { require(isFunctionalManager(), "sender is not the functional manager"); _; } /// Checks whether the caller is Admin: either the contract registry, the registry admin, or the initialization admin function isAdmin() internal view returns (bool) { return msg.sender == address(contractRegistry) || msg.sender == registryAdmin() || msg.sender == initializationAdmin(); } /// Checks whether the caller is a specific manager role or and Admin /// @dev queries the registry contract for the up to date manager assignment function isManager(string memory role) internal view returns (bool) { IContractRegistry _contractRegistry = contractRegistry; return isAdmin() || _contractRegistry != IContractRegistry(0) && contractRegistry.getManager(role) == msg.sender; } /// Checks whether the caller is the migration manager function isMigrationManager() internal view returns (bool) { return isManager('migrationManager'); } /// Checks whether the caller is the functional manager function isFunctionalManager() internal view returns (bool) { return isManager('functionalManager'); } /* * Contract getters, return the address of a contract by calling the contract registry */ function getProtocolContract() internal view returns (address) { return contractRegistry.getContract("protocol"); } function getStakingRewardsContract() internal view returns (address) { return contractRegistry.getContract("stakingRewards"); } function getFeesAndBootstrapRewardsContract() internal view returns (address) { return contractRegistry.getContract("feesAndBootstrapRewards"); } function getCommitteeContract() internal view returns (address) { return contractRegistry.getContract("committee"); } function getElectionsContract() internal view returns (address) { return contractRegistry.getContract("elections"); } function getDelegationsContract() internal view returns (address) { return contractRegistry.getContract("delegations"); } function getGuardiansRegistrationContract() internal view returns (address) { return contractRegistry.getContract("guardiansRegistration"); } function getCertificationContract() internal view returns (address) { return contractRegistry.getContract("certification"); } function getStakingContract() internal view returns (address) { return contractRegistry.getContract("staking"); } function getSubscriptionsContract() internal view returns (address) { return contractRegistry.getContract("subscriptions"); } function getStakingRewardsWallet() internal view returns (address) { return contractRegistry.getContract("stakingRewardsWallet"); } function getBootstrapRewardsWallet() internal view returns (address) { return contractRegistry.getContract("bootstrapRewardsWallet"); } function getGeneralFeesWallet() internal view returns (address) { return contractRegistry.getContract("generalFeesWallet"); } function getCertifiedFeesWallet() internal view returns (address) { return contractRegistry.getContract("certifiedFeesWallet"); } function getStakingContractHandler() internal view returns (address) { return contractRegistry.getContract("stakingContractHandler"); } /* * Governance functions */ event ContractRegistryAddressUpdated(address addr); /// Sets the contract registry address /// @dev governance function called only by an admin /// @param newContractRegistry is the new registry contract function setContractRegistry(IContractRegistry newContractRegistry) public override onlyAdmin { require(newContractRegistry.getPreviousContractRegistry() == address(contractRegistry), "new contract registry must provide the previous contract registry"); contractRegistry = newContractRegistry; emit ContractRegistryAddressUpdated(address(newContractRegistry)); } /// Returns the contract registry that the contract is set to use /// @return contractRegistry is the registry contract address function getContractRegistry() public override view returns (IContractRegistry) { return contractRegistry; } function setRegistryAdmin(address _registryAdmin) external override onlyInitializationAdmin { _transferRegistryManagement(_registryAdmin); } } // File: contracts/spec_interfaces/ILockable.sol pragma solidity 0.6.12; /// @title lockable contract interface, allows to lock a contract interface ILockable { event Locked(); event Unlocked(); /// Locks the contract to external non-governance function calls /// @dev governance function called only by the migration manager or an admin /// @dev typically called by the registry contract upon locking all managed contracts /// @dev getters and migration functions remain active also for locked contracts /// @dev checked by the onlyWhenActive modifier function lock() external /* onlyMigrationManager */; /// Unlocks the contract /// @dev governance function called only by the migration manager or an admin /// @dev typically called by the registry contract upon unlocking all managed contracts function unlock() external /* onlyMigrationManager */; /// Returns the contract locking status /// @return isLocked is a bool indicating the contract is locked function isLocked() view external returns (bool); } // File: contracts/Lockable.sol pragma solidity 0.6.12; /// @title lockable contract contract Lockable is ILockable, ContractRegistryAccessor { bool public locked; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address constructor(IContractRegistry _contractRegistry, address _registryAdmin) ContractRegistryAccessor(_contractRegistry, _registryAdmin) public {} /// Locks the contract to external non-governance function calls /// @dev governance function called only by the migration manager or an admin /// @dev typically called by the registry contract upon locking all managed contracts /// @dev getters and migration functions remain active also for locked contracts /// @dev checked by the onlyWhenActive modifier function lock() external override onlyMigrationManager { locked = true; emit Locked(); } /// Unlocks the contract /// @dev governance function called only by the migration manager or an admin /// @dev typically called by the registry contract upon unlocking all managed contracts function unlock() external override onlyMigrationManager { locked = false; emit Unlocked(); } /// Returns the contract locking status /// @return isLocked is a bool indicating the contract is locked function isLocked() external override view returns (bool) { return locked; } modifier onlyWhenActive() { require(!locked, "contract is locked for this operation"); _; } } // File: contracts/ManagedContract.sol pragma solidity 0.6.12; /// @title managed contract contract ManagedContract is IManagedContract, Lockable { /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address constructor(IContractRegistry _contractRegistry, address _registryAdmin) Lockable(_contractRegistry, _registryAdmin) public {} /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() virtual override external {} } // File: contracts/Subscriptions.sol pragma solidity 0.6.12; /// @title Subscriptions contract contract Subscriptions is ISubscriptions, ManagedContract { using SafeMath for uint256; struct VirtualChain { string name; string tier; uint256 rate; uint expiresAt; uint256 genRefTime; address owner; string deploymentSubset; bool isCertified; } mapping(uint => mapping(string => string)) configRecords; mapping(address => bool) public authorizedSubscribers; mapping(uint => VirtualChain) virtualChains; uint public nextVcId; struct Settings { uint genesisRefTimeDelay; uint256 minimumInitialVcPayment; } Settings settings; IERC20 public erc20; /// Constructor /// @dev the next allocated virtual chain id on createVC is the next ID after the maximum between the migrated virtual chains and the initialNextVcId /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address /// @param _erc20 is the token used for virtual chains fees /// @param _genesisRefTimeDelay is the initial genesis virtual chain reference time delay from the creation time /// @param _minimumInitialVcPayment is the minimum payment required for the initial subscription /// @param vcIds is a list of virtual chain ids to migrate from the previous subscription contract /// @param initialNextVcId is the initial virtual chain id /// @param previousSubscriptionsContract is the previous subscription contract to migrate virtual chains from constructor (IContractRegistry _contractRegistry, address _registryAdmin, IERC20 _erc20, uint256 _genesisRefTimeDelay, uint256 _minimumInitialVcPayment, uint[] memory vcIds, uint256 initialNextVcId, ISubscriptions previousSubscriptionsContract) ManagedContract(_contractRegistry, _registryAdmin) public { require(address(_erc20) != address(0), "erc20 must not be 0"); erc20 = _erc20; nextVcId = initialNextVcId; setGenesisRefTimeDelay(_genesisRefTimeDelay); setMinimumInitialVcPayment(_minimumInitialVcPayment); for (uint i = 0; i < vcIds.length; i++) { importSubscription(vcIds[i], previousSubscriptionsContract); } } modifier onlySubscriber { require(authorizedSubscribers[msg.sender], "sender must be an authorized subscriber"); _; } /* * External functions */ /// Creates a new virtual chain /// @dev Called only by: an authorized subscription plan contract /// @dev the initial amount paid for the virtual chain must be large than minimumInitialVcPayment /// @param name is the virtual chain name /// @param tier is the virtual chain tier /// @param rate is the virtual chain tier rate as determined by the subscription plan /// @param amount is the amount paid for the virtual chain initial subscription /// @param owner is the virtual chain owner. The owner may change virtual chain properties or ser config records /// @param isCertified indicates the virtual is run by the certified committee /// @param deploymentSubset indicates the code deployment subset the virtual chain uses such as main or canary /// @return vcId is the virtual chain ID allocated to the new virtual chain /// @return genRefTime is the virtual chain genesis reference time that determines the first block committee function createVC(string calldata name, string calldata tier, uint256 rate, uint256 amount, address owner, bool isCertified, string calldata deploymentSubset) external override onlySubscriber onlyWhenActive returns (uint vcId, uint genRefTime) { require(owner != address(0), "vc owner cannot be the zero address"); require(protocolContract.deploymentSubsetExists(deploymentSubset) == true, "No such deployment subset"); require(amount >= settings.minimumInitialVcPayment, "initial VC payment must be at least minimumInitialVcPayment"); vcId = nextVcId++; genRefTime = now + settings.genesisRefTimeDelay; VirtualChain memory vc = VirtualChain({ name: name, expiresAt: block.timestamp, genRefTime: genRefTime, owner: owner, tier: tier, rate: rate, deploymentSubset: deploymentSubset, isCertified: isCertified }); virtualChains[vcId] = vc; emit VcCreated(vcId); _extendSubscription(vcId, amount, tier, rate, owner); } /// Extends the subscription of an existing virtual chain. /// @dev Called only by: an authorized subscription plan contract /// @param vcId is the virtual chain ID /// @param amount is the amount paid for the virtual chain subscription extension /// @param tier is the virtual chain tier, must match the tier selected in the virtual creation /// @param rate is the virtual chain tier rate as determined by the subscription plan /// @param payer is the address paying for the subscription extension function extendSubscription(uint256 vcId, uint256 amount, string calldata tier, uint256 rate, address payer) external override onlySubscriber onlyWhenActive { _extendSubscription(vcId, amount, tier, rate, payer); } /// Sets a virtual chain config record /// @dev may be called only by the virtual chain owner /// @param vcId is the virtual chain ID /// @param key is the name of the config record to update /// @param value is the config record value function setVcConfigRecord(uint256 vcId, string calldata key, string calldata value) external override onlyWhenActive { require(msg.sender == virtualChains[vcId].owner, "only vc owner can set a vc config record"); configRecords[vcId][key] = value; emit VcConfigRecordChanged(vcId, key, value); } /// Returns the value of a virtual chain config record /// @param vcId is the virtual chain ID /// @param key is the name of the config record to query /// @return value is the config record value function getVcConfigRecord(uint256 vcId, string calldata key) external override view returns (string memory) { return configRecords[vcId][key]; } /// Transfers a virtual chain ownership to a new owner /// @dev may be called only by the current virtual chain owner /// @param vcId is the virtual chain ID /// @param owner is the address of the new owner function setVcOwner(uint256 vcId, address owner) external override onlyWhenActive { require(msg.sender == virtualChains[vcId].owner, "only the vc owner can transfer ownership"); require(owner != address(0), "cannot transfer ownership to the zero address"); virtualChains[vcId].owner = owner; emit VcOwnerChanged(vcId, msg.sender, owner); } /// Returns the data of a virtual chain /// @dev does not include config records data /// @param vcId is the virtual chain ID /// @return name is the virtual chain name /// @return tier is the virtual chain tier /// @return rate is the virtual chain tier rate /// @return expiresAt the virtual chain subscription expiration time /// @return genRefTime is the virtual chain genesis reference time /// @return owner is the virtual chain owner. The owner may change virtual chain properties or ser config records /// @return deploymentSubset indicates the code deployment subset the virtual chain uses such as main or canary /// @return isCertified indicates the virtual is run by the certified committee function getVcData(uint256 vcId) external override view returns ( string memory name, string memory tier, uint256 rate, uint expiresAt, uint256 genRefTime, address owner, string memory deploymentSubset, bool isCertified ) { VirtualChain memory vc = virtualChains[vcId]; name = vc.name; tier = vc.tier; rate = vc.rate; expiresAt = vc.expiresAt; genRefTime = vc.genRefTime; owner = vc.owner; deploymentSubset = vc.deploymentSubset; isCertified = vc.isCertified; } /* * Governance functions */ /// Adds a subscription plan contract to the authorized subscribers list /// @dev governance function called only by the functional manager /// @param addr is the address of the subscription plan contract function addSubscriber(address addr) external override onlyFunctionalManager { authorizedSubscribers[addr] = true; emit SubscriberAdded(addr); } /// Removes a subscription plan contract to the authorized subscribers list /// @dev governance function called only by the functional manager /// @param addr is the address of the subscription plan contract function removeSubscriber(address addr) external override onlyFunctionalManager { require(authorizedSubscribers[addr], "given add is not an authorized subscriber"); authorizedSubscribers[addr] = false; emit SubscriberRemoved(addr); } /// Sets the delay between a virtual chain genesis reference time and the virtual chain creation time /// @dev governance function called only by the functional manager /// @dev the reference time delay allows the guardian to be ready with the virtual chain resources for the first block consensus /// @param newGenesisRefTimeDelay is the delay time in seconds function setGenesisRefTimeDelay(uint256 newGenesisRefTimeDelay) public override onlyFunctionalManager { settings.genesisRefTimeDelay = newGenesisRefTimeDelay; emit GenesisRefTimeDelayChanged(newGenesisRefTimeDelay); } /// Returns the genesis reference time delay /// @return genesisRefTimeDelay is the delay time in seconds function getGenesisRefTimeDelay() external override view returns (uint) { return settings.genesisRefTimeDelay; } /// Sets the minimum initial virtual chain payment /// @dev Prevents abuse of the guardian nodes resources /// @param newMinimumInitialVcPayment is the minimum payment required for the initial subscription function setMinimumInitialVcPayment(uint256 newMinimumInitialVcPayment) public override onlyFunctionalManager { settings.minimumInitialVcPayment = newMinimumInitialVcPayment; emit MinimumInitialVcPaymentChanged(newMinimumInitialVcPayment); } /// Returns the minimum initial virtual chain payment /// @return minimumInitialVcPayment is the minimum payment required for the initial subscription function getMinimumInitialVcPayment() external override view returns (uint) { return settings.minimumInitialVcPayment; } /// Returns the settings of this contract /// @return genesisRefTimeDelay is the delay time in seconds /// @return minimumInitialVcPayment is the minimum payment required for the initial subscription function getSettings() external override view returns( uint genesisRefTimeDelay, uint256 minimumInitialVcPayment ) { Settings memory _settings = settings; genesisRefTimeDelay = _settings.genesisRefTimeDelay; minimumInitialVcPayment = _settings.minimumInitialVcPayment; } /// Imports virtual chain subscription from a previous subscriptions contract /// @dev governance function called only by the initialization admin during migration /// @dev if the migrated vcId is larger or equal to the next virtual chain ID to allocate, increment the next virtual chain ID /// @param vcId is the virtual chain ID to migrate /// @param previousSubscriptionsContract is the address of the previous subscription contract function importSubscription(uint vcId, ISubscriptions previousSubscriptionsContract) public override onlyInitializationAdmin { require(virtualChains[vcId].owner == address(0), "the vcId already exists"); (string memory name, string memory tier, uint256 rate, uint expiresAt, uint256 genRefTime, address owner, string memory deploymentSubset, bool isCertified) = previousSubscriptionsContract.getVcData(vcId); virtualChains[vcId] = VirtualChain({ name: name, tier: tier, rate: rate, expiresAt: expiresAt, genRefTime: genRefTime, owner: owner, deploymentSubset: deploymentSubset, isCertified: isCertified }); if (vcId >= nextVcId) { nextVcId = vcId + 1; } emit SubscriptionChanged(vcId, owner, name, genRefTime, tier, rate, expiresAt, isCertified, deploymentSubset); } /* * Private functions */ /// Extends the subscription of an existing virtual chain. /// @dev used by createVC and extendSubscription functions for subscription payment /// @dev assumes that the msg.sender approved the amount prior to the call /// @param vcId is the virtual chain ID /// @param amount is the amount paid for the virtual chain subscription extension /// @param tier is the virtual chain tier, must match the tier selected in the virtual creation /// @param rate is the virtual chain tier rate as determined by the subscription plan /// @param payer is the address paying for the subscription extension function _extendSubscription(uint256 vcId, uint256 amount, string memory tier, uint256 rate, address payer) private { VirtualChain memory vc = virtualChains[vcId]; require(vc.genRefTime != 0, "vc does not exist"); require(keccak256(bytes(tier)) == keccak256(bytes(virtualChains[vcId].tier)), "given tier must match the VC tier"); IFeesWallet feesWallet = vc.isCertified ? certifiedFeesWallet : generalFeesWallet; require(erc20.transferFrom(msg.sender, address(this), amount), "failed to transfer subscription fees from subscriber to subscriptions"); require(erc20.approve(address(feesWallet), amount), "failed to approve rewards to acquire subscription fees"); uint fromTimestamp = vc.expiresAt > now ? vc.expiresAt : now; feesWallet.fillFeeBuckets(amount, rate, fromTimestamp); vc.expiresAt = fromTimestamp.add(amount.mul(30 days).div(rate)); vc.rate = rate; // commit new expiration timestamp to storage virtualChains[vcId].expiresAt = vc.expiresAt; virtualChains[vcId].rate = vc.rate; emit SubscriptionChanged(vcId, vc.owner, vc.name, vc.genRefTime, vc.tier, vc.rate, vc.expiresAt, vc.isCertified, vc.deploymentSubset); emit Payment(vcId, payer, amount, vc.tier, vc.rate); } /* * Contracts topology / registry interface */ IFeesWallet generalFeesWallet; IFeesWallet certifiedFeesWallet; IProtocol protocolContract; /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() external override { generalFeesWallet = IFeesWallet(getGeneralFeesWallet()); certifiedFeesWallet = IFeesWallet(getCertifiedFeesWallet()); protocolContract = IProtocol(getProtocolContract()); } } // File: contracts/ContractRegistry.sol pragma solidity 0.6.12; /// @title Contract registry /// @dev The contract registry holds Orbs PoS contracts and managers lists /// @dev The contract registry updates the managed contracts on changes in the contract list /// @dev Governance functions restricted to managers access the registry to retrieve the manager address /// @dev The contract registry represents the source of truth for Orbs Ethereum contracts /// @dev By tracking the registry events or query before interaction, one can access the up to date contracts contract ContractRegistry is IContractRegistry, Initializable, WithClaimableRegistryManagement { address previousContractRegistry; mapping(string => address) contracts; address[] managedContractAddresses; mapping(string => address) managers; /// Constructor /// @param _previousContractRegistry is the previous contract registry address /// @param registryAdmin is the registry contract admin address constructor(address _previousContractRegistry, address registryAdmin) public { previousContractRegistry = _previousContractRegistry; _transferRegistryManagement(registryAdmin); } modifier onlyAdmin { require(msg.sender == registryAdmin() || msg.sender == initializationAdmin(), "sender is not an admin (registryAdmin or initializationAdmin when initialization in progress)"); _; } modifier onlyAdminOrMigrationManager { require(msg.sender == registryAdmin() || msg.sender == initializationAdmin() || msg.sender == managers["migrationManager"], "sender is not an admin (registryAdmin or initializationAdmin when initialization in progress) and not the migration manager"); _; } /* * External functions */ /// Updates the contracts address and emits a corresponding event /// @dev governance function called only by the migrationManager or registryAdmin /// @param contractName is the contract name, used to identify it /// @param addr is the contract updated address /// @param managedContract indicates whether the contract is managed by the registry and notified on changes function setContract(string calldata contractName, address addr, bool managedContract) external override onlyAdminOrMigrationManager { require(!managedContract || addr != address(0), "managed contract may not have address(0)"); removeManagedContract(contracts[contractName]); contracts[contractName] = addr; if (managedContract) { addManagedContract(addr); } emit ContractAddressUpdated(contractName, addr, managedContract); notifyOnContractsChange(); } /// Returns the current address of the given contracts /// @param contractName is the contract name, used to identify it /// @return addr is the contract updated address function getContract(string calldata contractName) external override view returns (address) { return contracts[contractName]; } /// Returns the list of contract addresses managed by the registry /// @dev Managed contracts are updated on changes in the registry contracts addresses /// @return addrs is the list of managed contracts function getManagedContracts() external override view returns (address[] memory) { return managedContractAddresses; } /// Locks all the managed contracts /// @dev governance function called only by the migrationManager or registryAdmin /// @dev When set all onlyWhenActive functions will revert function lockContracts() external override onlyAdminOrMigrationManager { for (uint i = 0; i < managedContractAddresses.length; i++) { ILockable(managedContractAddresses[i]).lock(); } } /// Unlocks all the managed contracts /// @dev governance function called only by the migrationManager or registryAdmin function unlockContracts() external override onlyAdminOrMigrationManager { for (uint i = 0; i < managedContractAddresses.length; i++) { ILockable(managedContractAddresses[i]).unlock(); } } /// Updates a manager address and emits a corresponding event /// @dev governance function called only by the registryAdmin /// @dev the managers list is a flexible list of role to the manager's address /// @param role is the managers' role name, for example "functionalManager" /// @param manager is the manager updated address function setManager(string calldata role, address manager) external override onlyAdmin { managers[role] = manager; emit ManagerChanged(role, manager); } /// Returns the current address of the given manager /// @param role is the manager name, used to identify it /// @return addr is the manager updated address function getManager(string calldata role) external override view returns (address) { return managers[role]; } /// Sets a new contract registry to migrate to /// @dev governance function called only by the registryAdmin /// @dev updates the registry address record in all the managed contracts /// @dev by tracking the emitted ContractRegistryUpdated, tools can track the up to date contracts /// @param newRegistry is the new registry contract function setNewContractRegistry(IContractRegistry newRegistry) external override onlyAdmin { for (uint i = 0; i < managedContractAddresses.length; i++) { IContractRegistryAccessor(managedContractAddresses[i]).setContractRegistry(newRegistry); IManagedContract(managedContractAddresses[i]).refreshContracts(); } emit ContractRegistryUpdated(address(newRegistry)); } /// Returns the previous contract registry address /// @dev used when the setting the contract as a new registry to assure a valid registry /// @return previousContractRegistry is the previous contract registry function getPreviousContractRegistry() external override view returns (address) { return previousContractRegistry; } /* * Private methods */ /// Notifies the managed contracts on a change in a contract address /// @dev invokes the refreshContracts() function in each contract that queries the relevant contract addresses function notifyOnContractsChange() private { for (uint i = 0; i < managedContractAddresses.length; i++) { IManagedContract(managedContractAddresses[i]).refreshContracts(); } } /// Adds a new managed contract address to the managed contracts list function addManagedContract(address addr) private { managedContractAddresses.push(addr); } /// Removes a managed contract address from the managed contracts list function removeManagedContract(address addr) private { uint length = managedContractAddresses.length; for (uint i = 0; i < length; i++) { if (managedContractAddresses[i] == addr) { if (i != length - 1) { managedContractAddresses[i] = managedContractAddresses[length-1]; } managedContractAddresses.pop(); length--; } } } } // File: contracts/MonthlySubscriptionPlan.sol pragma solidity 0.6.12; /// @title monthly subscription plan contract contract MonthlySubscriptionPlan is ContractRegistryAccessor { string public tier; uint256 public monthlyRate; IERC20 public erc20; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address /// @param _erc20 is the token used for virtual chains fees /// @param _tier is the virtual chain tier for the monthly subscription plan /// @param _monthlyRate is the virtual chain tier rate constructor(IContractRegistry _contractRegistry, address _registryAdmin, IERC20 _erc20, string memory _tier, uint256 _monthlyRate) ContractRegistryAccessor(_contractRegistry, _registryAdmin) public { require(bytes(_tier).length > 0, "must specify a valid tier label"); tier = _tier; erc20 = _erc20; monthlyRate = _monthlyRate; } /* * External functions */ /// Creates a new virtual chain /// @dev the virtual chain tier and rate are determined by the contract /// @dev the contract calls the subscription contract that stores the virtual chain data and allocates a virtual chain ID /// @dev the msg.sender that created the virtual chain is set as the initial virtual chain owner /// @dev the initial amount paid for the virtual chain must be large than minimumInitialVcPayment /// @param name is the virtual chain name /// @param amount is the amount paid for the virtual chain initial subscription /// @param isCertified indicates the virtual is run by the certified committee /// @param deploymentSubset indicates the code deployment subset the virtual chain uses such as main or canary function createVC(string calldata name, uint256 amount, bool isCertified, string calldata deploymentSubset) external { require(amount > 0, "must include funds"); ISubscriptions subs = ISubscriptions(getSubscriptionsContract()); require(erc20.transferFrom(msg.sender, address(this), amount), "failed to transfer subscription fees"); require(erc20.approve(address(subs), amount), "failed to transfer subscription fees"); subs.createVC(name, tier, monthlyRate, amount, msg.sender, isCertified, deploymentSubset); } /// Extends the subscription of an existing virtual chain. /// @dev may be called by anyone, not only the virtual chain owner /// @dev assumes that the amount has been approved by the msg.sender prior to calling the function /// @param vcId is the virtual chain ID /// @param amount is the amount paid for the virtual chain subscription extension function extendSubscription(uint256 vcId, uint256 amount) external { require(amount > 0, "must include funds"); ISubscriptions subs = ISubscriptions(getSubscriptionsContract()); require(erc20.transferFrom(msg.sender, address(this), amount), "failed to transfer subscription fees from vc payer to subscriber"); require(erc20.approve(address(subs), amount), "failed to approve subscription fees to subscriptions by subscriber"); subs.extendSubscription(vcId, amount, tier, monthlyRate, msg.sender); } }
Creates a new virtual chain the virtual chain tier and rate are determined by the contract the contract calls the subscription contract that stores the virtual chain data and allocates a virtual chain ID the msg.sender that created the virtual chain is set as the initial virtual chain owner the initial amount paid for the virtual chain must be large than minimumInitialVcPayment name is the virtual chain name amount is the amount paid for the virtual chain initial subscription isCertified indicates the virtual is run by the certified committee deploymentSubset indicates the code deployment subset the virtual chain uses such as main or canary
function createVC(string calldata name, uint256 amount, bool isCertified, string calldata deploymentSubset) external { require(amount > 0, "must include funds"); ISubscriptions subs = ISubscriptions(getSubscriptionsContract()); require(erc20.transferFrom(msg.sender, address(this), amount), "failed to transfer subscription fees"); require(erc20.approve(address(subs), amount), "failed to transfer subscription fees"); subs.createVC(name, tier, monthlyRate, amount, msg.sender, isCertified, deploymentSubset); }
173,692
pragma solidity 0.5.17; import "./CErc20Immutable.sol"; import "./CEther.sol"; import "./ErrorReporter.sol"; import "./EIP20Interface.sol"; import "./Strings.sol"; import "./TriggerInterface.sol"; /** * @notice Interface so ProtectionMarketFactory can use the same admin as the Comptroller */ interface ComptrollerAdmin { function admin() external view returns (address); } /** * @notice Factory contract for deploying protection markets * @dev The functionality of cEtherFactory and cErc20Factory lives in separate contracts, instead of directly in * this contract, since including them here would put this contract over the size limit */ contract ProtectionMarketFactory is ProtectionMarketFactoryErrorReporter { /// @notice Address of the comptroller ComptrollerInterface public comptroller; /// @notice Address of the CEtherFactory contract CEtherFactory public cEtherFactory; /// @notice Address of the CErc20Factory contract CErc20Factory public cErc20Factory; /// @notice Mapping of underlying to last-used index for protection token naming mapping(address => uint256) public tokenIndices; /// @notice Default InterestRateModel assigned to protection markets at deployment InterestRateModel public defaultInterestRateModel; /// @notice Special address used to represent ETH address internal constant ethUnderlyingAddress = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice Number of decimals used for protection market cToken when deployed uint8 internal constant decimals = 8; /// @notice Prefix to prepend to protection token symbols string internal constant tokenSymbolPrefix = "Cozy"; /// @notice Separator used in protection token symbols string internal constant tokenSymbolSeparator = "-"; /// @notice Indicator that this is ProtectionMarketFactory contract (for inspection) bool public constant isProtectionMarketFactory = true; /// @notice Emitted when protection market default interest rate model is changed by admin event NewDefaultInterestRateModel(InterestRateModel oldModel, InterestRateModel newModel); /** * @param cEtherFactory_ Address of the CEtherFactory contract * @param cErc20Factory_ Address of the CErc20Factory contract * @param comptroller_ Address of the system's comptroller * @param defaultInterestRateModel_ Address of the default interest rate model to use for new markets */ constructor( CEtherFactory cEtherFactory_, CErc20Factory cErc20Factory_, ComptrollerInterface comptroller_, InterestRateModel defaultInterestRateModel_ ) public { cEtherFactory = cEtherFactory_; cErc20Factory = cErc20Factory_; comptroller = comptroller_; require(_setDefaultInterestRateModel(defaultInterestRateModel_) == 0, "Set interest rate model failed"); } /** * @notice Deploy a new protection market * @dev We could use the Comptroller address in storage instead of requiring it as an input, but passing it as an * input makes this contract more flexible, and also saves some gas since address(this) is much cheaper than SLOAD * @param _underlying The address of the underlying asset * @param _comptroller Address of the system's comptroller * @param _admin Address of the administrator of this token * @param _trigger Address of the trigger contract * @param interestRateModel_ Address of the interest rate model to use, or zero address to use the default */ function deployProtectionMarket( address _underlying, ComptrollerInterface _comptroller, address payable _admin, TriggerInterface _trigger, address interestRateModel_ ) external returns (address) { require(msg.sender == address(_comptroller), "Caller not authorized"); // Get initial token symbol, token name, and initial exchange rate (string memory symbol, string memory name) = createTokenSymbolAndName(_trigger, _underlying); uint256 initialExchangeRateMantissa; { // Scope to avoid stack too deep errors uint256 underlyingDecimals = _underlying == ethUnderlyingAddress ? 18 : EIP20Interface(_underlying).decimals(); uint256 scale = 18 + underlyingDecimals - decimals; initialExchangeRateMantissa = 2 * 10**(scale - 2); // (scale - 2) so initial exchange rate is equivalent to 0.02 } // Deploy market if (_underlying == ethUnderlyingAddress) { return cEtherFactory.deployCEther( _comptroller, getInterestRateModel(interestRateModel_), // inline helper method to avoid stack too deep errors initialExchangeRateMantissa, name, symbol, decimals, _admin, address(_trigger) ); } else { return cErc20Factory.deployCErc20( _underlying, _comptroller, getInterestRateModel(interestRateModel_), // inline helper method to avoid stack too deep errors initialExchangeRateMantissa, name, symbol, decimals, _admin, address(_trigger) ); } } /** * @notice Returns the default interest rate model if none was provided * @param _interestRateModel Provided interest rate model */ function getInterestRateModel(address _interestRateModel) internal returns (InterestRateModel) { return _interestRateModel == address(0) ? defaultInterestRateModel : InterestRateModel(_interestRateModel); } /** * @notice Derive a cToken name and symbol based on the trigger, underlying, and previously deployed markets * @dev Used internally in the factory method for creating protection markets * @param _trigger The address of the trigger that will be associated with this market * @param _underlying The address of the underlying asset used for this cToken * @return (symbol, name) The symbol and name for the new cToken, respectively */ function createTokenSymbolAndName(TriggerInterface _trigger, address _underlying) internal returns (string memory symbol, string memory name) { // Generate string for index postfix uint256 nextIndex = tokenIndices[_underlying] + 1; string memory indexString = Strings.toString(nextIndex); // Remember that this token index has been used tokenIndices[_underlying] = nextIndex; // Get symbol for underlying asset string memory underlyingSymbol; if (_underlying == ethUnderlyingAddress) { underlyingSymbol = "ETH"; } else { EIP20Interface underlyingToken = EIP20Interface(_underlying); underlyingSymbol = underlyingToken.symbol(); } // Generate token symbol, example "Cozy-DAI-1" string memory tokenSymbol = string( abi.encodePacked(tokenSymbolPrefix, tokenSymbolSeparator, underlyingSymbol, tokenSymbolSeparator, indexString) ); // Generate token name, example "Cozy-DAI-1-Some Protocol Failure" string memory tokenName = string(abi.encodePacked(tokenSymbol, tokenSymbolSeparator, _trigger.name())); return (tokenSymbol, tokenName); } /** * @notice Sets defaultInterestRateModel * @dev Admin function to set defaultInterestRateModel, must be called by Comptroller admin * @param _newModel New defaultInterestRateModel * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setDefaultInterestRateModel(InterestRateModel _newModel) public returns (uint256) { // Check caller is the Comptroller admin if (msg.sender != ComptrollerAdmin(address(comptroller)).admin()) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_DEFAULT_INTEREST_RATE_MODEL_OWNER_CHECK); } // Sanity check the new contract if (!_newModel.isInterestRateModel()) { return fail(Error.INTEREST_RATE_MODEL_ERROR, FailureInfo.SET_DEFAULT_INTEREST_RATE_MODEL_VALIDITY_CHECK); } // Emit event with old model, new model emit NewDefaultInterestRateModel(defaultInterestRateModel, _newModel); // Set default model to the new model defaultInterestRateModel = _newModel; return uint256(Error.NO_ERROR); } } /** * @notice Simple contract with one method to deploy a new CEther contract with the specified parameters */ contract CEtherFactory { /** * @notice Deploy a new CEther money market or protection market * @param comptroller The address of the Comptroller * @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 trigger Trigger contract address for protection markets, or the zero address for money markets */ function deployCEther( ComptrollerInterface comptroller, InterestRateModel interestRateModel, uint256 initialExchangeRateMantissa, string calldata name, string calldata symbol, uint8 decimals, address payable admin, address trigger ) external returns (address) { CEther cToken = new CEther(comptroller, interestRateModel, initialExchangeRateMantissa, name, symbol, decimals, admin, trigger); return address(cToken); } } /** * @notice Simple contract with one method to deploy a new CErc20 contract with the specified parameters */ contract CErc20Factory { /** * @notice Construct a new CErc20 money market or protection market * @param underlying The address of the underlying asset * @param comptroller The address of the Comptroller * @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 trigger Trigger contract address for protection markets, or the zero address for money markets */ function deployCErc20( address underlying, ComptrollerInterface comptroller, InterestRateModel interestRateModel, uint256 initialExchangeRateMantissa, string calldata name, string calldata symbol, uint8 decimals, address payable admin, address trigger ) external returns (address) { CErc20Immutable cToken = new CErc20Immutable( underlying, comptroller, interestRateModel, initialExchangeRateMantissa, name, symbol, decimals, admin, trigger ); return address(cToken); } } pragma solidity 0.5.17; import "./CErc20.sol"; /** * @notice CTokens which wrap an EIP-20 underlying and are immutable */ contract CErc20Immutable is CErc20 { /** * @notice Construct a new money market or protection market * @param underlying_ The address of the underlying asset * @param comptroller_ The address of the Comptroller * @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 trigger_ Trigger contract address for protection markets, or the zero address for money markets */ constructor( address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint256 initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address payable admin_, address trigger_ ) public { // Creator of the contract is admin during initialization admin = msg.sender; // Initialize the market initialize( underlying_, comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_, trigger_ ); // Set the proper admin now that initialization is done admin = admin_; } } pragma solidity 0.5.17; import "./CToken.sol"; /** * @notice CToken which wraps Ether */ contract CEther is CToken { /** * @notice Construct a new CEther money market or protection market * @param comptroller_ The address of the Comptroller * @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 trigger_ Trigger contract address for protection markets, or the zero address for money markets */ constructor( ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint256 initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address payable admin_, address trigger_ ) public { // Creator of the contract is admin during initialization admin = msg.sender; initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_, trigger_); // Set the proper admin now that initialization is done admin = admin_; // Set the underlying to the special address used to indicate ETH underlying = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } /*** User Interface ***/ /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Reverts upon any failure */ function mint() external payable { (uint256 err, ) = mintInternal(msg.value); requireNoError(err, "mint failed"); } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint256 redeemTokens) external returns (uint256) { return redeemInternal(redeemTokens); } /** * @notice Sender redeems cTokens 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(uint256 redeemAmount) external returns (uint256) { return redeemUnderlyingInternal(redeemAmount); } /** * @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(uint256 borrowAmount) external returns (uint256) { return borrowInternal(borrowAmount); } /** * @notice Sender repays their own borrow * @dev Reverts upon any failure */ function repayBorrow() external payable { (uint256 err, ) = repayBorrowInternal(msg.value); requireNoError(err, "repayBorrow failed"); } /** * @notice Sender repays a borrow belonging to borrower * @dev Reverts upon any failure * @param borrower the account with the debt being payed off */ function repayBorrowBehalf(address borrower) external payable { (uint256 err, ) = repayBorrowBehalfInternal(borrower, msg.value); requireNoError(err, "repayBorrowBehalf failed"); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @dev Reverts upon any failure * @param borrower The borrower of this cToken to be liquidated * @param cTokenCollateral The market in which to seize collateral from the borrower */ function liquidateBorrow(address borrower, CToken cTokenCollateral) external payable { (uint256 err, ) = liquidateBorrowInternal(borrower, msg.value, cTokenCollateral); requireNoError(err, "liquidateBorrow failed"); } /** * @notice Send Ether to CEther to mint */ function() external payable { (uint256 err, ) = mintInternal(msg.value); requireNoError(err, "mint failed"); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of Ether, before this message * @dev This excludes the value of the current message, if any * @return The quantity of Ether owned by this contract */ function getCashPrior() internal view returns (uint256) { (MathError err, uint256 startingBalance) = subUInt(address(this).balance, msg.value); require(err == MathError.NO_ERROR); return startingBalance; } /** * @notice Perform the actual transfer in, which is a no-op * @param from Address sending the Ether * @param amount Amount of Ether being sent * @return The actual amount of Ether transferred */ function doTransferIn(address from, uint256 amount) internal returns (uint256) { // Sanity checks require(msg.sender == from, "sender mismatch"); require(msg.value == amount, "value mismatch"); return amount; } function doTransferOut(address payable to, uint256 amount) internal { /* Send the Ether, with minimal gas and revert on failure */ to.transfer(amount); } function requireNoError(uint256 errCode, string memory message) internal pure { if (errCode == uint256(Error.NO_ERROR)) { return; } bytes memory fullMessage = new bytes(bytes(message).length + 5); uint256 i; for (i = 0; i < bytes(message).length; i++) { fullMessage[i] = bytes(message)[i]; } fullMessage[i + 0] = bytes1(uint8(32)); fullMessage[i + 1] = bytes1(uint8(40)); fullMessage[i + 2] = bytes1(uint8(48 + (errCode / 10))); fullMessage[i + 3] = bytes1(uint8(48 + (errCode % 10))); fullMessage[i + 4] = bytes1(uint8(41)); require(errCode == uint256(Error.NO_ERROR), string(fullMessage)); } } pragma solidity 0.5.17; contract ComptrollerErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, COMPTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_ENTERED, // no longer possible MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY, INVALID_TRIGGER, PROTECTION_MARKET_FACTORY_ERROR } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, SET_CLOSE_FACTOR_OWNER_CHECK, SET_CLOSE_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_NO_EXISTS, SET_COLLATERAL_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_WITHOUT_PRICE, SET_IMPLEMENTATION_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_MAX_ASSETS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK, SET_TRIGGER_CHECK, SET_PROTECTION_WITH_INVALID_UNDERLYING, SET_PROTECTION_UNDERLYING_WITHOUT_PRICE, SET_PROTECTION_MARKET_FACTORY_OWNER_CHECK, SET_PROTECTION_MARKET_FACTORY_VALIDITY_CHECK, SET_RESERVE_GUARDIAN_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(uint256 error, uint256 info, uint256 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 (uint256) { emit Failure(uint256(err), uint256(info), 0); return uint256(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque( Error err, FailureInfo info, uint256 opaqueError ) internal returns (uint256) { emit Failure(uint256(err), uint256(info), opaqueError); return uint256(err); } } contract TokenErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, BAD_INPUT, COMPTROLLER_REJECTION, COMPTROLLER_CALCULATION_ERROR, INTEREST_RATE_MODEL_ERROR, INVALID_ACCOUNT_PAIR, INVALID_CLOSE_AMOUNT_REQUESTED, INVALID_COLLATERAL_FACTOR, MATH_ERROR, MARKET_NOT_FRESH, MARKET_NOT_LISTED, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_IN_FAILED, TOKEN_TRANSFER_OUT_FAILED, INVALID_GUARDIAN, MARKET_TRIGGERED } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_ACCRUE_INTEREST_FAILED, BORROW_CASH_NOT_AVAILABLE, BORROW_FRESHNESS_CHECK, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, BORROW_MARKET_NOT_LISTED, BORROW_COMPTROLLER_REJECTION, LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, LIQUIDATE_COMPTROLLER_REJECTION, LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, LIQUIDATE_FRESHNESS_CHECK, LIQUIDATE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_REPAY_BORROW_FRESH_FAILED, LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_SEIZE_TOO_MUCH, MINT_ACCRUE_INTEREST_FAILED, MINT_COMPTROLLER_REJECTION, MINT_EXCHANGE_CALCULATION_FAILED, MINT_EXCHANGE_RATE_READ_FAILED, MINT_FRESHNESS_CHECK, MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, MINT_TRANSFER_IN_FAILED, MINT_TRANSFER_IN_NOT_POSSIBLE, REDEEM_ACCRUE_INTEREST_FAILED, REDEEM_COMPTROLLER_REJECTION, REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, REDEEM_EXCHANGE_RATE_READ_FAILED, REDEEM_FRESHNESS_CHECK, REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, REDEEM_TRANSFER_OUT_NOT_POSSIBLE, REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, REDUCE_RESERVES_ADMIN_CHECK, REDUCE_RESERVES_CASH_NOT_AVAILABLE, REDUCE_RESERVES_FRESH_CHECK, REDUCE_RESERVES_VALIDATION, REPAY_BEHALF_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_COMPTROLLER_REJECTION, REPAY_BORROW_FRESHNESS_CHECK, REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_VALIDATION, SET_COMPTROLLER_OWNER_CHECK, SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, SET_INTEREST_RATE_MODEL_FRESH_CHECK, SET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_MAX_ASSETS_OWNER_CHECK, SET_ORACLE_MARKET_NOT_LISTED, SET_PENDING_ADMIN_OWNER_CHECK, SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, SET_RESERVE_FACTOR_ADMIN_CHECK, SET_RESERVE_FACTOR_FRESH_CHECK, SET_RESERVE_FACTOR_BOUNDS_CHECK, TRANSFER_COMPTROLLER_REJECTION, TRANSFER_NOT_ALLOWED, TRANSFER_NOT_ENOUGH, TRANSFER_TOO_MUCH, ADD_RESERVES_ACCRUE_INTEREST_FAILED, ADD_RESERVES_FRESH_CHECK, ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE, REDUCE_RESERVES_GUARDIAN_NOT_SET, TRIGGER_ACTIVATED_BEFORE_REDEEM_OR_BORROW } /** * @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(uint256 error, uint256 info, uint256 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 (uint256) { emit Failure(uint256(err), uint256(info), 0); return uint256(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque( Error err, FailureInfo info, uint256 opaqueError ) internal returns (uint256) { emit Failure(uint256(err), uint256(info), opaqueError); return uint256(err); } } contract ProtectionMarketFactoryErrorReporter { enum Error {NO_ERROR, UNAUTHORIZED, INTEREST_RATE_MODEL_ERROR} enum FailureInfo {SET_DEFAULT_INTEREST_RATE_MODEL_OWNER_CHECK, SET_DEFAULT_INTEREST_RATE_MODEL_VALIDITY_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(uint256 error, uint256 info, uint256 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 (uint256) { emit Failure(uint256(err), uint256(info), 0); return uint256(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque( Error err, FailureInfo info, uint256 opaqueError ) internal returns (uint256) { emit Failure(uint256(err), uint256(info), opaqueError); return uint256(err); } } contract OracleErrorReporter { enum Error {NO_ERROR, UNAUTHORIZED} enum FailureInfo {ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ADD_OR_UPDATE_ORACLES_OWNER_CHECK, SET_PENDING_ADMIN_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(uint256 error, uint256 info, uint256 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 (uint256) { emit Failure(uint256(err), uint256(info), 0); return uint256(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque( Error err, FailureInfo info, uint256 opaqueError ) internal returns (uint256) { emit Failure(uint256(err), uint256(info), opaqueError); return uint256(err); } } pragma solidity 0.5.17; /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /** * @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 success); /** * @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 success); /** * @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 success); /** * @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 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } // SPDX-License-Identifier: MIT pragma solidity 0.5.17; /** * @notice String operations * @dev Sourced from the OpenZeppelin implementation here: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/c789941d76dd713333bdeafe5b4484f6d9543c4e/contracts/utils/Strings.sol */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` 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); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + (temp % 10))); temp /= 10; } return string(buffer); } } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.5.17; /** * @notice Interface for creating or interacting with a Trigger contract * @dev All trigger contracts created must conform to this interface */ contract TriggerInterface { /// @notice Trigger name function name() external view returns (string memory); /// @notice Trigger symbol function symbol() external view returns (string memory); /// @notice Trigger description function description() external view returns (string memory); /// @notice Returns array of IDs, where each ID corresponds to a platform covered by this trigger /// @dev See documentation for mapping of ID number to platform function getPlatformIds() external view returns (uint256[] memory); /// @notice Returns address of recipient who receives subsidies for creating the trigger and associated protection market function recipient() external view returns (address); /// @notice Returns true if trigger condition has been met function isTriggered() external view returns (bool); /// @notice Checks trigger condition, sets isTriggered flag to true if condition is met, and returns the new trigger status function checkAndToggleTrigger() external returns (bool); } pragma solidity 0.5.17; import "./CToken.sol"; /** * @notice CTokens which wrap an EIP-20 underlying */ contract CErc20 is CToken, CErc20Interface { /** * @notice Initialize a new money market or protection market * @param underlying_ The address of the underlying asset * @param comptroller_ The address of the Comptroller * @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 trigger_ Trigger contract address for protection markets, or the zero address for money markets */ function initialize( address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint256 initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address trigger_ ) public { // CToken initialize does the bulk of the work super.initialize( comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_, trigger_ ); // Set underlying and sanity check it underlying = underlying_; EIP20Interface(underlying).totalSupply(); } /*** User Interface ***/ /** * @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(uint256 mintAmount) external returns (uint256) { (uint256 err, ) = mintInternal(mintAmount); return err; } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint256 redeemTokens) external returns (uint256) { return redeemInternal(redeemTokens); } /** * @notice Sender redeems cTokens 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(uint256 redeemAmount) external returns (uint256) { return redeemUnderlyingInternal(redeemAmount); } /** * @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(uint256 borrowAmount) external returns (uint256) { return borrowInternal(borrowAmount); } /** * @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(uint256 repayAmount) external returns (uint256) { (uint256 err, ) = repayBorrowInternal(repayAmount); return err; } /** * @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, uint256 repayAmount) external returns (uint256) { (uint256 err, ) = repayBorrowBehalfInternal(borrower, repayAmount); return err; } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param repayAmount The amount of the underlying borrowed asset to repay * @param cTokenCollateral The market in which to seize collateral from the borrower * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow( address borrower, uint256 repayAmount, CTokenInterface cTokenCollateral ) external returns (uint256) { (uint256 err, ) = liquidateBorrowInternal(borrower, repayAmount, cTokenCollateral); return err; } /** * @notice The sender adds to reserves. * @param addAmount The amount fo underlying token to add as reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReserves(uint256 addAmount) external returns (uint256) { return _addReservesInternal(addAmount); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying tokens owned by this contract */ function getCashPrior() internal view returns (uint256) { EIP20Interface token = EIP20Interface(underlying); return token.balanceOf(address(this)); } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case. * This will revert due to insufficient balance or insufficient allowance. * This function returns the actual amount received, * which may be less than `amount` if there is a fee attached to the transfer. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn(address from, uint256 amount) internal returns (uint256) { EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); uint256 balanceBefore = EIP20Interface(underlying).balanceOf(address(this)); token.transferFrom(from, address(this), amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a compliant ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_IN_FAILED"); // Calculate the amount that was *actually* transferred uint256 balanceAfter = EIP20Interface(underlying).balanceOf(address(this)); require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW"); return balanceAfter - balanceBefore; // underflow already checked above, just subtract } /** * @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut(address payable to, uint256 amount) internal { EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); token.transfer(to, amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a compliant ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_OUT_FAILED"); } } pragma solidity 0.5.17; import "./ComptrollerInterface.sol"; import "./CTokenInterfaces.sol"; import "./TriggerInterface.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./EIP20Interface.sol"; import "./EIP20NonStandardInterface.sol"; import "./InterestRateModel.sol"; /** * @notice Abstract base for CTokens */ contract CToken is CTokenInterface, Exponential, TokenErrorReporter { /// @notice The EIP-712 typehash for the contract's domain (computed inline later to reduce contract size) /// @dev Not exposing DOMAIN_SEPARATOR means this implementation not conform to EIP-2612 // bytes32 public constant DOMAIN_SEPARATOR = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the ballot struct used by the contract (inlined later to reduce contract size) // bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); // = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9 /// @notice Nonce mapping for permit support mapping(address => uint256) public nonces; /** * @notice Initialize a new money market or protection market * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ EIP-20 name of this token * @param symbol_ EIP-20 symbol of this token * @param decimals_ EIP-20 decimal precision of this token * @param trigger_ Trigger contract address for protection markets, or the zero address for money markets */ function initialize( ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint256 initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address trigger_ ) public { require(msg.sender == admin, "only admin may initialize market"); require(accrualBlockNumber == 0 && borrowIndex == 0, "market already initialized"); // Set initial exchange rate initialExchangeRateMantissa = initialExchangeRateMantissa_; require(initialExchangeRateMantissa > 0, "initial exchange rate must be above zero"); // Set the comptroller // Ensure invoke comptroller.isComptroller() returns true require(comptroller_.isComptroller(), "marker method returned false"); // Set market's comptroller to newComptroller emit NewComptroller(comptroller, comptroller_); comptroller = comptroller_; // Initialize block number and borrow index (block number mocks depend on comptroller being set) accrualBlockNumber = getBlockNumber(); borrowIndex = mantissaOne; // Set the interest rate model (depends on block number / borrow index) uint256 err = _setInterestRateModelFresh(interestRateModel_); require(err == uint256(Error.NO_ERROR), "setting interest rate model failed"); name = name_; symbol = symbol_; decimals = decimals_; // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund) _notEntered = true; // Set trigger contract address and market type trigger = trigger_; emit TriggerSet(false); } /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally * @param spender The address of the account performing the transfer * @param src The address of the source account * @param dst The address of the destination account * @param tokens The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferTokens( address spender, address src, address dst, uint256 tokens ) internal returns (uint256) { /* Fail if transfer not allowed */ uint256 allowed = comptroller.transferAllowed(address(this), src, dst, tokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed); } /* Do not allow self-transfers */ if (src == dst) { return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED); } /* Get the allowance, infinite for the account owner */ uint256 startingAllowance = 0; if (spender == src) { startingAllowance = uint256(-1); } else { startingAllowance = transferAllowances[src][spender]; } /* Do the calculations, checking for {under,over}flow */ MathError mathErr; uint256 allowanceNew; uint256 srcTokensNew; uint256 dstTokensNew; (mathErr, allowanceNew) = subUInt(startingAllowance, tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED); } (mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH); } (mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) accountTokens[src] = srcTokensNew; accountTokens[dst] = dstTokensNew; /* Eat some of the allowance (if necessary) */ if (startingAllowance != uint256(-1)) { transferAllowances[src][spender] = allowanceNew; } /* We emit a Transfer event */ emit Transfer(src, dst, tokens); return uint256(Error.NO_ERROR); } /** * @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 nonReentrant returns (bool) { return transferTokens(msg.sender, msg.sender, dst, amount) == uint256(Error.NO_ERROR); } /** * @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 nonReentrant returns (bool) { return transferTokens(msg.sender, src, dst, amount) == uint256(Error.NO_ERROR); } /** * @notice Approve `spender` to transfer up to `amount` from `owner` (base method) * @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 owner The address of the account that owns the tokens * @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 owner, address spender, uint256 amount ) private returns (bool) { transferAllowances[owner][spender] = amount; emit Approval(owner, spender, amount); return true; } /** * @notice Approve `spender` to transfer up to `amount` from `msg.sender` * @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) { return _approve(msg.sender, spender, amount); } /** * @notice Permit - approve a 'spender' to transfer up to 'amount' from owner if signatore denotes owner * @dev This will overwrite the approval amount for `spender` should the signature indicate the proper owner */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require(deadline >= block.timestamp, "Permit expired"); // Original address recovery and digest creation code // bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_SEPARATOR, keccak256(bytes(name)), getChainId(), address(this))); // bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)); // bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); // address recoveredAddress = ecrecover(digest, v, r, s); // Digest creation and address recovery code with everything in-line and permit hash pre-hashed to reduce code size address recoveredAddress = ecrecover( keccak256( abi.encodePacked( "\x19\x01", keccak256( abi.encode( keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), getChainId(), address(this) ) ), keccak256( abi.encode( 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9, owner, spender, value, nonces[owner]++, deadline ) ) ) ), v, r, s ); require(recoveredAddress != address(0) && recoveredAddress == owner, "Invalid signature"); _approve(owner, spender, value); } /** * @notice Get the chain ID (uses assembly) * @return The chain ID */ function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } /** * @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) { return transferAllowances[owner][spender]; } /** * @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) { return accountTokens[owner]; } /** * @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 (uint256) { Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()}); (MathError mErr, uint256 balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]); require(mErr == MathError.NO_ERROR, "could not calculate balance"); return balance; } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by comptroller 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 ( uint256, uint256, uint256, uint256 ) { uint256 cTokenBalance = accountTokens[account]; uint256 borrowBalance; uint256 exchangeRateMantissa; MathError mErr; (mErr, borrowBalance) = borrowBalanceStoredInternal(account); if (mErr != MathError.NO_ERROR) { return (uint256(Error.MATH_ERROR), 0, 0, 0); } (mErr, exchangeRateMantissa) = exchangeRateStoredInternal(); if (mErr != MathError.NO_ERROR) { return (uint256(Error.MATH_ERROR), 0, 0, 0); } return (uint256(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa); } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint256) { return block.number; } /** * @notice Returns the current per-block borrow interest rate for this cToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint256) { if (isTriggered) { return 0; } return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves); } /** * @notice Returns the current per-block supply interest rate for this cToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint256) { if (isTriggered) { return 0; } return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external nonReentrant returns (uint256) { require(accrueInterest() == uint256(Error.NO_ERROR), "accrue interest failed"); return totalBorrows; } /** * @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 nonReentrant returns (uint256) { require(accrueInterest() == uint256(Error.NO_ERROR), "accrue interest failed"); return borrowBalanceStored(account); } /** * @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 (uint256) { (MathError err, uint256 result) = borrowBalanceStoredInternal(account); require(err == MathError.NO_ERROR, "borrowBalanceStoredInternal failed"); return result; } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return (error code, the calculated balance or 0 if error code is non-zero) */ function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint256) { if (isTriggered) { return (MathError.NO_ERROR, 0); } /* Note: we do not assert that the market is up to date */ MathError mathErr; uint256 principalTimesIndex; uint256 result; /* Get borrowBalance and borrowIndex */ BorrowSnapshot storage borrowSnapshot = accountBorrows[account]; /* If borrowBalance = 0 then borrowIndex is likely also 0. * Rather than failing the calculation with a division by 0, we immediately return 0 in this case. */ if (borrowSnapshot.principal == 0) { return (MathError.NO_ERROR, 0); } /* Calculate new borrow balance using the interest index: * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex */ (mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, result); } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public nonReentrant returns (uint256) { require(accrueInterest() == uint256(Error.NO_ERROR), "accrue interest failed"); return exchangeRateStored(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint256) { (MathError err, uint256 result) = exchangeRateStoredInternal(); require(err == MathError.NO_ERROR, "exchangeRateStoredInternal failed"); return result; } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return (error code, calculated exchange rate scaled by 1e18) */ function exchangeRateStoredInternal() internal view returns (MathError, uint256) { uint256 _totalSupply = totalSupply; if (_totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return (MathError.NO_ERROR, initialExchangeRateMantissa); } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint256 totalCash = getCashPrior(); uint256 cashPlusBorrowsMinusReserves; Exp memory exchangeRate; MathError mathErr; (mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, exchangeRate.mantissa); } } /** * @notice Get cash balance of this cToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint256) { return getCashPrior(); } /** * @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 (uint256) { /* Short-circuit if trigger event occured */ if (isTriggered) { accrualBlockNumber = getBlockNumber(); // required to allow redemptions return uint256(Error.NO_ERROR); } /* Remember the initial block number */ uint256 currentBlockNumber = getBlockNumber(); uint256 accrualBlockNumberPrior = accrualBlockNumber; /* Short-circuit accumulating 0 interest */ if (accrualBlockNumberPrior == currentBlockNumber) { return uint256(Error.NO_ERROR); } /* Read the previous values out of storage */ uint256 cashPrior = getCashPrior(); uint256 borrowsPrior = totalBorrows; uint256 reservesPrior = totalReserves; uint256 borrowIndexPrior = borrowIndex; /* Calculate the current borrow interest rate */ uint256 borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate too high"); /* Calculate the number of blocks elapsed since the last accrual */ (MathError mathErr, uint256 blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior); require(mathErr == MathError.NO_ERROR, "could not calculate block delta"); /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ Exp memory simpleInterestFactor; uint256 interestAccumulated; uint256 totalBorrowsNew; uint256 totalReservesNew; uint256 borrowIndexNew; (mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta); if (mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint256(mathErr) ); } (mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint256(mathErr) ); } (mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint256(mathErr) ); } (mathErr, totalReservesNew) = mulScalarTruncateAddUInt( Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior ); if (mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint256(mathErr) ); } (mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint256(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualBlockNumber = currentBlockNumber; borrowIndex = borrowIndexNew; totalBorrows = totalBorrowsNew; totalReserves = totalReservesNew; /* We emit an AccrueInterest event */ emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew); return uint256(Error.NO_ERROR); } /** * @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, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintInternal(uint256 mintAmount) internal nonReentrant returns (uint256, uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0); } // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to return mintFresh(msg.sender, mintAmount); } struct MintLocalVars { Error err; MathError mathErr; uint256 exchangeRateMantissa; uint256 mintTokens; uint256 totalSupplyNew; uint256 accountTokensNew; uint256 actualMintAmount; } /** * @notice User supplies assets into the market and receives cTokens in exchange * @dev Assumes interest has already been accrued up to the current block * @param minter The address of the account which is supplying the assets * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintFresh(address minter, uint256 mintAmount) internal whenNotTriggered returns (uint256, uint256) { /* Fail if mint not allowed */ uint256 allowed = comptroller.mintAllowed(address(this), minter, mintAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0); } MintLocalVars memory vars; (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint256(vars.mathErr)), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call `doTransferIn` for the minter and the mintAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * `doTransferIn` reverts if anything goes wrong, since we can't be sure if * side-effects occurred. The function returns the amount actually transferred, * in case of a fee. On success, the cToken holds an additional `actualMintAmount` * of cash. */ vars.actualMintAmount = doTransferIn(minter, mintAmount); /* * We get the current exchange rate and calculate the number of cTokens to be minted: * mintTokens = actualMintAmount / exchangeRate */ (vars.mathErr, vars.mintTokens) = divScalarByExpTruncate( vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}) ); require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED"); /* * We calculate the new total supply of cTokens and minter token balance, checking for overflow: * totalSupplyNew = totalSupply + mintTokens * accountTokensNew = accountTokens[minter] + mintTokens */ (vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED"); (vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED"); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[minter] = vars.accountTokensNew; /* We emit a Mint event, and a Transfer event */ emit Mint(minter, vars.actualMintAmount, vars.mintTokens); emit Transfer(address(this), minter, vars.mintTokens); return (uint256(Error.NO_ERROR), vars.actualMintAmount); } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemInternal(uint256 redeemTokens) internal nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, redeemTokens, 0); } /** * @notice Sender redeems cTokens 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 receive from redeeming cTokens * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlyingInternal(uint256 redeemAmount) internal nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, 0, redeemAmount); } struct RedeemLocalVars { Error err; MathError mathErr; uint256 exchangeRateMantissa; uint256 redeemTokens; uint256 redeemAmount; uint256 totalSupplyNew; uint256 accountTokensNew; } /** * @notice User redeems cTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block * @param redeemer The address of the account which is redeeming the tokens * @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemFresh( address payable redeemer, uint256 redeemTokensIn, uint256 redeemAmountIn ) internal returns (uint256) { // If trigger has not been toggled yet, check the condition, and if toggled exit this function and return failure // code indicating this. We have the `!isTriggered` check because without this suppliers would be blocked from // redeeming funds after a trigger occurs. In other words, we allow redeems in transactions before the trigger // was toggled, and in transactions after the trigger was toggled, but not if the trigger was just toggled in // this transaction if (!isTriggered && checkAndToggleTriggerInternal()) { return fail(Error.MARKET_TRIGGERED, FailureInfo.TRIGGER_ACTIVATED_BEFORE_REDEEM_OR_BORROW); } require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero"); RedeemLocalVars memory vars; /* exchangeRate = invoke Exchange Rate Stored() */ (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint256(vars.mathErr)); } /* If redeemTokensIn > 0: */ if (redeemTokensIn > 0) { /* * We calculate the exchange rate and the amount of underlying to be redeemed: * redeemTokens = redeemTokensIn * redeemAmount = redeemTokensIn x exchangeRateCurrent */ vars.redeemTokens = redeemTokensIn; (vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint256(vars.mathErr)); } } else { /* * We get the current exchange rate and calculate the amount to be redeemed: * redeemTokens = redeemAmountIn / exchangeRate * redeemAmount = redeemAmountIn */ (vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate( redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}) ); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint256(vars.mathErr)); } vars.redeemAmount = redeemAmountIn; } /* Fail if redeem not allowed */ uint256 allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK); } /* * We calculate the new total supply and redeemer balance, checking for underflow: * totalSupplyNew = totalSupply - redeemTokens * accountTokensNew = accountTokens[redeemer] - redeemTokens */ (vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint256(vars.mathErr)); } (vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint256(vars.mathErr)); } /* Fail gracefully if protocol has insufficient cash */ if (getCashPrior() < vars.redeemAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken has redeemAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(redeemer, vars.redeemAmount); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[redeemer] = vars.accountTokensNew; /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(this), vars.redeemTokens); emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens); /* Require tokens is zero or amount is also zero */ if (vars.redeemTokens == 0 && vars.redeemAmount > 0) { revert("redeemTokens zero"); } return uint256(Error.NO_ERROR); } /** * @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 borrowInternal(uint256 borrowAmount) internal nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED); } // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(msg.sender, borrowAmount); } struct BorrowLocalVars { MathError mathErr; uint256 accountBorrows; uint256 accountBorrowsNew; uint256 totalBorrowsNew; } /** * @notice Users borrow 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 borrowFresh(address payable borrower, uint256 borrowAmount) internal whenNotTriggered returns (uint256) { // Check trigger condition, and if triggered, exit function and return failure code indicating this if (checkAndToggleTriggerInternal()) { return fail(Error.MARKET_TRIGGERED, FailureInfo.TRIGGER_ACTIVATED_BEFORE_REDEEM_OR_BORROW); } /* Fail if borrow not allowed */ uint256 allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK); } /* Fail gracefully if protocol has insufficient underlying cash */ if (getCashPrior() < borrowAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE); } BorrowLocalVars memory vars; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint256(vars.mathErr)); } (vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint256(vars.mathErr) ); } (vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint256(vars.mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken borrowAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(borrower, borrowAmount); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a Borrow event */ emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); return uint256(Error.NO_ERROR); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowInternal(uint256 repayAmount) internal nonReentrant returns (uint256, uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, msg.sender, repayAmount); } /** * @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, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowBehalfInternal(address borrower, uint256 repayAmount) internal nonReentrant returns (uint256, uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, borrower, repayAmount); } struct RepayBorrowLocalVars { Error err; MathError mathErr; uint256 repayAmount; uint256 borrowerIndex; uint256 accountBorrows; uint256 accountBorrowsNew; uint256 totalBorrowsNew; uint256 actualRepayAmount; } /** * @notice Borrows are repaid by another user (possibly the borrower). * @param payer the account paying off the borrow * @param borrower the account with the debt being payed off * @param repayAmount the amount of undelrying tokens being returned * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowFresh( address payer, address borrower, uint256 repayAmount ) internal whenNotTriggered returns (uint256, uint256) { /* Fail if repayBorrow not allowed */ uint256 allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0); } RepayBorrowLocalVars memory vars; /* We remember the original borrowerIndex for verification purposes */ vars.borrowerIndex = accountBorrows[borrower].interestIndex; /* We fetch the amount the borrower owes, with accumulated interest */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return ( failOpaque( Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint256(vars.mathErr) ), 0 ); } /* If repayAmount == -1, repayAmount = accountBorrows */ if (repayAmount == uint256(-1)) { vars.repayAmount = vars.accountBorrows; } else { vars.repayAmount = repayAmount; } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the payer and the repayAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional repayAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount); /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - actualRepayAmount * totalBorrowsNew = totalBorrows - actualRepayAmount */ (vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED"); (vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED"); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a RepayBorrow event */ emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); return (uint256(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice The sender liquidates the borrowers collateral. The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowInternal( address borrower, uint256 repayAmount, CTokenInterface cTokenCollateral ) internal nonReentrant returns (uint256, uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0); } error = cTokenCollateral.accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0); } // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral); } /** * @notice The liquidator liquidates the borrowers collateral. The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param liquidator The address repaying the borrow and seizing collateral * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowFresh( address liquidator, address borrower, uint256 repayAmount, CTokenInterface cTokenCollateral ) internal whenNotTriggered returns (uint256, uint256) { /* Fail if liquidate not allowed */ uint256 allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0); } /* Verify cTokenCollateral market's block number equals current block number */ if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0); } /* Fail if repayAmount = 0 */ if (repayAmount == 0) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0); } /* Fail if repayAmount = -1 */ if (repayAmount == uint256(-1)) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0); } /* Fail if repayBorrow fails */ (uint256 repayBorrowError, uint256 actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount); if (repayBorrowError != uint256(Error.NO_ERROR)) { return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We calculate the number of collateral tokens that will be seized */ (uint256 amountSeizeError, uint256 seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount); require(amountSeizeError == uint256(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED"); /* Revert if borrower collateral token balance < seizeTokens */ require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH"); // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call uint256 seizeError; if (address(cTokenCollateral) == address(this)) { seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens); } else { seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens); } /* Revert if seize tokens fails (since we cannot be sure of side effects) */ require(seizeError == uint256(Error.NO_ERROR), "token seizure failed"); /* We emit a LiquidateBorrow event */ emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens); return (uint256(Error.NO_ERROR), actualRepayAmount); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another cToken during the process of liquidation. * It's absolutely critical to use msg.sender as the borrowed cToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize( address liquidator, address borrower, uint256 seizeTokens ) external nonReentrant returns (uint256) { return seizeInternal(msg.sender, liquidator, borrower, seizeTokens); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken. * It's absolutely critical to use msg.sender as the seizer cToken and not a parameter. * @param seizerToken The contract seizing the collateral (i.e. borrowed cToken) * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seizeInternal( address seizerToken, address liquidator, address borrower, uint256 seizeTokens ) internal returns (uint256) { /* Fail if seize not allowed */ uint256 allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER); } MathError mathErr; uint256 borrowerTokensNew; uint256 liquidatorTokensNew; /* * We calculate the new borrower and liquidator token balances, failing on underflow/overflow: * borrowerTokensNew = accountTokens[borrower] - seizeTokens * liquidatorTokensNew = accountTokens[liquidator] + seizeTokens */ (mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint256(mathErr)); } (mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint256(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accountTokens[borrower] = borrowerTokensNew; accountTokens[liquidator] = liquidatorTokensNew; /* Emit a Transfer event */ emit Transfer(borrower, liquidator, seizeTokens); return uint256(Error.NO_ERROR); } /** * @notice Checks the trigger contract, and if triggered updates the state * @dev Implemented as a wrapper around borrow to avoid reentrancy risks. If this method simply called * `checkAndToggleTriggerInternal`, you have can have a reentrancy risk as follows: * Call `checkAndToggleTriggerInternal` > enter trigger contract > trigger contract tries to borrow funds > * borrow method enters `checkAndToggleTriggerInternal` > trigger contract returns false > borrow succeeds > * trigger contract returns true > debts canceled for a borrow that occured in the triggering transaction * But you cannot do that if you enter `checkAndToggleTriggerInternal` from the borrow method, because the only way * to proceed with a borrow is for the trigger to return false * @return Returns the new trigger status */ function checkAndToggleTrigger() external whenNotTriggered returns (bool) { borrowInternal(0); // this calls `checkAndToggleTriggerInternal` return isTriggered; } /** * @notice Checks the trigger contract, and if triggered updates the state * @return Returns the new trigger status */ function checkAndToggleTriggerInternal() internal returns (bool) { /* Trigger can never be toggled for Money Markets, which have the zero address as the trigger address */ if (trigger == address(0)) return false; /* * Untrusted call, since anyone can deploy a new protection market with any trigger. However, nothing * malicious can occur from reentering here, so a reentrancy guard and the checks-effects-interaction * are not required. The reason nothing malicious can happen is because the reentrancy must come from * the malicious trigger, and if we had a malicious trigger that tried to exploit reentrancy, here are * the options: * 1. Trigger is not toggled: You reenter during the trigger call, you'd call `accrueInterest()` again * and that method does nothing when called twice in the same block. After `trigger.checkAndToggleTriggerInternal()` * finally returns false, things continue as normal * 2. Trigger is toggled: As above, if you reenter during the trigger call, you'd call `accrueInterest()` * again which will do nothing. If you try to borrow or redeem funds, this method will ultimately return true * and prevent borrowing/redeeming (along with the `nonReentrant` modifier in `borrowInternal`). If you try to * supply funds to get more COZY, you'll accrue that COZY for zero blocks and then lose some supplied funds */ isTriggered = TriggerInterface(trigger).checkAndToggleTrigger(); if (isTriggered) { /* * After the trigger event protection providers cannot redeem the full amount they supplied, * but can still redeem a fraction of the amount they supplied. This is because the only * funds left for suppliers to redeem is the unborrowed funds, as borrowed funds do not need * to be paid back. The amount you can redeem is proportional to how much you supplied. * * For example, if $1000 is supplied by protection providers, but only $800 is borrowed by * protection seekers, then when the trigger happens protection providers can withdraw a total * of $200 instead of $1000. That $200 is split proportionally between all providers. So if * Alice provided $300 and Bob provided $700 of the $1000, after the trigger Alice can redeem * her cTokens for $300 / $1000 * 200 = $60 and Bob can redeem his for $700 / $1000 * 200 = $140 * * The exchange rate is calculated as: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply * * Therefore, if we zero out total borrows, the exchange rate methods will calculate the * desired exchange rate after the trigger event without needing to be modified. */ totalBorrows = 0; emit TriggerSet(isTriggered); /* End subsidies to the market */ comptroller._zeroOutCozySpeeds(address(this)); } return isTriggered; } /*** 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 (uint256) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } emit NewPendingAdmin(pendingAdmin, newPendingAdmin); // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; return uint256(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() external returns (uint256) { // 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 uint256(Error.NO_ERROR); } /** * @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(uint256 newReserveFactorMantissa) external nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed. return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED); } // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to. return _setReserveFactorFresh(newReserveFactorMantissa); } /** * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual) * @dev Admin function to set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactorFresh(uint256 newReserveFactorMantissa) internal returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK); } // Verify market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK); } // Check newReserveFactor ≤ maxReserveFactor if (newReserveFactorMantissa > reserveFactorMaxMantissa) { return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK); } emit NewReserveFactor(reserveFactorMantissa, newReserveFactorMantissa); reserveFactorMantissa = newReserveFactorMantissa; return uint256(Error.NO_ERROR); } /** * @notice Accrues interest and reduces reserves by transferring from msg.sender * @param addAmount Amount of addition to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReservesInternal(uint256 addAmount) internal nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED); } // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to. (error, ) = _addReservesFresh(addAmount); return error; } /** * @notice Add reserves by transferring from caller * @dev Requires fresh interest accrual * @param addAmount Amount of addition to reserves * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees */ function _addReservesFresh(uint256 addAmount) internal returns (uint256, uint256) { // totalReserves + actualAddAmount uint256 totalReservesNew; uint256 actualAddAmount; // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the caller and the addAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional addAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ actualAddAmount = doTransferIn(msg.sender, addAmount); totalReservesNew = totalReserves + actualAddAmount; /* Revert on overflow */ require(totalReservesNew >= totalReserves, "add reserves overflow"); // Store reserves[n+1] = reserves[n] + actualAddAmount totalReserves = totalReservesNew; /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */ emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew); /* Return (NO_ERROR, actualAddAmount) */ return (uint256(Error.NO_ERROR), actualAddAmount); } /** * @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(uint256 reduceAmount) external nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED); } // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to. return _reduceReservesFresh(reduceAmount); } /** * @notice Reduces reserves by transferring to admin * @dev Requires fresh interest accrual * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReservesFresh(uint256 reduceAmount) internal returns (uint256) { // totalReserves - reduceAmount uint256 totalReservesNew; // Check caller is Reserve Guardian or admin if (msg.sender != comptroller.reserveGuardian() && msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE); } // Check reduceAmount ≤ reserves[n] (totalReserves) if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); } // Make sure reserve guardian was set to avoid transferring reserves to the zero address if (comptroller.reserveGuardian() == address(0)) { return fail(Error.INVALID_GUARDIAN, FailureInfo.REDUCE_RESERVES_GUARDIAN_NOT_SET); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalReservesNew = totalReserves - reduceAmount; // We checked reduceAmount <= totalReserves above, so this should never revert. require(totalReservesNew <= totalReserves, "reduce reserves underflow"); // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. doTransferOut(comptroller.reserveGuardian(), reduceAmount); emit ReservesReduced(comptroller.reserveGuardian(), reduceAmount, totalReservesNew); return uint256(Error.NO_ERROR); } /** * @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) external returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED); } // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. return _setInterestRateModelFresh(newInterestRateModel); } /** * @notice updates the interest rate model (*requires fresh interest accrual) * @dev Admin function to 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 _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK); } // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require(newInterestRateModel.isInterestRateModel(), "marker method returned false"); // Set the interest rate model to newInterestRateModel emit NewMarketInterestRateModel(interestRateModel, newInterestRateModel); interestRateModel = newInterestRateModel; return uint256(Error.NO_ERROR); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying owned by this contract */ function getCashPrior() internal view returns (uint256); /** * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. * This may revert due to insufficient balance or insufficient allowance. */ function doTransferIn(address from, uint256 amount) internal returns (uint256); /** * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. */ function doTransferOut(address payable to, uint256 amount) internal; /*** Reentrancy Guard ***/ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } /** * @dev Prevents execution of a function if the trigger event has occured */ modifier whenNotTriggered() { require(!isTriggered, "Not allowed once triggered"); _; } } pragma solidity 0.5.17; /** * @notice Partial implementation of Comptroller interface. The methods listed here are the set used by CTokens */ contract ComptrollerInterface { /// @notice Indicator that this is a Comptroller contract (for inspection) bool public constant isComptroller = true; /// @notice Address that CToken reserves are transferred to address payable public reserveGuardian; /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory); function exitMarket(address cToken) external returns (uint256); /*** Policy Hooks ***/ function mintAllowed( address cToken, address minter, uint256 mintAmount ) external returns (uint256); function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external returns (uint256); function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256); function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external returns (uint256); function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256); function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external returns (uint256); /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 repayAmount ) external view returns (uint256, uint256); /*** COZY ***/ /// @notice Sets supply and borrow COZY subsidies to a market to zero function _zeroOutCozySpeeds(address cToken) external; } pragma solidity 0.5.17; import "./ComptrollerInterface.sol"; import "./InterestRateModel.sol"; contract CTokenStorage { /** * @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 Underlying asset for this CToken */ address public underlying; /** * @notice Maximum borrow rate that can ever be applied (.0005% / block) */ uint256 internal constant borrowRateMaxMantissa = 0.0005e16; /** * @notice Maximum fraction of interest that can be set aside for reserves */ uint256 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-cToken operations */ ComptrollerInterface public comptroller; /** * @notice Model which tells what the current interest rate should be */ InterestRateModel public interestRateModel; /** * @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0) */ uint256 internal initialExchangeRateMantissa; /** * @notice Fraction of interest currently set aside for reserves */ uint256 public reserveFactorMantissa; /** * @notice Block number that interest was last accrued at */ uint256 public accrualBlockNumber; /** * @notice Accumulator of the total earned interest rate since the opening of the market */ uint256 public borrowIndex; /** * @notice Total amount of outstanding borrows of the underlying in this market */ uint256 public totalBorrows; /** * @notice Total amount of reserves of the underlying held in this market */ uint256 public totalReserves; /** * @notice Total number of tokens in circulation */ uint256 public totalSupply; /** * @notice Official record of token balances for each account */ mapping(address => uint256) internal accountTokens; /** * @notice Approved token transfer amounts on behalf of others */ mapping(address => mapping(address => uint256)) 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 { uint256 principal; uint256 interestIndex; } /** * @notice Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) internal accountBorrows; /** * @notice Trigger address if token is part of the protection market, zero address otherwise */ address public trigger; /** * @notice Total number of tokens in circulation at the time the trigger event was activated * @dev This variable is not used, but for some reason removing it increases contract size (compiler bug?) so it's kept */ uint256 public totalSupplyWhenTriggered; } contract CTokenInterface is CTokenStorage { /** * @notice Indicator that this is a CToken contract (for inspection) */ bool public constant isCToken = true; /** * @notice Becomes true when the associated `trigger` contract signals that trigger event has occured * @dev This is a one-way toggle: Once set to true it cannot be set back to false */ bool public isTriggered = false; /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint256 cashPrior, uint256 interestAccumulated, uint256 borrowIndex, uint256 totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint256 mintAmount, uint256 mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow(address payer, address borrower, uint256 repayAmount, uint256 accountBorrows, uint256 totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow( address liquidator, address borrower, uint256 repayAmount, address cTokenCollateral, uint256 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 comptroller is changed */ event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint256 oldReserveFactorMantissa, uint256 newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint256 addAmount, uint256 newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint256 reduceAmount, uint256 newTotalReserves); /** * @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); /** * @notice Event emitted when trigger status is set */ event TriggerSet(bool isTriggered); /** * @notice Failure event */ event Failure(uint256 error, uint256 info, uint256 detail); /*** User Interface ***/ function transfer(address dst, uint256 amount) external returns (bool); function transferFrom( address src, address dst, uint256 amount ) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function borrowRatePerBlock() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); function totalBorrowsCurrent() external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) public view returns (uint256); function exchangeRateCurrent() public returns (uint256); function exchangeRateStored() public view returns (uint256); function getCash() external view returns (uint256); function accrueInterest() public returns (uint256); function seize( address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); /*** Admin Functions ***/ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint256); function _acceptAdmin() external returns (uint256); function _setReserveFactor(uint256 newReserveFactorMantissa) external returns (uint256); function _reduceReserves(uint256 reduceAmount) external returns (uint256); function _setInterestRateModel(InterestRateModel newInterestRateModel) external returns (uint256); } contract CErc20Storage {} contract CErc20Interface is CErc20Storage { /*** User Interface ***/ function mint(uint256 mintAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256); function liquidateBorrow( address borrower, uint256 repayAmount, CTokenInterface cTokenCollateral ) external returns (uint256); /*** Admin Functions ***/ function _addReserves(uint256 addAmount) external returns (uint256); } contract CDelegationStorage { /** * @notice Implementation address for this contract */ address public implementation; } contract CDelegatorInterface is CDelegationStorage { /** * @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; } contract CDelegateInterface is CDelegationStorage { /** * @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; } pragma solidity 0.5.17; import "./CarefulMath.sol"; import "./ExponentialNoError.sol"; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @dev Legacy contract for compatibility reasons with existing contracts that still use MathError * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath, ExponentialNoError { /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint256 num, uint256 denom) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint256 rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError error, uint256 result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError error, uint256 result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (MathError, uint256) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt( Exp memory a, uint256 scalar, uint256 addend ) internal pure returns (MathError, uint256) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint256 scalar, Exp memory divisor) internal pure returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint256 numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint256 scalar, Exp memory divisor) internal pure returns (MathError, uint256) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint256 doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint256 product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint256 a, uint256 b) internal pure returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3( Exp memory a, Exp memory b, Exp memory c ) internal pure returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } } pragma solidity 0.5.17; /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ interface EIP20NonStandardInterface { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @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 */ function transfer(address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @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 */ function transferFrom( address src, address dst, uint256 amount ) external; /** * @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 * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @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 */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } pragma solidity 0.5.17; /** * @title Compound's InterestRateModel Interface * @author Compound */ 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( uint256 cash, uint256 borrows, uint256 reserves ) external view returns (uint256); /** * @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( uint256 cash, uint256 borrows, uint256 reserves, uint256 reserveFactorMantissa ) external view returns (uint256); } pragma solidity 0.5.17; /** * @title Careful Math * @author Compound * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError {NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW} /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint256 c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { uint256 c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt( uint256 a, uint256 b, uint256 c ) internal pure returns (MathError, uint256) { (MathError err0, uint256 sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } pragma solidity 0.5.17; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract ExponentialNoError { uint256 constant expScale = 1e18; uint256 constant doubleScale = 1e36; uint256 constant halfExpScale = expScale / 2; uint256 constant mantissaOne = expScale; struct Exp { uint256 mantissa; } struct Double { uint256 mantissa; } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) internal pure returns (uint256) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mul_ScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (uint256) { Exp memory product = mul_(a, scalar); return truncate(product); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mul_ScalarTruncateAddUInt( Exp memory a, uint256 scalar, uint256 addend ) internal pure returns (uint256) { Exp memory product = mul_(a, scalar); return add_(truncate(product), addend); } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) internal pure returns (bool) { return value.mantissa == 0; } function safe224(uint256 n, string memory errorMessage) internal pure returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint256 a, uint256 b) internal pure returns (uint256) { return add_(a, b, "addition overflow"); } function add_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint256 a, uint256 b) internal pure returns (uint256) { return sub_(a, b, "subtraction underflow"); } function sub_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint256 b) internal pure returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint256 a, Exp memory b) internal pure returns (uint256) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint256 a, Double memory b) internal pure returns (uint256) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint256 a, uint256 b) internal pure returns (uint256) { return mul_(a, b, "multiplication overflow"); } function mul_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint256 b) internal pure returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint256 a, Exp memory b) internal pure returns (uint256) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint256 a, Double memory b) internal pure returns (uint256) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint256 a, uint256 b) internal pure returns (uint256) { return div_(a, b, "divide by zero"); } function div_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } function fraction(uint256 a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } }
accrues interest and updates the interest rate model using _setInterestRateModelFresh Admin function to accrue interest and update the interest rate model newInterestRateModel the new interest rate model to use return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/ accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed
function _setInterestRateModel(InterestRateModel newInterestRateModel) external returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED); } }
14,760,618
pragma solidity 0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(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; } } /** * @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 OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() 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 transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { /// Total amount of tokens uint256 public totalSupply; function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _amount) public returns (bool success); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @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 remaining); function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success); function approve(address _spender, uint256 _amount) public returns (bool success); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; struct TokenVest { address vestAddress; uint vestTokensLimit; uint vestTill; } //balance in each address account mapping(address => uint256) balances; // list of tokens vest TokenVest[] listofVest; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _amount The amount to be transferred. */ function transfer(address _to, uint256 _amount) public returns (bool success) { require(isTransferAllowed(msg.sender,_amount)); require(_to != address(0)); require(balances[msg.sender] >= _amount && _amount > 0 && balances[_to].add(_amount) > balances[_to]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(msg.sender, _to, _amount); 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 balance) { return balances[_owner]; } function isTransferAllowed(address trans_from, uint amt) internal returns(bool) { for(uint i=0;i<listofVest.length;i++) { if(listofVest[i].vestAddress==trans_from) { if(now<=listofVest[i].vestTill) { if((balanceOf(trans_from).sub(amt)<listofVest[i].vestTokensLimit)) { return false; } } } } return true; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 */ 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 _amount uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { require(isTransferAllowed(_from,_amount)); require(_to != address(0)); require(balances[_from] >= _amount); require(allowed[_from][msg.sender] >= _amount); require(_amount > 0 && balances[_to].add(_amount) > balances[_to]); balances[_from] = balances[_from].sub(_amount); balances[_to] = balances[_to].add(_amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); emit Transfer(_from, _to, _amount); 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 _amount The amount of tokens to be spent. */ function approve(address _spender, uint256 _amount) public returns (bool success) { allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); 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 remaining) { return allowed[_owner][_spender]; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is StandardToken, Ownable { 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 onlyOwner{ require(_value <= balances[msg.sender]); // 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[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(msg.sender, _value); } } /** * @title EthereumTravelToken Token * @dev */ contract EthereumTravelToken is BurnableToken { string public name ; string public symbol ; uint8 public decimals = 18 ; address public AdvisorsAddress; address public TeamAddress; address public ReserveAddress; TokenVest vestObject; uint public TeamVestTimeLimit; /** *@dev users sending ether to this contract will be reverted. Any ether sent to the contract will be sent back to the caller */ function ()public payable { revert(); } /** * @dev Constructor function to initialize the initial supply of token to the creator of the contract */ function EthereumTravelToken( address wallet, uint supply, string nam, string symb ) public { owner = wallet; totalSupply = supply; totalSupply = totalSupply.mul( 10 ** uint256(decimals)); //Update total supply with the decimal amount name = nam; symbol = symb; balances[wallet] = totalSupply; TeamAddress=0xACE8841DF22F7b5d112db5f5AE913c7adA3457aF; AdvisorsAddress=0x49695C3cB19aA4A32F6f465b54CE62e337A07c7b; ReserveAddress=0xec599e12B45BB77B65291C30911d9B2c3991aB3D; TeamVestTimeLimit = now + 365 days; //Emitting transfer event since assigning all tokens to the creator also corresponds to the transfer of tokens to the creator emit Transfer(address(0), msg.sender, totalSupply); // transferring 18% of the tokens to team Address transfer(TeamAddress, (totalSupply.mul(18)).div(100)); // transferring 1% of the tokens to advisors Address transfer(AdvisorsAddress, (totalSupply.mul(1)).div(100)); // transferring 21% of the tokens to company Address transfer(ReserveAddress, (totalSupply.mul(21)).div(100)); // vesting team address vestTokens(TeamAddress,(totalSupply.mul(18)).div(100),TeamVestTimeLimit); } /** *@dev helper method to get token details, name, symbol and totalSupply in one go */ function getTokenDetail() public view returns (string, string, uint256) { return (name, symbol, totalSupply); } /** *@dev internal method to add a vest in token memory */ function vestTokens(address ad, uint tkns, uint timelimit) internal { vestObject = TokenVest({ vestAddress:ad, vestTokensLimit:tkns, vestTill:timelimit }); listofVest.push(vestObject); } }
Constructor function to initialize the initial supply of token to the creator of the contract/Emitting transfer event since assigning all tokens to the creator also corresponds to the transfer of tokens to the creator transferring 18% of the tokens to team Address transferring 1% of the tokens to advisors Address transferring 21% of the tokens to company Address vesting team address
function EthereumTravelToken( address wallet, uint supply, string nam, string symb ) public { owner = wallet; totalSupply = supply; name = nam; symbol = symb; balances[wallet] = totalSupply; TeamAddress=0xACE8841DF22F7b5d112db5f5AE913c7adA3457aF; AdvisorsAddress=0x49695C3cB19aA4A32F6f465b54CE62e337A07c7b; ReserveAddress=0xec599e12B45BB77B65291C30911d9B2c3991aB3D; TeamVestTimeLimit = now + 365 days; emit Transfer(address(0), msg.sender, totalSupply); transfer(TeamAddress, (totalSupply.mul(18)).div(100)); transfer(AdvisorsAddress, (totalSupply.mul(1)).div(100)); transfer(ReserveAddress, (totalSupply.mul(21)).div(100)); vestTokens(TeamAddress,(totalSupply.mul(18)).div(100),TeamVestTimeLimit); }
14,559,375
pragma solidity ^0.4.23; contract ERC20 { .. } pragma solidity ^0.4.23; import "./math/SafeMath.sol"; contract ERC20 { using SafeMath for uint256; } // Total number of tokens in existence uint256 totalSupply_; pragma solidity ^0.4.23; import "./math/SafeMath.sol"; contract ERC20 { using SafeMath for uint256; // The total number of tokens in existence uint256 totalSupply_; function totalSupply() public view returns (uint256) { return totalSupply_; } } mapping(address => uint256) balances; pragma solidity ^0.4.23; import "./math/SafeMath.sol"; contract ERC20 { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev To get 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]; } } pragma solidity ^0.4.23; import "./math/SafeMath.sol"; contract ERC20 { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; constructor(uint _totalSupply) { totalSupply_ = _totalSupply; // Assigns all tokens to the owner balances[msg.sender] = _totalSupply; } /** * @dev An uint256 representing the total number of tokens. */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @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]; } }
Gets the balance of the specified address. _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]; }
12,868,429
// A life-log, done for Charlyn Greeff, born 18 April 2016 @ 15h30 (1460993400) // Mother: Mirana Hotz, 16 December 1977 (251078400) // Father: Jaco Greeff, 11 June 1973 (108604800) // // version: 1.0.0 // source: https://github.com/jacogr/ethcontracts/tree/master/src/LifeLog contract CharlyLifeLog { // allow a maximum 20% withdrawal at any time uint private constant MAX_WITHDRAW_DIV = 5; // 100/20 // allow one withdrawal every 6 months/180 days uint private constant WITHDRAW_INTERVAL = 180 days; // all the actual events that can be created event LogDonation(address indexed by, uint loggedAt, uint amount); event LogWithdrawal(address indexed by, uint loggedAt, uint amount); event LogPersonNew(address indexed by, uint loggedAt, uint index); event LogPersonUpdate(address indexed by, uint loggedAt, uint index, string field); event LogWhitelistAdd(address indexed by, uint loggedAt, address addr); event LogWhitelistRemove(address indexed by, uint loggedAt); event LogEvent(address indexed by, uint loggedAt, uint when, string description); // a structure describing a person struct Person { bool active; uint activatedAt; uint deactivatedAt; int dateOfBirth; int dateOfDeath; string name; string relation; } // next time whitelist address is allowed to get some funds uint public nextWithdrawal = now + WITHDRAW_INTERVAL; // totals of received and withdrawn amounts uint public totalDonated = 0; uint public totalWithdrawn = 0; // people in the life of ([0] == 'self') Person[] public people; // donations received mapping(address => uint) public donations; // whitelisted modifier accounts mapping(address => bool) public whitelist; // modifier to allow only the whitelisted addresses modifier isOnWhitelist { // if not in the whitelist, throw error if (!whitelist[msg.sender]) { throw; } // if any value attached, don't accept it if (msg.value > 0) { throw; } // original code executes in here _ } // construct a lifelog for this specific person function CharlyLifeLog(string name, int dateOfBirth) { // creator should go on the whitelist whitelist[msg.sender] = true; // add the first person personAdd(name, dateOfBirth, 0, 'self'); // any donations? if (msg.value > 0) { donate(); } } // log an event function log(string description, uint _when) public isOnWhitelist { // infer timestamp or use specified uint when = _when; if (when == 0) { when = now; } // create the event LogEvent(msg.sender, now, when, description); } // add a specific person function personAdd(string name, int dateOfBirth, int dateOfDeath, string relation) public isOnWhitelist { // create the event LogPersonNew(msg.sender, now, people.length); // add the person people.push( Person({ active: true, activatedAt: now, deactivatedAt: 0, dateOfBirth: dateOfBirth, dateOfDeath: dateOfDeath, name: name, relation: relation }) ); } // activate/deactivate a specific person function personUpdateActivity(uint index, bool active) public isOnWhitelist { // set the flag people[index].active = active; // activate/deactivate if (active) { // create the event LogPersonUpdate(msg.sender, now, index, 'active'); // make it so people[index].activatedAt = now; people[index].deactivatedAt = 0; } else { // create the event LogPersonUpdate(msg.sender, now, index, 'inactive'); // make it so people[index].deactivatedAt = now; } } // update a person's name function personUpdateName(uint index, string name) public isOnWhitelist { // create the event LogPersonUpdate(msg.sender, now, index, 'name'); // update people[index].name = name; } // update a person's relation function personUpdateRelation(uint index, string relation) public isOnWhitelist { // create the event LogPersonUpdate(msg.sender, now, index, 'relation'); // update people[index].relation = relation; } // update a person's DOB function personUpdateDOB(uint index, int dateOfBirth) public isOnWhitelist { // create the event LogPersonUpdate(msg.sender, now, index, 'dateOfBirth'); // update people[index].dateOfBirth = dateOfBirth; } // update a person's DOD function personUpdateDOD(uint index, int dateOfDeath) public isOnWhitelist { // create the event LogPersonUpdate(msg.sender, now, index, 'dateOfDeath'); // update people[index].dateOfDeath = dateOfDeath; } // add a whitelist address function whitelistAdd(address addr) public isOnWhitelist { // create the event LogWhitelistAdd(msg.sender, now, addr); // update whitelist[addr] = true; } // remove a whitelist address function whitelistRemove(address addr) public isOnWhitelist { // we can only remove ourselves, double-validate failsafe if (msg.sender != addr) { throw; } // create the event LogWhitelistRemove(msg.sender, now); // remove whitelist[msg.sender] = false; } // withdraw funds as/when needed function withdraw(uint amount) public isOnWhitelist { // the maximum we are allowed to take out right now uint max = this.balance / MAX_WITHDRAW_DIV; // see that we are in range and the timing matches if (amount > max || now < nextWithdrawal) { throw; } // update the event log with the action LogWithdrawal(msg.sender, now, amount); // set the next withdrawal date/time & totals nextWithdrawal = now + WITHDRAW_INTERVAL; totalWithdrawn += amount; // send and throw if not ok if (!msg.sender.send(amount)) { throw; } } // accept donations from anywhere and give credit function donate() public { // there needs to be something here if (msg.value == 0) { throw; } // update the event log with the action LogDonation(msg.sender, now, msg.value); // store the donation donations[msg.sender] += msg.value; totalDonated += msg.value; } // fallback is a donation function() public { donate(); } }
withdraw funds as/when needed the maximum we are allowed to take out right now see that we are in range and the timing matches send and throw if not ok
function withdraw(uint amount) public isOnWhitelist { uint max = this.balance / MAX_WITHDRAW_DIV; if (amount > max || now < nextWithdrawal) { throw; } totalWithdrawn += amount; if (!msg.sender.send(amount)) { throw; } }
5,469,891
// SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "./PoolTokensContainer.sol"; import "./LiquidityPoolV2ConverterCustomFactory.sol"; import "../../LiquidityPoolConverter.sol"; import "../../interfaces/IConverterFactory.sol"; import "../../../utility/interfaces/IPriceOracle.sol"; /** * @dev Liquidity Pool v2 Converter * * The liquidity pool v2 converter is a specialized version of a converter that uses * price oracles to rebalance the reserve weights in such a way that the primary token * balance always strives to match the staked balance. * * This type of liquidity pool always has 2 reserves and the reserve weights are dynamic. */ contract LiquidityPoolV2Converter is LiquidityPoolConverter { uint32 internal constant HIGH_FEE_UPPER_BOUND = 997500; // high fee upper bound in PPM units uint256 internal constant MAX_RATE_FACTOR_LOWER_BOUND = 1e30; struct Fraction { uint256 n; // numerator uint256 d; // denominator } IPriceOracle public priceOracle; // external price oracle IERC20Token public primaryReserveToken; // primary reserve in the pool IERC20Token public secondaryReserveToken; // secondary reserve in the pool (cache) mapping (IERC20Token => uint256) private stakedBalances; // tracks the staked liquidity in the pool plus the fees mapping (IERC20Token => ISmartToken) private reservesToPoolTokens; // maps each reserve to its pool token mapping (ISmartToken => IERC20Token) private poolTokensToReserves; // maps each pool token to its reserve uint8 public amplificationFactor = 20; // factor to use for conversion calculations (reduces slippage) uint256 public externalRatePropagationTime = 1 hours; // the time it takes for the external rate to fully take effect uint256 public prevConversionTime; // previous conversion time in seconds // factors used in fee calculations uint32 public lowFeeFactor = 200000; uint32 public highFeeFactor = 800000; // used by the temp liquidity limit mechanism during the beta mapping (IERC20Token => uint256) public maxStakedBalances; bool public maxStakedBalanceEnabled = true; /** * @dev triggered when the amplification factor is updated * * @param _prevAmplificationFactor previous amplification factor * @param _newAmplificationFactor new amplification factor */ event AmplificationFactorUpdate(uint8 _prevAmplificationFactor, uint8 _newAmplificationFactor); /** * @dev triggered when the external rate propagation time is updated * * @param _prevPropagationTime previous external rate propagation time, in seconds * @param _newPropagationTime new external rate propagation time, in seconds */ event ExternalRatePropagationTimeUpdate(uint256 _prevPropagationTime, uint256 _newPropagationTime); /** * @dev triggered when the fee factors are updated * * @param _prevLowFactor previous low factor percentage, represented in ppm * @param _newLowFactor new low factor percentage, represented in ppm * @param _prevHighFactor previous high factor percentage, represented in ppm * @param _newHighFactor new high factor percentage, represented in ppm */ event FeeFactorsUpdate(uint256 _prevLowFactor, uint256 _newLowFactor, uint256 _prevHighFactor, uint256 _newHighFactor); /** * @dev initializes a new LiquidityPoolV2Converter instance * * @param _poolTokensContainer pool tokens container governed by the converter * @param _registry address of a contract registry contract * @param _maxConversionFee maximum conversion fee, represented in ppm */ constructor(IPoolTokensContainer _poolTokensContainer, IContractRegistry _registry, uint32 _maxConversionFee) public LiquidityPoolConverter(_poolTokensContainer, _registry, _maxConversionFee) { } // ensures the address is a pool token modifier validPoolToken(ISmartToken _address) { _validPoolToken(_address); _; } // error message binary size optimization function _validPoolToken(ISmartToken _address) internal view { require(address(poolTokensToReserves[_address]) != address(0), "ERR_INVALID_POOL_TOKEN"); } /** * @dev returns the converter type * * @return see the converter types in the the main contract doc */ function converterType() public override pure returns (uint16) { return 2; } /** * @dev returns true if the converter is active, false otherwise * * @return true if the converter is active, false otherwise */ function isActive() public override view returns (bool) { return super.isActive() && address(priceOracle) != address(0); } /** * @dev sets the pool's primary reserve token / price oracles and activates the pool * each oracle must be able to provide the rate for each reserve token * note that the oracle must be whitelisted prior to the call * can only be called by the owner while the pool is inactive * * @param _primaryReserveToken address of the pool's primary reserve token * @param _primaryReserveOracle address of a chainlink price oracle for the primary reserve token * @param _secondaryReserveOracle address of a chainlink price oracle for the secondary reserve token */ function activate( IERC20Token _primaryReserveToken, IChainlinkPriceOracle _primaryReserveOracle, IChainlinkPriceOracle _secondaryReserveOracle) public inactive ownerOnly validReserve(_primaryReserveToken) notThis(address(_primaryReserveOracle)) notThis(address(_secondaryReserveOracle)) validAddress(address(_primaryReserveOracle)) validAddress(address(_secondaryReserveOracle)) { // validate anchor ownership require(anchor.owner() == address(this), "ERR_ANCHOR_NOT_OWNED"); // validate oracles IWhitelist oracleWhitelist = IWhitelist(addressOf(CHAINLINK_ORACLE_WHITELIST)); require(oracleWhitelist.isWhitelisted(address(_primaryReserveOracle)) && oracleWhitelist.isWhitelisted(address(_secondaryReserveOracle)), "ERR_INVALID_ORACLE"); // create the converter's pool tokens if they don't already exist createPoolTokens(); // sets the primary & secondary reserve tokens primaryReserveToken = _primaryReserveToken; if (_primaryReserveToken == reserveTokens[0]) secondaryReserveToken = reserveTokens[1]; else secondaryReserveToken = reserveTokens[0]; // creates and initalizes the price oracle and sets initial rates LiquidityPoolV2ConverterCustomFactory customFactory = LiquidityPoolV2ConverterCustomFactory(address(IConverterFactory(addressOf(CONVERTER_FACTORY)).customFactories(converterType()))); priceOracle = customFactory.createPriceOracle( _primaryReserveToken, secondaryReserveToken, _primaryReserveOracle, _secondaryReserveOracle); // if we are upgrading from an older converter, make sure that reserve balances are in-sync and rebalance uint256 primaryReserveStakedBalance = reserveStakedBalance(primaryReserveToken); uint256 primaryReserveBalance = reserveBalance(primaryReserveToken); uint256 secondaryReserveBalance = reserveBalance(secondaryReserveToken); if (primaryReserveStakedBalance == primaryReserveBalance) { if (primaryReserveStakedBalance > 0 || secondaryReserveBalance > 0) { rebalance(); } } else if (primaryReserveStakedBalance > 0 && primaryReserveBalance > 0 && secondaryReserveBalance > 0) { rebalance(); } emit Activation(converterType(), anchor, true); } /** * @dev returns the staked balance of a given reserve token * * @param _reserveToken reserve token address * * @return staked balance */ function reserveStakedBalance(IERC20Token _reserveToken) public view validReserve(_reserveToken) returns (uint256) { return stakedBalances[_reserveToken]; } /** * @dev returns the amplified balance of a given reserve token * * @param _reserveToken reserve token address * * @return amplified balance */ function reserveAmplifiedBalance(IERC20Token _reserveToken) public view validReserve(_reserveToken) returns (uint256) { return amplifiedBalance(_reserveToken); } /** * @dev sets the reserve's staked balance * can only be called by the upgrader contract while the upgrader is the owner * * @param _reserveToken reserve token address * @param _balance new reserve staked balance */ function setReserveStakedBalance(IERC20Token _reserveToken, uint256 _balance) public ownerOnly only(CONVERTER_UPGRADER) validReserve(_reserveToken) { stakedBalances[_reserveToken] = _balance; } /** * @dev sets the max staked balance for both reserves * available as a temporary mechanism during the beta * can only be called by the owner * * @param _reserve1MaxStakedBalance max staked balance for reserve 1 * @param _reserve2MaxStakedBalance max staked balance for reserve 2 */ function setMaxStakedBalances(uint256 _reserve1MaxStakedBalance, uint256 _reserve2MaxStakedBalance) public ownerOnly { maxStakedBalances[reserveTokens[0]] = _reserve1MaxStakedBalance; maxStakedBalances[reserveTokens[1]] = _reserve2MaxStakedBalance; } /** * @dev disables the max staked balance mechanism * available as a temporary mechanism during the beta * once disabled, it cannot be re-enabled * can only be called by the owner */ function disableMaxStakedBalances() public ownerOnly { maxStakedBalanceEnabled = false; } /** * @dev returns the pool token address by the reserve token address * * @param _reserveToken reserve token address * * @return pool token address */ function poolToken(IERC20Token _reserveToken) public view returns (ISmartToken) { return reservesToPoolTokens[_reserveToken]; } /** * @dev returns the maximum number of pool tokens that can currently be liquidated * * @param _poolToken address of the pool token * * @return liquidation limit */ function liquidationLimit(ISmartToken _poolToken) public view returns (uint256) { // get the pool token supply uint256 poolTokenSupply = _poolToken.totalSupply(); // get the reserve token associated with the pool token and its balance / staked balance IERC20Token reserveToken = poolTokensToReserves[_poolToken]; uint256 balance = reserveBalance(reserveToken); uint256 stakedBalance = stakedBalances[reserveToken]; // calculate the amount that's available for liquidation return balance.mul(poolTokenSupply).div(stakedBalance); } /** * @dev defines a new reserve token for the converter * can only be called by the owner while the converter is inactive and * 2 reserves aren't defined yet * * @param _token address of the reserve token * @param _weight reserve weight, represented in ppm, 1-1000000 */ function addReserve(IERC20Token _token, uint32 _weight) public override ownerOnly { // verify that the converter doesn't have 2 reserves yet require(reserveTokenCount() < 2, "ERR_INVALID_RESERVE_COUNT"); super.addReserve(_token, _weight); } /** * @dev returns the effective rate of 1 primary token in secondary tokens * * @return rate of 1 primary token in secondary tokens (numerator) * @return rate of 1 primary token in secondary tokens (denominator) */ function effectiveTokensRate() public view returns (uint256, uint256) { Fraction memory rate = rateFromPrimaryWeight(effectivePrimaryWeight()); return (rate.n, rate.d); } /** * @dev returns the effective reserve tokens weights * * @return reserve1 weight * @return reserve2 weight */ function effectiveReserveWeights() public view returns (uint256, uint256) { uint32 primaryReserveWeight = effectivePrimaryWeight(); if (primaryReserveToken == reserveTokens[0]) { return (primaryReserveWeight, inverseWeight(primaryReserveWeight)); } return (inverseWeight(primaryReserveWeight), primaryReserveWeight); } /** * @dev updates the amplification factor * can only be called by the contract owner * * @param _amplificationFactor new amplification factor */ function setAmplificationFactor(uint8 _amplificationFactor) public ownerOnly { emit AmplificationFactorUpdate(amplificationFactor, _amplificationFactor); amplificationFactor = _amplificationFactor; } /** * @dev updates the external rate propagation time * can only be called by the contract owner * * @param _propagationTime new rate propagation time, in seconds */ function setExternalRatePropagationTime(uint256 _propagationTime) public ownerOnly { emit ExternalRatePropagationTimeUpdate(externalRatePropagationTime, _propagationTime); externalRatePropagationTime = _propagationTime; } /** * @dev updates the fee factors * can only be called by the contract owner * * @param _lowFactor new low fee factor, represented in ppm * @param _highFactor new high fee factor, represented in ppm */ function setFeeFactors(uint32 _lowFactor, uint32 _highFactor) public ownerOnly { require(_lowFactor <= PPM_RESOLUTION, "ERR_INVALID_FEE_FACTOR"); require(_highFactor <= PPM_RESOLUTION, "ERR_INVALID_FEE_FACTOR"); emit FeeFactorsUpdate(lowFeeFactor, _lowFactor, highFeeFactor, _highFactor); lowFeeFactor = _lowFactor; highFeeFactor = _highFactor; } /** * @dev returns the expected target amount of converting one reserve to another along with the fee * * @param _sourceToken contract address of the source reserve token * @param _targetToken contract address of the target reserve token * @param _amount amount of tokens received from the user * * @return expected target amount * @return expected fee */ function targetAmountAndFee(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount) public override view active validReserve(_sourceToken) validReserve(_targetToken) returns (uint256, uint256) { // validate input require(_sourceToken != _targetToken, "ERR_SAME_SOURCE_TARGET"); // get the external rate between the reserves along with its update time Fraction memory externalRate; uint256 externalRateUpdateTime; (externalRate.n, externalRate.d, externalRateUpdateTime) = priceOracle.latestRateAndUpdateTime(primaryReserveToken, secondaryReserveToken); // get the source token effective / external weights (uint32 sourceTokenWeight, uint32 externalSourceTokenWeight) = effectiveAndExternalPrimaryWeight(externalRate, externalRateUpdateTime); if (_targetToken == primaryReserveToken) { sourceTokenWeight = inverseWeight(sourceTokenWeight); externalSourceTokenWeight = inverseWeight(externalSourceTokenWeight); } // return the target amount and the fee using the updated reserve weights return targetAmountAndFee( _sourceToken, _targetToken, sourceTokenWeight, inverseWeight(sourceTokenWeight), externalRate, inverseWeight(externalSourceTokenWeight), _amount); } /** * @dev converts a specific amount of source tokens to target tokens * can only be called by the bancor network contract * * @param _sourceToken source ERC20 token * @param _targetToken target ERC20 token * @param _amount amount of tokens to convert (in units of the source token) * @param _trader address of the caller who executed the conversion * @param _beneficiary wallet to receive the conversion result * * @return amount of tokens received (in units of the target token) */ function doConvert(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount, address _trader, address payable _beneficiary) internal override active validReserve(_sourceToken) validReserve(_targetToken) returns (uint256) { // convert and get the target amount and fee (uint256 amount, uint256 fee) = doConvert(_sourceToken, _targetToken, _amount); // update the previous conversion time prevConversionTime = time(); // transfer funds to the beneficiary in the to reserve token if (_targetToken == ETH_RESERVE_ADDRESS) { _beneficiary.transfer(amount); } else { safeTransfer(_targetToken, _beneficiary, amount); } // dispatch the conversion event dispatchConversionEvent(_sourceToken, _targetToken, _trader, _amount, amount, fee); // dispatch rate updates for the pool / reserve tokens dispatchRateEvents(_sourceToken, _targetToken, reserves[_sourceToken].weight, reserves[_targetToken].weight); // return the conversion result amount return amount; } /** * @dev converts a specific amount of source tokens to target tokens * can only be called by the bancor network contract * * @param _sourceToken source ERC20 token * @param _targetToken target ERC20 token * @param _amount amount of tokens to convert (in units of the source token) * * @return amount of target tokens received * @return fee amount */ function doConvert(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount) private returns (uint256, uint256) { // get the external rate between the reserves along with its update time Fraction memory externalRate; uint256 externalRateUpdateTime; (externalRate.n, externalRate.d, externalRateUpdateTime) = priceOracle.latestRateAndUpdateTime(primaryReserveToken, secondaryReserveToken); // pre-conversion preparation - update the weights if needed and get the target amount and feee (uint256 targetAmount, uint256 fee) = prepareConversion(_sourceToken, _targetToken, _amount, externalRate, externalRateUpdateTime); // ensure that the trade gives something in return require(targetAmount != 0, "ERR_ZERO_TARGET_AMOUNT"); // ensure that the trade won't deplete the reserve balance uint256 targetReserveBalance = reserves[_targetToken].balance; require(targetAmount < targetReserveBalance, "ERR_TARGET_AMOUNT_TOO_HIGH"); // ensure that the input amount was already deposited if (_sourceToken == ETH_RESERVE_ADDRESS) require(msg.value == _amount, "ERR_ETH_AMOUNT_MISMATCH"); else require(msg.value == 0 && _sourceToken.balanceOf(address(this)).sub(reserves[_sourceToken].balance) >= _amount, "ERR_INVALID_AMOUNT"); // sync the reserve balances syncReserveBalance(_sourceToken); reserves[_targetToken].balance = targetReserveBalance.sub(targetAmount); // if the pool is in deficit, add half the fee to the target staked balance, otherwise add all stakedBalances[_targetToken] = stakedBalances[_targetToken].add(calculateDeficit(externalRate) == 0 ? fee : fee / 2); // return a tuple of [target amount (excluding fee), fee] return (targetAmount, fee); } /** * @dev increases the pool's liquidity and mints new shares in the pool to the caller * * @param _reserveToken address of the reserve token to add liquidity to * @param _amount amount of liquidity to add * @param _minReturn minimum return-amount of pool tokens * * @return amount of pool tokens minted */ function addLiquidity(IERC20Token _reserveToken, uint256 _amount, uint256 _minReturn) public payable protected active validReserve(_reserveToken) greaterThanZero(_amount) greaterThanZero(_minReturn) returns (uint256) { // verify that msg.value is identical to the provided amount for ETH reserve, or 0 otherwise require(_reserveToken == ETH_RESERVE_ADDRESS ? msg.value == _amount : msg.value == 0, "ERR_ETH_AMOUNT_MISMATCH"); // sync the reserve balances just in case syncReserveBalances(); // for ETH reserve, deduct the amount that was just synced (since it's already in the converter) if (_reserveToken == ETH_RESERVE_ADDRESS) { reserves[ETH_RESERVE_ADDRESS].balance = reserves[ETH_RESERVE_ADDRESS].balance.sub(msg.value); } // get the reserve staked balance before adding the liquidity to it uint256 initialStakedBalance = stakedBalances[_reserveToken]; // during the beta, ensure that the new staked balance isn't greater than the max limit if (maxStakedBalanceEnabled) { require(maxStakedBalances[_reserveToken] == 0 || initialStakedBalance.add(_amount) <= maxStakedBalances[_reserveToken], "ERR_MAX_STAKED_BALANCE_REACHED"); } // get the pool token associated with the reserve and its supply ISmartToken reservePoolToken = reservesToPoolTokens[_reserveToken]; uint256 poolTokenSupply = reservePoolToken.totalSupply(); // for non ETH reserve, transfer the funds from the user to the pool if (_reserveToken != ETH_RESERVE_ADDRESS) safeTransferFrom(_reserveToken, msg.sender, address(this), _amount); // get the rate before updating the staked balance Fraction memory rate = rebalanceRate(); // sync the reserve balance / staked balance reserves[_reserveToken].balance = reserves[_reserveToken].balance.add(_amount); stakedBalances[_reserveToken] = initialStakedBalance.add(_amount); // calculate how many pool tokens to mint // for an empty pool, the price is 1:1, otherwise the price is based on the ratio // between the pool token supply and the staked balance uint256 poolTokenAmount = 0; if (initialStakedBalance == 0 || poolTokenSupply == 0) poolTokenAmount = _amount; else poolTokenAmount = _amount.mul(poolTokenSupply).div(initialStakedBalance); require(poolTokenAmount >= _minReturn, "ERR_RETURN_TOO_LOW"); // mint new pool tokens to the caller IPoolTokensContainer(address(anchor)).mint(reservePoolToken, msg.sender, poolTokenAmount); // rebalance the pool's reserve weights rebalance(rate); // dispatch the LiquidityAdded event emit LiquidityAdded(msg.sender, _reserveToken, _amount, initialStakedBalance.add(_amount), poolTokenSupply.add(poolTokenAmount)); // dispatch the `TokenRateUpdate` event for the pool token dispatchPoolTokenRateUpdateEvent(reservePoolToken, poolTokenSupply.add(poolTokenAmount), _reserveToken); // dispatch the `TokenRateUpdate` event for the reserve tokens dispatchTokenRateUpdateEvent(reserveTokens[0], reserveTokens[1], 0, 0); // return the amount of pool tokens minted return poolTokenAmount; } /** * @dev decreases the pool's liquidity and burns the caller's shares in the pool * * @param _poolToken address of the pool token * @param _amount amount of pool tokens to burn * @param _minReturn minimum return-amount of reserve tokens * * @return amount of liquidity removed */ function removeLiquidity(ISmartToken _poolToken, uint256 _amount, uint256 _minReturn) public protected active validPoolToken(_poolToken) greaterThanZero(_amount) greaterThanZero(_minReturn) returns (uint256) { // sync the reserve balances just in case syncReserveBalances(); // get the pool token supply before burning the caller's shares uint256 initialPoolSupply = _poolToken.totalSupply(); // get the reserve token return before burning the caller's shares (uint256 reserveAmount, ) = removeLiquidityReturnAndFee(_poolToken, _amount); require(reserveAmount >= _minReturn, "ERR_RETURN_TOO_LOW"); // get the reserve token associated with the pool token IERC20Token reserveToken = poolTokensToReserves[_poolToken]; // burn the caller's pool tokens IPoolTokensContainer(address(anchor)).burn(_poolToken, msg.sender, _amount); // get the rate before updating the staked balance Fraction memory rate = rebalanceRate(); // sync the reserve balance / staked balance reserves[reserveToken].balance = reserves[reserveToken].balance.sub(reserveAmount); uint256 newStakedBalance = stakedBalances[reserveToken].sub(reserveAmount); stakedBalances[reserveToken] = newStakedBalance; // transfer the reserve amount to the caller if (reserveToken == ETH_RESERVE_ADDRESS) msg.sender.transfer(reserveAmount); else safeTransfer(reserveToken, msg.sender, reserveAmount); // rebalance the pool's reserve weights rebalance(rate); uint256 newPoolTokenSupply = initialPoolSupply.sub(_amount); // dispatch the LiquidityRemoved event emit LiquidityRemoved(msg.sender, reserveToken, reserveAmount, newStakedBalance, newPoolTokenSupply); // dispatch the `TokenRateUpdate` event for the pool token dispatchPoolTokenRateUpdateEvent(_poolToken, newPoolTokenSupply, reserveToken); // dispatch the `TokenRateUpdate` event for the reserve tokens dispatchTokenRateUpdateEvent(reserveTokens[0], reserveTokens[1], 0, 0); // return the amount of liquidity removed return reserveAmount; } /** * @dev calculates the amount of reserve tokens entitled for a given amount of pool tokens * note that a fee is applied according to the equilibrium level of the primary reserve token * * @param _poolToken address of the pool token * @param _amount amount of pool tokens * * @return amount after fee and fee, in reserve token units */ function removeLiquidityReturnAndFee(ISmartToken _poolToken, uint256 _amount) public view returns (uint256, uint256) { uint256 totalSupply = _poolToken.totalSupply(); uint256 stakedBalance = stakedBalances[poolTokensToReserves[_poolToken]]; if (_amount < totalSupply) { (uint256 min, uint256 max) = tokensRateAccuracy(); uint256 amountBeforeFee = _amount.mul(stakedBalance).div(totalSupply); uint256 amountAfterFee = amountBeforeFee.mul(min).div(max); return (amountAfterFee, amountBeforeFee - amountAfterFee); } return (stakedBalance, 0); } /** * @dev calculates the tokens-rate accuracy * * @return the tokens-rate accuracy as a tuple of numerator and denominator */ function tokensRateAccuracy() internal view returns (uint256, uint256) { uint32 weight = reserves[primaryReserveToken].weight; Fraction memory poolRate = tokensRate(primaryReserveToken, secondaryReserveToken, weight, inverseWeight(weight)); (uint256 n, uint256 d) = effectiveTokensRate(); (uint256 x, uint256 y) = reducedRatio(poolRate.n.mul(d), poolRate.d.mul(n), MAX_RATE_FACTOR_LOWER_BOUND); return x < y ? (x, y) : (y, x); } /** * @dev returns the expected target amount of converting one reserve to another along with the fee * this version of the function expects the reserve weights as an input (gas optimization) * * @param _sourceToken contract address of the source reserve token * @param _targetToken contract address of the target reserve token * @param _sourceWeight source reserve token weight * @param _targetWeight target reserve token weight * @param _externalRate external rate of 1 primary token in secondary tokens * @param _targetExternalWeight target reserve token weight based on external rate * @param _amount amount of tokens received from the user * * @return expected target amount * @return expected fee */ function targetAmountAndFee( IERC20Token _sourceToken, IERC20Token _targetToken, uint32 _sourceWeight, uint32 _targetWeight, Fraction memory _externalRate, uint32 _targetExternalWeight, uint256 _amount) private view returns (uint256, uint256) { // get the tokens amplified balances uint256 sourceBalance = amplifiedBalance(_sourceToken); uint256 targetBalance = amplifiedBalance(_targetToken); // get the target amount uint256 targetAmount = IBancorFormula(addressOf(BANCOR_FORMULA)).crossReserveTargetAmount( sourceBalance, _sourceWeight, targetBalance, _targetWeight, _amount ); // if the target amount is larger than the target reserve balance, return 0 // this can happen due to the amplification require(targetAmount <= reserves[_targetToken].balance, "ERR_TARGET_AMOUNT_TOO_HIGH"); // return a tuple of [target amount (excluding fee), fee] uint256 fee = calculateFee(_sourceToken, _targetToken, _sourceWeight, _targetWeight, _externalRate, _targetExternalWeight, targetAmount); return (targetAmount - fee, fee); } /** * @dev returns the fee amount for a given target amount * * @param _sourceToken contract address of the source reserve token * @param _targetToken contract address of the target reserve token * @param _sourceWeight source reserve token weight * @param _targetWeight target reserve token weight * @param _externalRate external rate of 1 primary token in secondary tokens * @param _targetExternalWeight target reserve token weight based on external rate * @param _targetAmount target amount * * @return fee amount */ function calculateFee( IERC20Token _sourceToken, IERC20Token _targetToken, uint32 _sourceWeight, uint32 _targetWeight, Fraction memory _externalRate, uint32 _targetExternalWeight, uint256 _targetAmount) internal view returns (uint256) { // get the external rate of 1 source token in target tokens Fraction memory targetExternalRate; if (_targetToken == primaryReserveToken) { (targetExternalRate.n, targetExternalRate.d) = (_externalRate.n, _externalRate.d); } else { (targetExternalRate.n, targetExternalRate.d) = (_externalRate.d, _externalRate.n); } // get the token pool rate Fraction memory currentRate = tokensRate(_targetToken, _sourceToken, _targetWeight, _sourceWeight); if (compareRates(currentRate, targetExternalRate) < 0) { uint256 lo = currentRate.n.mul(targetExternalRate.d); uint256 hi = targetExternalRate.n.mul(currentRate.d); (lo, hi) = reducedRatio(hi - lo, hi, MAX_RATE_FACTOR_LOWER_BOUND); // apply the high fee only if the ratio between the effective weight and the external (target) weight is below the high fee upper bound uint32 feeFactor; if (uint256(_targetWeight).mul(PPM_RESOLUTION) < uint256(_targetExternalWeight).mul(HIGH_FEE_UPPER_BOUND)) { feeFactor = highFeeFactor; } else { feeFactor = lowFeeFactor; } return _targetAmount.mul(lo).mul(feeFactor).div(hi.mul(PPM_RESOLUTION)); } return 0; } /** * @dev calculates the deficit in the pool (in secondary reserve token amount) * * @param _externalRate external rate of 1 primary token in secondary tokens * * @return the deficit in the pool */ function calculateDeficit(Fraction memory _externalRate) internal view returns (uint256) { IERC20Token primaryReserveTokenLocal = primaryReserveToken; // gas optimization IERC20Token secondaryReserveTokenLocal = secondaryReserveToken; // gas optimization // get the amount of primary balances in secondary tokens using the external rate uint256 primaryBalanceInSecondary = reserves[primaryReserveTokenLocal].balance.mul(_externalRate.n).div(_externalRate.d); uint256 primaryStakedInSecondary = stakedBalances[primaryReserveTokenLocal].mul(_externalRate.n).div(_externalRate.d); // if the total balance is lower than the total staked balance, return the delta uint256 totalBalance = primaryBalanceInSecondary.add(reserves[secondaryReserveTokenLocal].balance); uint256 totalStaked = primaryStakedInSecondary.add(stakedBalances[secondaryReserveTokenLocal]); if (totalBalance < totalStaked) { return totalStaked - totalBalance; } return 0; } /** * @dev updates the weights based on the effective weights calculation if needed * and returns the target amount and fee * * @param _sourceToken source ERC20 token * @param _targetToken target ERC20 token * @param _amount amount of tokens to convert (in units of the source token) * @param _externalRate external rate of 1 primary token in secondary tokens * @param _externalRateUpdateTime external rate update time * * @return expected target amount * @return expected fee */ function prepareConversion( IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount, Fraction memory _externalRate, uint256 _externalRateUpdateTime) internal returns (uint256, uint256) { // get the source token effective / external weights (uint32 effectiveSourceReserveWeight, uint32 externalSourceReserveWeight) = effectiveAndExternalPrimaryWeight(_externalRate, _externalRateUpdateTime); if (_targetToken == primaryReserveToken) { effectiveSourceReserveWeight = inverseWeight(effectiveSourceReserveWeight); externalSourceReserveWeight = inverseWeight(externalSourceReserveWeight); } // check if the weights need to be updated if (reserves[_sourceToken].weight != effectiveSourceReserveWeight) { // update the weights reserves[_sourceToken].weight = effectiveSourceReserveWeight; reserves[_targetToken].weight = inverseWeight(effectiveSourceReserveWeight); } // get expected target amount and fee return targetAmountAndFee( _sourceToken, _targetToken, effectiveSourceReserveWeight, inverseWeight(effectiveSourceReserveWeight), _externalRate, inverseWeight(externalSourceReserveWeight), _amount); } /** * @dev creates the converter's pool tokens * note that technically pool tokens can be created on deployment but gas limit * might get too high for a block, so creating them on first activation * */ function createPoolTokens() internal { IPoolTokensContainer container = IPoolTokensContainer(address(anchor)); ISmartToken[] memory poolTokens = container.poolTokens(); bool initialSetup = poolTokens.length == 0; uint256 reserveCount = reserveTokens.length; for (uint256 i = 0; i < reserveCount; i++) { ISmartToken reservePoolToken; if (initialSetup) { reservePoolToken = container.createToken(); } else { reservePoolToken = poolTokens[i]; } // cache the pool token address (gas optimization) reservesToPoolTokens[reserveTokens[i]] = reservePoolToken; poolTokensToReserves[reservePoolToken] = reserveTokens[i]; } } /** * @dev returns the effective primary reserve token weight * * @return effective primary reserve weight */ function effectivePrimaryWeight() internal view returns (uint32) { // get the external rate between the reserves along with its update time Fraction memory externalRate; uint256 externalRateUpdateTime; (externalRate.n, externalRate.d, externalRateUpdateTime) = priceOracle.latestRateAndUpdateTime(primaryReserveToken, secondaryReserveToken); (uint32 effectiveWeight,) = effectiveAndExternalPrimaryWeight(externalRate, externalRateUpdateTime); return effectiveWeight; } /** * @dev returns the effective and the external primary reserve token weights * * @param _externalRate external rate of 1 primary token in secondary tokens * @param _externalRateUpdateTime external rate update time * * @return effective primary reserve weight * @return external primary reserve weight */ function effectiveAndExternalPrimaryWeight(Fraction memory _externalRate, uint256 _externalRateUpdateTime) internal view returns (uint32, uint32) { // get the external rate primary reserve weight uint32 externalPrimaryReserveWeight = primaryWeightFromRate(_externalRate); // get the primary reserve weight IERC20Token primaryReserveTokenLocal = primaryReserveToken; // gas optimization uint32 primaryReserveWeight = reserves[primaryReserveTokenLocal].weight; // if the weights are already at their target, return current weights if (primaryReserveWeight == externalPrimaryReserveWeight) { return (primaryReserveWeight, externalPrimaryReserveWeight); } // get the elapsed time since the last conversion time and the external rate update time uint256 referenceTime = prevConversionTime; if (referenceTime < _externalRateUpdateTime) { referenceTime = _externalRateUpdateTime; } // limit the reference time by current time uint256 currentTime = time(); if (referenceTime > currentTime) { referenceTime = currentTime; } // if no time has passed since the reference time, return current weights (also ensures a single update per block) uint256 elapsedTime = currentTime - referenceTime; if (elapsedTime == 0) { return (primaryReserveWeight, externalPrimaryReserveWeight); } // find the token whose weight is lower than the target weight and get its pool rate - if it's // lower than external rate, update the weights Fraction memory poolRate = tokensRate( primaryReserveTokenLocal, secondaryReserveToken, primaryReserveWeight, inverseWeight(primaryReserveWeight)); bool updateWeights = false; if (primaryReserveWeight < externalPrimaryReserveWeight) { updateWeights = compareRates(poolRate, _externalRate) < 0; } else { updateWeights = compareRates(poolRate, _externalRate) > 0; } if (!updateWeights) { return (primaryReserveWeight, externalPrimaryReserveWeight); } // if the elapsed time since the reference rate is equal or larger than the propagation time, // the external rate should take full effect if (elapsedTime >= externalRatePropagationTime) { return (externalPrimaryReserveWeight, externalPrimaryReserveWeight); } // move the weights towards their target by the same proportion of elapsed time out of the rate propagation time primaryReserveWeight = uint32(weightedAverageIntegers( primaryReserveWeight, externalPrimaryReserveWeight, elapsedTime, externalRatePropagationTime)); return (primaryReserveWeight, externalPrimaryReserveWeight); } /** * @dev returns the current rate for add/remove liquidity rebalancing * only used to circumvent the `stack too deep` compiler error * * @return effective rate */ function rebalanceRate() private view returns (Fraction memory) { // if one of the balances is 0, return the external rate if (reserves[primaryReserveToken].balance == 0 || reserves[secondaryReserveToken].balance == 0) { Fraction memory externalRate; (externalRate.n, externalRate.d) = priceOracle.latestRate(primaryReserveToken, secondaryReserveToken); return externalRate; } // return the rate based on the current rate return tokensRate(primaryReserveToken, secondaryReserveToken, 0, 0); } /** * @dev updates the reserve weights based on the external rate */ function rebalance() private { // get the external rate Fraction memory externalRate; (externalRate.n, externalRate.d) = priceOracle.latestRate(primaryReserveToken, secondaryReserveToken); // rebalance the weights based on the external rate rebalance(externalRate); } /** * @dev updates the reserve weights based on the given rate * * @param _rate rate of 1 primary token in secondary tokens */ function rebalance(Fraction memory _rate) private { // get the new primary reserve weight uint256 a = amplifiedBalance(primaryReserveToken).mul(_rate.n); uint256 b = amplifiedBalance(secondaryReserveToken).mul(_rate.d); (uint256 x, uint256 y) = normalizedRatio(a, b, PPM_RESOLUTION); // update the reserve weights with the new values reserves[primaryReserveToken].weight = uint32(x); reserves[secondaryReserveToken].weight = uint32(y); } /** * @dev returns the amplified balance of a given reserve token * this version skips the input validation (gas optimization) * * @param _reserveToken reserve token address * * @return amplified balance */ function amplifiedBalance(IERC20Token _reserveToken) internal view returns (uint256) { return stakedBalances[_reserveToken].mul(amplificationFactor - 1).add(reserves[_reserveToken].balance); } /** * @dev returns the effective primary reserve weight based on the staked balance, current balance and given rate * * @param _rate rate of 1 primary token in secondary tokens * * @return primary reserve weight */ function primaryWeightFromRate(Fraction memory _rate) private view returns (uint32) { uint256 a = stakedBalances[primaryReserveToken].mul(_rate.n); uint256 b = stakedBalances[secondaryReserveToken].mul(_rate.d); (uint256 x,) = normalizedRatio(a, b, PPM_RESOLUTION); return uint32(x); } /** * @dev returns the effective rate based on the staked balance, current balance and given primary reserve weight * * @param _primaryReserveWeight primary reserve weight * * @return effective rate of 1 primary token in secondary tokens */ function rateFromPrimaryWeight(uint32 _primaryReserveWeight) private view returns (Fraction memory) { uint256 n = stakedBalances[secondaryReserveToken].mul(_primaryReserveWeight); uint256 d = stakedBalances[primaryReserveToken].mul(inverseWeight(_primaryReserveWeight)); (n, d) = reducedRatio(n, d, MAX_RATE_FACTOR_LOWER_BOUND); return Fraction(n, d); } /** * @dev calculates and returns the rate between two reserve tokens * * @param _token1 contract address of the token to calculate the rate of one unit of * @param _token2 contract address of the token to calculate the rate of one `_token1` unit in * @param _token1Weight reserve weight of token1 * @param _token2Weight reserve weight of token2 * * @return rate */ function tokensRate(IERC20Token _token1, IERC20Token _token2, uint32 _token1Weight, uint32 _token2Weight) private view returns (Fraction memory) { if (_token1Weight == 0) { _token1Weight = reserves[_token1].weight; } if (_token2Weight == 0) { _token2Weight = inverseWeight(_token1Weight); } uint256 n = amplifiedBalance(_token2).mul(_token1Weight); uint256 d = amplifiedBalance(_token1).mul(_token2Weight); (n, d) = reducedRatio(n, d, MAX_RATE_FACTOR_LOWER_BOUND); return Fraction(n, d); } /** * @dev dispatches rate events for both reserve tokens and for the target pool token * only used to circumvent the `stack too deep` compiler error * * @param _sourceToken contract address of the source reserve token * @param _targetToken contract address of the target reserve token * @param _sourceWeight source reserve token weight * @param _targetWeight target reserve token weight */ function dispatchRateEvents(IERC20Token _sourceToken, IERC20Token _targetToken, uint32 _sourceWeight, uint32 _targetWeight) private { dispatchTokenRateUpdateEvent(_sourceToken, _targetToken, _sourceWeight, _targetWeight); // dispatch the `TokenRateUpdate` event for the pool token // the target reserve pool token rate is the only one that's affected // by conversions since conversion fees are applied to the target reserve ISmartToken targetPoolToken = poolToken(_targetToken); uint256 targetPoolTokenSupply = targetPoolToken.totalSupply(); dispatchPoolTokenRateUpdateEvent(targetPoolToken, targetPoolTokenSupply, _targetToken); } /** * @dev dispatches token rate update event * only used to circumvent the `stack too deep` compiler error * * @param _token1 contract address of the token to calculate the rate of one unit of * @param _token2 contract address of the token to calculate the rate of one `_token1` unit in * @param _token1Weight reserve weight of token1 * @param _token2Weight reserve weight of token2 */ function dispatchTokenRateUpdateEvent(IERC20Token _token1, IERC20Token _token2, uint32 _token1Weight, uint32 _token2Weight) private { // dispatch token rate update event Fraction memory rate = tokensRate(_token1, _token2, _token1Weight, _token2Weight); emit TokenRateUpdate(_token1, _token2, rate.n, rate.d); } /** * @dev dispatches the `TokenRateUpdate` for the pool token * only used to circumvent the `stack too deep` compiler error * * @param _poolToken address of the pool token * @param _poolTokenSupply total pool token supply * @param _reserveToken address of the reserve token */ function dispatchPoolTokenRateUpdateEvent(ISmartToken _poolToken, uint256 _poolTokenSupply, IERC20Token _reserveToken) private { emit TokenRateUpdate(_poolToken, _reserveToken, stakedBalances[_reserveToken], _poolTokenSupply); } // utilities /** * @dev returns the inverse weight for a given weight * * @param _weight reserve token weight * * @return reserve weight */ function inverseWeight(uint32 _weight) internal pure returns (uint32) { return PPM_RESOLUTION - _weight; } /** * @dev returns the current time */ function time() internal virtual view returns (uint256) { return now; } /** * @dev computes "scale * a / (a + b)" and "scale * b / (a + b)". */ function normalizedRatio(uint256 _a, uint256 _b, uint256 _scale) internal pure returns (uint256, uint256) { if (_a == _b) return (_scale / 2, _scale / 2); if (_a < _b) return accurateRatio(_a, _b, _scale); (uint256 y, uint256 x) = accurateRatio(_b, _a, _scale); return (x, y); } /** * @dev computes "scale * a / (a + b)" and "scale * b / (a + b)", assuming that "a < b". */ function accurateRatio(uint256 _a, uint256 _b, uint256 _scale) internal pure returns (uint256, uint256) { uint256 maxVal = uint256(-1) / _scale; if (_a > maxVal) { uint256 c = _a / (maxVal + 1) + 1; _a /= c; _b /= c; } uint256 x = roundDiv(_a * _scale, _a.add(_b)); uint256 y = _scale - x; return (x, y); } /** * @dev computes a reduced-scalar ratio * * @param _n ratio numerator * @param _d ratio denominator * @param _max maximum desired scalar * * @return ratio's numerator and denominator */ function reducedRatio(uint256 _n, uint256 _d, uint256 _max) internal pure returns (uint256, uint256) { if (_n > _max || _d > _max) return normalizedRatio(_n, _d, _max); return (_n, _d); } /** * @dev computes the nearest integer to a given quotient without overflowing or underflowing. */ function roundDiv(uint256 _n, uint256 _d) internal pure returns (uint256) { return _n / _d + _n % _d / (_d - _d / 2); } /** * @dev calculates the weighted-average of two integers * * @param _x first integer * @param _y second integer * @param _n factor numerator * @param _d factor denominator * * @return the weighted-average of the given integers */ function weightedAverageIntegers(uint256 _x, uint256 _y, uint256 _n, uint256 _d) internal pure returns (uint256) { return _x.mul(_d).add(_y.mul(_n)).sub(_x.mul(_n)).div(_d); } /** * @dev compares two rates * * @param _rate1 first rate to compare * @param _rate2 second rate to compare * * @return `-1` if `_rate1` is lower than `_rate2`, `1` if `_rate1` is higher than `_rate2`, 0 if the rates are identical */ function compareRates(Fraction memory _rate1, Fraction memory _rate2) internal pure returns (int8) { uint256 x = _rate1.n.mul(_rate2.d); uint256 y = _rate2.n.mul(_rate1.d); if (x < y) return -1; if (x > y) return 1; return 0; } }
creates the converter's pool tokens note that technically pool tokens can be created on deployment but gas limit might get too high for a block, so creating them on first activation/
function createPoolTokens() internal { IPoolTokensContainer container = IPoolTokensContainer(address(anchor)); ISmartToken[] memory poolTokens = container.poolTokens(); bool initialSetup = poolTokens.length == 0; uint256 reserveCount = reserveTokens.length; for (uint256 i = 0; i < reserveCount; i++) { ISmartToken reservePoolToken; if (initialSetup) { reservePoolToken = container.createToken(); } else { reservePoolToken = poolTokens[i]; } poolTokensToReserves[reservePoolToken] = reserveTokens[i]; } }
1,066,825
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.2.0-solc-0.7/contracts/utils/EnumerableSet.sol // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; 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; } function _ADD852(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING if (!_CONTAINS492(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; } } function _REMOVE675(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING // 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; } } function _CONTAINS492(Set storage set, bytes32 value) private view returns (bool) { //inject NONSTANDARD NAMING return set._indexes[value] != 0; } function _LENGTH742(Set storage set) private view returns (uint256) { //inject NONSTANDARD NAMING return set._values.length; } function _AT360(Set storage set, uint256 index) private view returns (bytes32) { //inject NONSTANDARD NAMING require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } function ADD146(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD852(set._inner, bytes32(uint256(value))); } function REMOVE620(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE675(set._inner, bytes32(uint256(value))); } function CONTAINS72(AddressSet storage set, address value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS492(set._inner, bytes32(uint256(value))); } function LENGTH675(AddressSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH742(set._inner); } function AT889(AddressSet storage set, uint256 index) internal view returns (address) { //inject NONSTANDARD NAMING return address(uint256(_AT360(set._inner, index))); } // UintSet struct UintSet { Set _inner; } function ADD146(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD852(set._inner, bytes32(value)); } function REMOVE620(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE675(set._inner, bytes32(value)); } function CONTAINS72(UintSet storage set, uint256 value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS492(set._inner, bytes32(value)); } function LENGTH675(UintSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH742(set._inner); } function AT889(UintSet storage set, uint256 index) internal view returns (uint256) { //inject NONSTANDARD NAMING return uint256(_AT360(set._inner, index)); } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.2.0-solc-0.7/contracts/GSN/Context.sol // pragma solidity ^0.7.0; abstract contract Context { function _MSGSENDER914() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA708() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.2.0-solc-0.7/contracts/access/AccessControl.sol // pragma solidity ^0.7.0; 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_role935 = 0x00; //inject NONSTANDARD NAMING event ROLEADMINCHANGED723(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); //inject NONSTANDARD NAMING event ROLEGRANTED103(bytes32 indexed role, address indexed account, address indexed sender); //inject NONSTANDARD NAMING event ROLEREVOKED950(bytes32 indexed role, address indexed account, address indexed sender); //inject NONSTANDARD NAMING function HASROLE117(bytes32 role, address account) public view returns (bool) { //inject NONSTANDARD NAMING return _roles[role].members.CONTAINS72(account); } function GETROLEMEMBERCOUNT773(bytes32 role) public view returns (uint256) { //inject NONSTANDARD NAMING return _roles[role].members.LENGTH675(); } function GETROLEMEMBER894(bytes32 role, uint256 index) public view returns (address) { //inject NONSTANDARD NAMING return _roles[role].members.AT889(index); } function GETROLEADMIN738(bytes32 role) public view returns (bytes32) { //inject NONSTANDARD NAMING return _roles[role].adminRole; } function GRANTROLE962(bytes32 role, address account) public virtual { //inject NONSTANDARD NAMING require(HASROLE117(_roles[role].adminRole, _MSGSENDER914()), "AccessControl: sender must be an admin to grant"); _GRANTROLE886(role, account); } function REVOKEROLE159(bytes32 role, address account) public virtual { //inject NONSTANDARD NAMING require(HASROLE117(_roles[role].adminRole, _MSGSENDER914()), "AccessControl: sender must be an admin to revoke"); _REVOKEROLE39(role, account); } function RENOUNCEROLE17(bytes32 role, address account) public virtual { //inject NONSTANDARD NAMING require(account == _MSGSENDER914(), "AccessControl: can only renounce roles for self"); _REVOKEROLE39(role, account); } function _SETUPROLE488(bytes32 role, address account) internal virtual { //inject NONSTANDARD NAMING _GRANTROLE886(role, account); } function _SETROLEADMIN697(bytes32 role, bytes32 adminRole) internal virtual { //inject NONSTANDARD NAMING emit ROLEADMINCHANGED723(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _GRANTROLE886(bytes32 role, address account) private { //inject NONSTANDARD NAMING if (_roles[role].members.ADD146(account)) { emit ROLEGRANTED103(role, account, _MSGSENDER914()); } } function _REVOKEROLE39(bytes32 role, address account) private { //inject NONSTANDARD NAMING if (_roles[role].members.REMOVE620(account)) { emit ROLEREVOKED950(role, account, _MSGSENDER914()); } } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.2.0-solc-0.7/contracts/utils/Address.sol // pragma solidity ^0.7.0; library Address { function ISCONTRACT647(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // 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); } function SENDVALUE238(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING 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"); } function FUNCTIONCALL669(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALL669(target, data, "Address: low-level call failed"); } function FUNCTIONCALL669(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING return _FUNCTIONCALLWITHVALUE523(target, data, 0, errorMessage); } function FUNCTIONCALLWITHVALUE570(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALLWITHVALUE570(target, data, value, "Address: low-level call with value failed"); } function FUNCTIONCALLWITHVALUE570(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING require(address(this).balance >= value, "Address: insufficient balance for call"); return _FUNCTIONCALLWITHVALUE523(target, data, value, errorMessage); } function _FUNCTIONCALLWITHVALUE523(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING require(ISCONTRACT647(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); } } } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.2.0-solc-0.7/contracts/math/SafeMath.sol // pragma solidity ^0.7.0; library SafeMath { function ADD146(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB570(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB570(a, b, "SafeMath: subtraction overflow"); } function SUB570(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL634(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // 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; } function DIV640(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV640(a, b, "SafeMath: division by zero"); } function DIV640(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING 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; } function MOD654(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD654(a, b, "SafeMath: modulo by zero"); } function MOD654(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.2.0-solc-0.7/contracts/token/ERC20/IERC20.sol // pragma solidity ^0.7.0; interface IERC20 { function TOTALSUPPLY217() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF756(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER622(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE863(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE47(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM568(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER456(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL815(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.2.0-solc-0.7/contracts/token/ERC20/ERC20.sol // pragma solidity ^0.7.0; contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol) { _name = name; _symbol = symbol; _decimals = 18; } function NAME91() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL382() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS96() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } function TOTALSUPPLY217() public view override returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF756(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER622(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER619(_MSGSENDER914(), recipient, amount); return true; } function ALLOWANCE863(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE47(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _APPROVE737(_MSGSENDER914(), spender, amount); return true; } function TRANSFERFROM568(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER619(sender, recipient, amount); _APPROVE737(sender, _MSGSENDER914(), _allowances[sender][_MSGSENDER914()].SUB570(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE53(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE737(_MSGSENDER914(), spender, _allowances[_MSGSENDER914()][spender].ADD146(addedValue)); return true; } function DECREASEALLOWANCE706(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE737(_MSGSENDER914(), spender, _allowances[_MSGSENDER914()][spender].SUB570(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER619(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _BEFORETOKENTRANSFER428(sender, recipient, amount); _balances[sender] = _balances[sender].SUB570(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD146(amount); emit TRANSFER456(sender, recipient, amount); } function _MINT727(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _BEFORETOKENTRANSFER428(address(0), account, amount); _totalSupply = _totalSupply.ADD146(amount); _balances[account] = _balances[account].ADD146(amount); emit TRANSFER456(address(0), account, amount); } function _BURN562(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _BEFORETOKENTRANSFER428(account, address(0), amount); _balances[account] = _balances[account].SUB570(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB570(amount); emit TRANSFER456(account, address(0), amount); } function _APPROVE737(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING 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 APPROVAL815(owner, spender, amount); } function _SETUPDECIMALS703(uint8 decimals_) internal { //inject NONSTANDARD NAMING _decimals = decimals_; } function _BEFORETOKENTRANSFER428(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING } abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; function BURN447(uint256 amount) public virtual { //inject NONSTANDARD NAMING _BURN562(_MSGSENDER914(), amount); } function BURNFROM566(address account, uint256 amount) public virtual { //inject NONSTANDARD NAMING uint256 decreasedAllowance = ALLOWANCE863(account, _MSGSENDER914()).SUB570(amount, "ERC20: burn amount exceeds allowance"); _APPROVE737(account, _MSGSENDER914(), decreasedAllowance); _BURN562(account, amount); } } // File: browser/TokenERC20.sol // pragma solidity ^0.7; contract Token is ERC20Burnable, AccessControl { bytes32 public constant minter_role392 = keccak256("MINTER_ROLE"); //inject NONSTANDARD NAMING bytes32 public constant burner_role509 = keccak256("BURNER_ROLE"); //inject NONSTANDARD NAMING constructor (string memory name, string memory symbol) ERC20(name, symbol) { _SETUPROLE488(default_admin_role935, _MSGSENDER914()); _SETUPROLE488(minter_role392, _MSGSENDER914()); _SETUPROLE488(burner_role509, _MSGSENDER914()); } function MINT678(address to, uint256 amount) public { //inject NONSTANDARD NAMING require(HASROLE117(minter_role392, _MSGSENDER914()), "Caller is not a minter"); _MINT727(to, amount); } function BURN447(uint256 amount) public override { //inject NONSTANDARD NAMING require(HASROLE117(burner_role509, _MSGSENDER914()), "Caller is not a burner"); super.BURN447(amount); } function BURNFROM566(address account, uint256 amount) public override { //inject NONSTANDARD NAMING require(HASROLE117(burner_role509, _MSGSENDER914()), "Caller is not a burner"); super.BURNFROM566(account, amount); } } interface IERC20Ops { function MINT678(address, uint256) external; //inject NONSTANDARD NAMING function BURNFROM566(address, uint256) external; //inject NONSTANDARD NAMING function DECIMALS96() external view returns (uint8); //inject NONSTANDARD NAMING } contract TokenSwap is AccessControl { bytes32 public constant whitelisted497 = keccak256("WHITELISTED"); //inject NONSTANDARD NAMING address public oldToken; address public newToken; uint8 public decimalsFactor; bool public positiveDecimalsFactor; constructor(address _oldToken, address _newToken){ oldToken = _oldToken; newToken = _newToken; uint8 oldTokenDecimals = IERC20Ops(oldToken).DECIMALS96(); uint8 newTokenDecimals = IERC20Ops(newToken).DECIMALS96(); if (newTokenDecimals >= oldTokenDecimals){ decimalsFactor = newTokenDecimals - oldTokenDecimals; positiveDecimalsFactor = true; } else { decimalsFactor = oldTokenDecimals - newTokenDecimals; positiveDecimalsFactor = false; } _SETUPROLE488(default_admin_role935, _MSGSENDER914()); _SETUPROLE488(whitelisted497, _MSGSENDER914()); } function WHITELISTED831(address addr) public view returns (bool) { //inject NONSTANDARD NAMING return HASROLE117(whitelisted497, addr); } function WHITELISTADD908(address[] memory addrs) public { //inject NONSTANDARD NAMING require(HASROLE117(default_admin_role935, _MSGSENDER914()), "Caller is not admin"); for (uint256 i = 0; i < addrs.length; i++){ GRANTROLE962(whitelisted497, addrs[i]); } } function WHITELISTREMOVE906(address[] memory addrs) public { //inject NONSTANDARD NAMING require(HASROLE117(default_admin_role935, _MSGSENDER914()), "Caller is not admin"); for (uint256 i = 0; i < addrs.length; i++){ REVOKEROLE159(whitelisted497, addrs[i]); } } function SWAP530(uint256 val) public { //inject NONSTANDARD NAMING require(HASROLE117(whitelisted497, _MSGSENDER914()), "Caller is not whitelisted"); IERC20Ops(oldToken).BURNFROM566(_MSGSENDER914(), val); if (positiveDecimalsFactor) IERC20Ops(newToken).MINT678(_MSGSENDER914(), val * (10 ** decimalsFactor)); else IERC20Ops(newToken).MINT678(_MSGSENDER914(), val / (10 ** decimalsFactor)); } }
inject NONSTANDARD NAMING
function GETROLEMEMBER894(bytes32 role, uint256 index) public view returns (address) {
5,351,532
./full_match/3/0xcd8b28F7ED4f291bC69435dE1c8bcC39877F96F0/sources/home/jenja/NFT_ERC-721/contracts/STBU_Token.sol
Transfer tokens from one address to another _from address The address which you want to send tokens from _to address The address which you want to transfer to _amount uint256 the amount of tokens to be transferred/
function transferFrom(address _from, address _to, uint256 _amount) public override returns (bool success) { require(_from != msg.sender, "Cannot transfer from self, use transfer function instead"); require(_from != address(this) && _to != address(this), "Cannot transfer from or to Contract"); require(_to != address(0), "Cannot transfer to 0x0"); require(balances[_from] >= _amount, "Not enough balance to transfer from"); require(allowed[_from][msg.sender] >= _amount, "Not enough allowance to transfer from"); require(_amount > 0 && balances[_to].add(_amount) > balances[_to], "Amount must be > 0 to transfer from"); requireWithinLockupRange(_from, _amount); balances[_from] = balances[_from].sub(_amount); balances[_to] = balances[_to].add(_amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); emit Transfer(_from, _to, _amount); return true; }
8,268,694
// SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./ActionGuards.sol"; import "../../internal/nToken/nTokenHandler.sol"; import "../../internal/nToken/nTokenSupply.sol"; import "../../internal/nToken/nTokenCalculations.sol"; import "../../internal/markets/AssetRate.sol"; import "../../internal/balances/BalanceHandler.sol"; import "../../internal/balances/Incentives.sol"; import "../../math/SafeInt256.sol"; import "../../global/StorageLayoutV1.sol"; import "../../external/FreeCollateralExternal.sol"; import "../../../interfaces/notional/nTokenERC20.sol"; import "@openzeppelin/contracts/utils/SafeCast.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract nTokenAction is StorageLayoutV1, nTokenERC20, ActionGuards { using BalanceHandler for BalanceState; using AssetRate for AssetRateParameters; using AccountContextHandler for AccountContext; using nTokenHandler for nTokenPortfolio; using SafeInt256 for int256; using SafeMath for uint256; /// @notice Total number of tokens in circulation /// @param nTokenAddress The address of the nToken /// @return totalSupply number of tokens held function nTokenTotalSupply(address nTokenAddress) external view override returns (uint256 totalSupply) { // prettier-ignore ( totalSupply, /* accumulatedNOTEPerNToken */, /* lastAccumulatedTime */ ) = nTokenSupply.getStoredNTokenSupplyFactors(nTokenAddress); } /// @notice Get the number of tokens held by the `account` /// @param account The address of the account to get the balance of /// @return The number of tokens held function nTokenBalanceOf(uint16 currencyId, address account) external view override returns (uint256) { // prettier-ignore ( /* int cashBalance */, int256 nTokenBalance, /* uint lastClaimTime */, /* uint accountIncentiveDebt */ ) = BalanceHandler.getBalanceStorage(account, currencyId); require(nTokenBalance >= 0); // dev: negative nToken balance return uint256(nTokenBalance); } /// @notice Get the number of tokens `spender` is approved to spend on behalf of `account` /// @param currencyId Currency id of the nToken account /// @param tokenHolder The address of the account holding the funds /// @param spender The address of the account spending the funds /// @return The number of tokens approved function nTokenTransferAllowance( uint16 currencyId, address tokenHolder, address spender ) external view override returns (uint256) { // The specific allowance overrides the blanket whitelist uint256 allowance = nTokenAllowance[tokenHolder][spender][currencyId]; if (allowance > 0) { return allowance; } else { return nTokenWhitelist[tokenHolder][spender]; } } /// @notice Approve `spender` to transfer up to `amount` from `src` /// @dev auth:nTokenProxy /// @param currencyId Currency id of the nToken account /// @param tokenHolder The address of the account holding the funds /// @param spender The address of the account which may transfer tokens /// @param amount The number of tokens that are approved (2^256-1 means infinite) /// @return Whether or not the approval succeeded function nTokenTransferApprove( uint16 currencyId, address tokenHolder, address spender, uint256 amount ) external override returns (bool) { address nTokenAddress = nTokenHandler.nTokenAddress(currencyId); require(msg.sender == nTokenAddress, "Unauthorized caller"); require(tokenHolder != address(0)); nTokenAllowance[tokenHolder][spender][currencyId] = amount; return true; } /// @notice Transfer `amount` tokens from `msg.sender` to `dst` /// @dev auth:nTokenProxy /// @param from The address of the destination account /// @param to The address of the destination account /// @param amount The number of tokens to transfer /// @return Whether or not the transfer succeeded function nTokenTransfer( uint16 currencyId, address from, address to, uint256 amount ) external override returns (bool) { address nTokenAddress = nTokenHandler.nTokenAddress(currencyId); require(msg.sender == nTokenAddress, "Unauthorized caller"); require(from != to, "Cannot transfer to self"); requireValidAccount(to); return _transfer(currencyId, from, to, amount); } /// @notice Transfer `amount` tokens from `src` to `dst` /// @dev auth:nTokenProxy /// @param currencyId Currency id of the nToken /// @param spender The address of the original caller /// @param from The address of the source account /// @param to The address of the destination account /// @param amount The number of tokens to transfer /// @return Whether or not the transfer succeeded function nTokenTransferFrom( uint16 currencyId, address spender, address from, address to, uint256 amount ) external override returns (bool) { address nTokenAddress = nTokenHandler.nTokenAddress(currencyId); require(msg.sender == nTokenAddress, "Unauthorized caller"); require(from != to, "Cannot transfer to self"); requireValidAccount(to); uint256 allowance = nTokenAllowance[from][spender][currencyId]; if (allowance > 0) { // This is the specific allowance for the nToken. require(allowance >= amount, "Insufficient allowance"); // Overflow checked above nTokenAllowance[from][spender][currencyId] = allowance - amount; } else { // This whitelist allowance works across all nTokens allowance = nTokenWhitelist[from][spender]; require(allowance >= amount, "Insufficient allowance"); // Overflow checked above nTokenWhitelist[from][spender] = allowance - amount; } return _transfer(currencyId, from, to, amount); } /// @notice Will approve all nToken transfers to the specific sender. This is used for simplifying UX, a user can approve /// all token transfers to an external exchange or protocol in a single txn. This must be called directly /// on the Notional contract, not available via the ERC20 proxy. /// @dev emit:Approval /// @dev auth:msg.sender /// @param spender The address of the account which may transfer tokens /// @param amount The number of tokens that are approved /// @return Whether or not the approval succeeded function nTokenTransferApproveAll(address spender, uint256 amount) external override returns (bool) { nTokenWhitelist[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /// @notice Claims incentives accrued on all nToken balances and transfers them to the msg.sender /// @dev auth:msg.sender /// @return Total amount of incentives claimed function nTokenClaimIncentives() external override returns (uint256) { address account = msg.sender; AccountContext memory accountContext = AccountContextHandler.getAccountContext(account); uint256 totalIncentivesClaimed = 0; BalanceState memory balanceState; if (accountContext.isBitmapEnabled()) { balanceState.loadBalanceState(account, accountContext.bitmapCurrencyId, accountContext); if (balanceState.storedNTokenBalance > 0) { // balance state is updated inside claim incentives manual totalIncentivesClaimed = balanceState.claimIncentivesManual(account); } } bytes18 currencies = accountContext.activeCurrencies; while (currencies != 0) { uint16 currencyId = uint16(bytes2(currencies) & Constants.UNMASK_FLAGS); balanceState.loadBalanceState(account, currencyId, accountContext); if (balanceState.storedNTokenBalance > 0) { // balance state is updated inside claim incentives manual totalIncentivesClaimed = totalIncentivesClaimed .add(balanceState.claimIncentivesManual(account)); } currencies = currencies << 16; } // NOTE: no need to set account context after claiming incentives. No currencies // or fCash assets have been added or changed. return totalIncentivesClaimed; } /// @notice Returns the present value of the nToken's assets denominated in asset tokens function nTokenPresentValueAssetDenominated(uint16 currencyId) external view override returns (int256) { // prettier-ignore ( int256 totalAssetPV, /* portfolio */ ) = _getNTokenPV(currencyId); return totalAssetPV; } /// @notice Returns the present value of the nToken's assets denominated in underlying function nTokenPresentValueUnderlyingDenominated(uint16 currencyId) external view override returns (int256) { (int256 totalAssetPV, nTokenPortfolio memory nToken) = _getNTokenPV(currencyId); return nToken.cashGroup.assetRate.convertToUnderlying(totalAssetPV); } function _getNTokenPV(uint16 currencyId) private view returns (int256, nTokenPortfolio memory) { uint256 blockTime = block.timestamp; nTokenPortfolio memory nToken; nToken.loadNTokenPortfolioView(currencyId); int256 totalAssetPV = nTokenCalculations.getNTokenAssetPV(nToken, blockTime); return (totalAssetPV, nToken); } /// @notice Transferring tokens will also claim incentives at the same time function _transfer( uint16 currencyId, address sender, address recipient, uint256 amount ) internal returns (bool) { // This prevents amountInt from being negative int256 amountInt = SafeCast.toInt256(amount); AccountContext memory senderContext = AccountContextHandler.getAccountContext(sender); // If sender has debt then we will check free collateral which will revert if we have not // settled assets first. To prevent this we settle sender context if required. if (senderContext.mustSettleAssets()) { senderContext = SettleAssetsExternal.settleAccount(sender, senderContext); } BalanceState memory senderBalance; senderBalance.loadBalanceState(sender, currencyId, senderContext); senderBalance.netNTokenTransfer = amountInt.neg(); senderBalance.finalize(sender, senderContext, false); senderContext.setAccountContext(sender); AccountContext memory recipientContext = AccountContextHandler.getAccountContext(recipient); BalanceState memory recipientBalance; recipientBalance.loadBalanceState(recipient, currencyId, recipientContext); recipientBalance.netNTokenTransfer = amountInt; recipientBalance.finalize(recipient, recipientContext, false); recipientContext.setAccountContext(recipient); // nTokens are used as collateral so we have to check the free collateral when we transfer. Only the // sender needs a free collateral check, the receiver's net free collateral position will only increase if (senderContext.hasDebt != 0x00) { FreeCollateralExternal.checkFreeCollateralAndRevert(sender); } return true; } /// @notice Get a list of deployed library addresses (sorted by library name) function getLibInfo() external view returns (address, address, address) { return ( address(FreeCollateralExternal), address(MigrateIncentives), address(SettleAssetsExternal) ); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../global/StorageLayoutV1.sol"; import "../../internal/nToken/nTokenHandler.sol"; abstract contract ActionGuards is StorageLayoutV1 { uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; function initializeReentrancyGuard() internal { require(reentrancyStatus == 0); // Initialize the guard to a non-zero value, see the OZ reentrancy guard // description for why this is more gas efficient: // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol reentrancyStatus = _NOT_ENTERED; } modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(reentrancyStatus != _ENTERED, "Reentrant call"); // Any calls to nonReentrant after this point will fail reentrancyStatus = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) reentrancyStatus = _NOT_ENTERED; } // These accounts cannot receive deposits, transfers, fCash or any other // types of value transfers. function requireValidAccount(address account) internal view { require(account != Constants.RESERVE); // Reserve address is address(0) require(account != address(this)); ( uint256 isNToken, /* incentiveAnnualEmissionRate */, /* lastInitializedTime */, /* assetArrayLength */, /* parameters */ ) = nTokenHandler.getNTokenContext(account); require(isNToken == 0); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./nTokenSupply.sol"; import "../markets/CashGroup.sol"; import "../markets/AssetRate.sol"; import "../portfolio/PortfolioHandler.sol"; import "../balances/BalanceHandler.sol"; import "../../global/LibStorage.sol"; import "../../math/SafeInt256.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library nTokenHandler { using SafeInt256 for int256; /// @dev Mirror of the value in LibStorage, solidity compiler does not allow assigning /// two constants to each other. uint256 private constant NUM_NTOKEN_MARKET_FACTORS = 14; /// @notice Returns an account context object that is specific to nTokens. function getNTokenContext(address tokenAddress) internal view returns ( uint16 currencyId, uint256 incentiveAnnualEmissionRate, uint256 lastInitializedTime, uint8 assetArrayLength, bytes5 parameters ) { mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; currencyId = context.currencyId; incentiveAnnualEmissionRate = context.incentiveAnnualEmissionRate; lastInitializedTime = context.lastInitializedTime; assetArrayLength = context.assetArrayLength; parameters = context.nTokenParameters; } /// @notice Returns the nToken token address for a given currency function nTokenAddress(uint256 currencyId) internal view returns (address tokenAddress) { mapping(uint256 => address) storage store = LibStorage.getNTokenAddressStorage(); return store[currencyId]; } /// @notice Called by governance to set the nToken token address and its reverse lookup. Cannot be /// reset once this is set. function setNTokenAddress(uint16 currencyId, address tokenAddress) internal { mapping(uint256 => address) storage addressStore = LibStorage.getNTokenAddressStorage(); require(addressStore[currencyId] == address(0), "PT: token address exists"); mapping(address => nTokenContext) storage contextStore = LibStorage.getNTokenContextStorage(); nTokenContext storage context = contextStore[tokenAddress]; require(context.currencyId == 0, "PT: currency exists"); // This will initialize all other context slots to zero context.currencyId = currencyId; addressStore[currencyId] = tokenAddress; } /// @notice Set nToken token collateral parameters function setNTokenCollateralParameters( address tokenAddress, uint8 residualPurchaseIncentive10BPS, uint8 pvHaircutPercentage, uint8 residualPurchaseTimeBufferHours, uint8 cashWithholdingBuffer10BPS, uint8 liquidationHaircutPercentage ) internal { mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; require(liquidationHaircutPercentage <= Constants.PERCENTAGE_DECIMALS, "Invalid haircut"); // The pv haircut percentage must be less than the liquidation percentage or else liquidators will not // get profit for liquidating nToken. require(pvHaircutPercentage < liquidationHaircutPercentage, "Invalid pv haircut"); // Ensure that the cash withholding buffer is greater than the residual purchase incentive or // the nToken may not have enough cash to pay accounts to buy its negative ifCash require(residualPurchaseIncentive10BPS <= cashWithholdingBuffer10BPS, "Invalid discounts"); bytes5 parameters = (bytes5(uint40(residualPurchaseIncentive10BPS)) | (bytes5(uint40(pvHaircutPercentage)) << 8) | (bytes5(uint40(residualPurchaseTimeBufferHours)) << 16) | (bytes5(uint40(cashWithholdingBuffer10BPS)) << 24) | (bytes5(uint40(liquidationHaircutPercentage)) << 32)); // Set the parameters context.nTokenParameters = parameters; } /// @notice Sets a secondary rewarder contract on an nToken so that incentives can come from a different /// contract, aside from the native NOTE token incentives. function setSecondaryRewarder( uint16 currencyId, IRewarder rewarder ) internal { address tokenAddress = nTokenAddress(currencyId); // nToken must exist for a secondary rewarder require(tokenAddress != address(0)); mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; // Setting the rewarder to address(0) will disable it. We use a context setting here so that // we can save a storage read before getting the rewarder context.hasSecondaryRewarder = (address(rewarder) != address(0)); LibStorage.getSecondaryIncentiveRewarder()[tokenAddress] = rewarder; } /// @notice Returns the secondary rewarder if it is set function getSecondaryRewarder(address tokenAddress) internal view returns (IRewarder) { mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; if (context.hasSecondaryRewarder) { return LibStorage.getSecondaryIncentiveRewarder()[tokenAddress]; } else { return IRewarder(address(0)); } } function setArrayLengthAndInitializedTime( address tokenAddress, uint8 arrayLength, uint256 lastInitializedTime ) internal { require(lastInitializedTime >= 0 && uint256(lastInitializedTime) < type(uint32).max); // dev: next settle time overflow mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; context.lastInitializedTime = uint32(lastInitializedTime); context.assetArrayLength = arrayLength; } /// @notice Returns the array of deposit shares and leverage thresholds for nTokens function getDepositParameters(uint256 currencyId, uint256 maxMarketIndex) internal view returns (int256[] memory depositShares, int256[] memory leverageThresholds) { mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenDepositStorage(); uint32[NUM_NTOKEN_MARKET_FACTORS] storage depositParameters = store[currencyId]; (depositShares, leverageThresholds) = _getParameters(depositParameters, maxMarketIndex, false); } /// @notice Sets the deposit parameters /// @dev We pack the values in alternating between the two parameters into either one or two // storage slots depending on the number of markets. This is to save storage reads when we use the parameters. function setDepositParameters( uint256 currencyId, uint32[] calldata depositShares, uint32[] calldata leverageThresholds ) internal { require( depositShares.length <= Constants.MAX_TRADED_MARKET_INDEX, "PT: deposit share length" ); require(depositShares.length == leverageThresholds.length, "PT: leverage share length"); uint256 shareSum; for (uint256 i; i < depositShares.length; i++) { // This cannot overflow in uint 256 with 9 max slots shareSum = shareSum + depositShares[i]; require( leverageThresholds[i] > 0 && leverageThresholds[i] < Constants.RATE_PRECISION, "PT: leverage threshold" ); } // Total deposit share must add up to 100% require(shareSum == uint256(Constants.DEPOSIT_PERCENT_BASIS), "PT: deposit shares sum"); mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenDepositStorage(); uint32[NUM_NTOKEN_MARKET_FACTORS] storage depositParameters = store[currencyId]; _setParameters(depositParameters, depositShares, leverageThresholds); } /// @notice Sets the initialization parameters for the markets, these are read only when markets /// are initialized function setInitializationParameters( uint256 currencyId, uint32[] calldata annualizedAnchorRates, uint32[] calldata proportions ) internal { require(annualizedAnchorRates.length <= Constants.MAX_TRADED_MARKET_INDEX, "PT: annualized anchor rates length"); require(proportions.length == annualizedAnchorRates.length, "PT: proportions length"); for (uint256 i; i < proportions.length; i++) { // Proportions must be between zero and the rate precision require(annualizedAnchorRates[i] > 0, "NT: anchor rate zero"); require( proportions[i] > 0 && proportions[i] < Constants.RATE_PRECISION, "PT: invalid proportion" ); } mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenInitStorage(); uint32[NUM_NTOKEN_MARKET_FACTORS] storage initParameters = store[currencyId]; _setParameters(initParameters, annualizedAnchorRates, proportions); } /// @notice Returns the array of initialization parameters for a given currency. function getInitializationParameters(uint256 currencyId, uint256 maxMarketIndex) internal view returns (int256[] memory annualizedAnchorRates, int256[] memory proportions) { mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenInitStorage(); uint32[NUM_NTOKEN_MARKET_FACTORS] storage initParameters = store[currencyId]; (annualizedAnchorRates, proportions) = _getParameters(initParameters, maxMarketIndex, true); } function _getParameters( uint32[NUM_NTOKEN_MARKET_FACTORS] storage slot, uint256 maxMarketIndex, bool noUnset ) private view returns (int256[] memory, int256[] memory) { uint256 index = 0; int256[] memory array1 = new int256[](maxMarketIndex); int256[] memory array2 = new int256[](maxMarketIndex); for (uint256 i; i < maxMarketIndex; i++) { array1[i] = slot[index]; index++; array2[i] = slot[index]; index++; if (noUnset) { require(array1[i] > 0 && array2[i] > 0, "PT: init value zero"); } } return (array1, array2); } function _setParameters( uint32[NUM_NTOKEN_MARKET_FACTORS] storage slot, uint32[] calldata array1, uint32[] calldata array2 ) private { uint256 index = 0; for (uint256 i = 0; i < array1.length; i++) { slot[index] = array1[i]; index++; slot[index] = array2[i]; index++; } } function loadNTokenPortfolioNoCashGroup(nTokenPortfolio memory nToken, uint16 currencyId) internal view { nToken.tokenAddress = nTokenAddress(currencyId); // prettier-ignore ( /* currencyId */, /* incentiveRate */, uint256 lastInitializedTime, uint8 assetArrayLength, bytes5 parameters ) = getNTokenContext(nToken.tokenAddress); // prettier-ignore ( uint256 totalSupply, /* accumulatedNOTEPerNToken */, /* lastAccumulatedTime */ ) = nTokenSupply.getStoredNTokenSupplyFactors(nToken.tokenAddress); nToken.lastInitializedTime = lastInitializedTime; nToken.totalSupply = int256(totalSupply); nToken.parameters = parameters; nToken.portfolioState = PortfolioHandler.buildPortfolioState( nToken.tokenAddress, assetArrayLength, 0 ); // prettier-ignore ( nToken.cashBalance, /* nTokenBalance */, /* lastClaimTime */, /* accountIncentiveDebt */ ) = BalanceHandler.getBalanceStorage(nToken.tokenAddress, currencyId); } /// @notice Uses buildCashGroupStateful function loadNTokenPortfolioStateful(nTokenPortfolio memory nToken, uint16 currencyId) internal { loadNTokenPortfolioNoCashGroup(nToken, currencyId); nToken.cashGroup = CashGroup.buildCashGroupStateful(currencyId); } /// @notice Uses buildCashGroupView function loadNTokenPortfolioView(nTokenPortfolio memory nToken, uint16 currencyId) internal view { loadNTokenPortfolioNoCashGroup(nToken, currencyId); nToken.cashGroup = CashGroup.buildCashGroupView(currencyId); } /// @notice Returns the next settle time for the nToken which is 1 quarter away function getNextSettleTime(nTokenPortfolio memory nToken) internal pure returns (uint256) { if (nToken.lastInitializedTime == 0) return 0; return DateTime.getReferenceTime(nToken.lastInitializedTime) + Constants.QUARTER; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./nTokenHandler.sol"; import "../../global/LibStorage.sol"; import "../../math/SafeInt256.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library nTokenSupply { using SafeInt256 for int256; using SafeMath for uint256; /// @notice Retrieves stored nToken supply and related factors. Do not use accumulatedNOTEPerNToken for calculating /// incentives! Use `getUpdatedAccumulatedNOTEPerNToken` instead. function getStoredNTokenSupplyFactors(address tokenAddress) internal view returns ( uint256 totalSupply, uint256 accumulatedNOTEPerNToken, uint256 lastAccumulatedTime ) { mapping(address => nTokenTotalSupplyStorage) storage store = LibStorage.getNTokenTotalSupplyStorage(); nTokenTotalSupplyStorage storage nTokenStorage = store[tokenAddress]; totalSupply = nTokenStorage.totalSupply; // NOTE: DO NOT USE THIS RETURNED VALUE FOR CALCULATING INCENTIVES. The accumulatedNOTEPerNToken // must be updated given the block time. Use `getUpdatedAccumulatedNOTEPerNToken` instead accumulatedNOTEPerNToken = nTokenStorage.accumulatedNOTEPerNToken; lastAccumulatedTime = nTokenStorage.lastAccumulatedTime; } /// @notice Returns the updated accumulated NOTE per nToken for calculating incentives function getUpdatedAccumulatedNOTEPerNToken(address tokenAddress, uint256 blockTime) internal view returns ( uint256 totalSupply, uint256 accumulatedNOTEPerNToken, uint256 lastAccumulatedTime ) { ( totalSupply, accumulatedNOTEPerNToken, lastAccumulatedTime ) = getStoredNTokenSupplyFactors(tokenAddress); // nToken totalSupply is never allowed to drop to zero but we check this here to avoid // divide by zero errors during initialization. Also ensure that lastAccumulatedTime is not // zero to avoid a massive accumulation amount on initialization. if (blockTime > lastAccumulatedTime && lastAccumulatedTime > 0 && totalSupply > 0) { // prettier-ignore ( /* currencyId */, uint256 emissionRatePerYear, /* initializedTime */, /* assetArrayLength */, /* parameters */ ) = nTokenHandler.getNTokenContext(tokenAddress); uint256 additionalNOTEAccumulatedPerNToken = _calculateAdditionalNOTE( // Emission rate is denominated in whole tokens, scale to 1e8 decimals here emissionRatePerYear.mul(uint256(Constants.INTERNAL_TOKEN_PRECISION)), // Time since last accumulation (overflow checked above) blockTime - lastAccumulatedTime, totalSupply ); accumulatedNOTEPerNToken = accumulatedNOTEPerNToken.add(additionalNOTEAccumulatedPerNToken); require(accumulatedNOTEPerNToken < type(uint128).max); // dev: accumulated NOTE overflow } } /// @notice additionalNOTEPerNToken accumulated since last accumulation time in 1e18 precision function _calculateAdditionalNOTE( uint256 emissionRatePerYear, uint256 timeSinceLastAccumulation, uint256 totalSupply ) private pure returns (uint256) { // If we use 18 decimal places as the accumulation precision then we will overflow uint128 when // a single nToken has accumulated 3.4 x 10^20 NOTE tokens. This isn't possible since the max // NOTE that can accumulate is 10^16 (100 million NOTE in 1e8 precision) so we should be safe // using 18 decimal places and uint128 storage slot // timeSinceLastAccumulation (SECONDS) // accumulatedNOTEPerSharePrecision (1e18) // emissionRatePerYear (INTERNAL_TOKEN_PRECISION) // DIVIDE BY // YEAR (SECONDS) // totalSupply (INTERNAL_TOKEN_PRECISION) return timeSinceLastAccumulation .mul(Constants.INCENTIVE_ACCUMULATION_PRECISION) .mul(emissionRatePerYear) .div(Constants.YEAR) // totalSupply > 0 is checked in the calling function .div(totalSupply); } /// @notice Updates the nToken token supply amount when minting or redeeming. /// @param tokenAddress address of the nToken /// @param netChange positive or negative change to the total nToken supply /// @param blockTime current block time /// @return accumulatedNOTEPerNToken updated to the given block time function changeNTokenSupply( address tokenAddress, int256 netChange, uint256 blockTime ) internal returns (uint256) { ( uint256 totalSupply, uint256 accumulatedNOTEPerNToken, /* uint256 lastAccumulatedTime */ ) = getUpdatedAccumulatedNOTEPerNToken(tokenAddress, blockTime); // Update storage variables mapping(address => nTokenTotalSupplyStorage) storage store = LibStorage.getNTokenTotalSupplyStorage(); nTokenTotalSupplyStorage storage nTokenStorage = store[tokenAddress]; int256 newTotalSupply = int256(totalSupply).add(netChange); // We allow newTotalSupply to equal zero here even though it is prevented from being redeemed down to // exactly zero by other internal logic inside nTokenRedeem. This is meant to be purely an overflow check. require(0 <= newTotalSupply && uint256(newTotalSupply) < type(uint96).max); // dev: nToken supply overflow nTokenStorage.totalSupply = uint96(newTotalSupply); // NOTE: overflow checked inside getUpdatedAccumulatedNOTEPerNToken so that behavior here mirrors what // the user would see if querying the view function nTokenStorage.accumulatedNOTEPerNToken = uint128(accumulatedNOTEPerNToken); require(blockTime < type(uint32).max); // dev: block time overflow nTokenStorage.lastAccumulatedTime = uint32(blockTime); return accumulatedNOTEPerNToken; } /// @notice Called by governance to set the new emission rate function setIncentiveEmissionRate(address tokenAddress, uint32 newEmissionsRate, uint256 blockTime) internal { // Ensure that the accumulatedNOTEPerNToken updates to the current block time before we update the // emission rate changeNTokenSupply(tokenAddress, 0, blockTime); mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; context.incentiveAnnualEmissionRate = newEmissionsRate; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./nTokenHandler.sol"; import "../portfolio/BitmapAssetsHandler.sol"; import "../../math/SafeInt256.sol"; import "../../math/Bitmap.sol"; library nTokenCalculations { using Bitmap for bytes32; using SafeInt256 for int256; using AssetRate for AssetRateParameters; using CashGroup for CashGroupParameters; /// @notice Returns the nToken present value denominated in asset terms. function getNTokenAssetPV(nTokenPortfolio memory nToken, uint256 blockTime) internal view returns (int256) { int256 totalAssetPV; int256 totalUnderlyingPV; { uint256 nextSettleTime = nTokenHandler.getNextSettleTime(nToken); // If the first asset maturity has passed (the 3 month), this means that all the LTs must // be settled except the 6 month (which is now the 3 month). We don't settle LTs except in // initialize markets so we calculate the cash value of the portfolio here. if (nextSettleTime <= blockTime) { // NOTE: this condition should only be present for a very short amount of time, which is the window between // when the markets are no longer tradable at quarter end and when the new markets have been initialized. // We time travel back to one second before maturity to value the liquidity tokens. Although this value is // not strictly correct the different should be quite slight. We do this to ensure that free collateral checks // for withdraws and liquidations can still be processed. If this condition persists for a long period of time then // the entire protocol will have serious problems as markets will not be tradable. blockTime = nextSettleTime - 1; } } // This is the total value in liquid assets (int256 totalAssetValueInMarkets, /* int256[] memory netfCash */) = getNTokenMarketValue(nToken, blockTime); // Then get the total value in any idiosyncratic fCash residuals (if they exist) bytes32 ifCashBits = getNTokenifCashBits( nToken.tokenAddress, nToken.cashGroup.currencyId, nToken.lastInitializedTime, blockTime, nToken.cashGroup.maxMarketIndex ); int256 ifCashResidualUnderlyingPV = 0; if (ifCashBits != 0) { // Non idiosyncratic residuals have already been accounted for (ifCashResidualUnderlyingPV, /* hasDebt */) = BitmapAssetsHandler.getNetPresentValueFromBitmap( nToken.tokenAddress, nToken.cashGroup.currencyId, nToken.lastInitializedTime, blockTime, nToken.cashGroup, false, // nToken present value calculation does not use risk adjusted values ifCashBits ); } // Return the total present value denominated in asset terms return totalAssetValueInMarkets .add(nToken.cashGroup.assetRate.convertFromUnderlying(ifCashResidualUnderlyingPV)) .add(nToken.cashBalance); } /** * @notice Handles the case when liquidity tokens should be withdrawn in proportion to their amounts * in the market. This will be the case when there is no idiosyncratic fCash residuals in the nToken * portfolio. * @param nToken portfolio object for nToken * @param nTokensToRedeem amount of nTokens to redeem * @param tokensToWithdraw array of liquidity tokens to withdraw from each market, proportional to * the account's share of the total supply * @param netfCash an empty array to hold net fCash values calculated later when the tokens are actually * withdrawn from markets */ function _getProportionalLiquidityTokens( nTokenPortfolio memory nToken, int256 nTokensToRedeem ) private pure returns (int256[] memory tokensToWithdraw, int256[] memory netfCash) { uint256 numMarkets = nToken.portfolioState.storedAssets.length; tokensToWithdraw = new int256[](numMarkets); netfCash = new int256[](numMarkets); for (uint256 i = 0; i < numMarkets; i++) { int256 totalTokens = nToken.portfolioState.storedAssets[i].notional; tokensToWithdraw[i] = totalTokens.mul(nTokensToRedeem).div(nToken.totalSupply); } } /** * @notice Returns the number of liquidity tokens to withdraw from each market if the nToken * has idiosyncratic residuals during nToken redeem. In this case the redeemer will take * their cash from the rest of the fCash markets, redeeming around the nToken. * @param nToken portfolio object for nToken * @param nTokensToRedeem amount of nTokens to redeem * @param blockTime block time * @param ifCashBits the bits in the bitmap that represent ifCash assets * @return tokensToWithdraw array of tokens to withdraw from each corresponding market * @return netfCash array of netfCash amounts to go back to the account */ function getLiquidityTokenWithdraw( nTokenPortfolio memory nToken, int256 nTokensToRedeem, uint256 blockTime, bytes32 ifCashBits ) internal view returns (int256[] memory, int256[] memory) { // If there are no ifCash bits set then this will just return the proportion of all liquidity tokens if (ifCashBits == 0) return _getProportionalLiquidityTokens(nToken, nTokensToRedeem); ( int256 totalAssetValueInMarkets, int256[] memory netfCash ) = getNTokenMarketValue(nToken, blockTime); int256[] memory tokensToWithdraw = new int256[](netfCash.length); // NOTE: this total portfolio asset value does not include any cash balance the nToken may hold. // The redeemer will always get a proportional share of this cash balance and therefore we don't // need to account for it here when we calculate the share of liquidity tokens to withdraw. We are // only concerned with the nToken's portfolio assets in this method. int256 totalPortfolioAssetValue; { // Returns the risk adjusted net present value for the idiosyncratic residuals (int256 underlyingPV, /* hasDebt */) = BitmapAssetsHandler.getNetPresentValueFromBitmap( nToken.tokenAddress, nToken.cashGroup.currencyId, nToken.lastInitializedTime, blockTime, nToken.cashGroup, true, // use risk adjusted here to assess a penalty for withdrawing around the residual ifCashBits ); // NOTE: we do not include cash balance here because the account will always take their share // of the cash balance regardless of the residuals totalPortfolioAssetValue = totalAssetValueInMarkets.add( nToken.cashGroup.assetRate.convertFromUnderlying(underlyingPV) ); } // Loops through each liquidity token and calculates how much the redeemer can withdraw to get // the requisite amount of present value after adjusting for the ifCash residual value that is // not accessible via redemption. for (uint256 i = 0; i < tokensToWithdraw.length; i++) { int256 totalTokens = nToken.portfolioState.storedAssets[i].notional; // Redeemer's baseline share of the liquidity tokens based on total supply: // redeemerShare = totalTokens * nTokensToRedeem / totalSupply // Scalar factor to account for residual value (need to inflate the tokens to withdraw // proportional to the value locked up in ifCash residuals): // scaleFactor = totalPortfolioAssetValue / totalAssetValueInMarkets // Final math equals: // tokensToWithdraw = redeemerShare * scalarFactor // tokensToWithdraw = (totalTokens * nTokensToRedeem * totalPortfolioAssetValue) // / (totalAssetValueInMarkets * totalSupply) tokensToWithdraw[i] = totalTokens .mul(nTokensToRedeem) .mul(totalPortfolioAssetValue); tokensToWithdraw[i] = tokensToWithdraw[i] .div(totalAssetValueInMarkets) .div(nToken.totalSupply); // This is the share of net fcash that will be credited back to the account netfCash[i] = netfCash[i].mul(tokensToWithdraw[i]).div(totalTokens); } return (tokensToWithdraw, netfCash); } /// @notice Returns the value of all the liquid assets in an nToken portfolio which are defined by /// the liquidity tokens held in each market and their corresponding fCash positions. The formula /// can be described as: /// totalAssetValue = sum_per_liquidity_token(cashClaim + presentValue(netfCash)) /// where netfCash = fCashClaim + fCash /// and fCash refers the the fCash position at the corresponding maturity function getNTokenMarketValue(nTokenPortfolio memory nToken, uint256 blockTime) internal view returns (int256 totalAssetValue, int256[] memory netfCash) { uint256 numMarkets = nToken.portfolioState.storedAssets.length; netfCash = new int256[](numMarkets); MarketParameters memory market; for (uint256 i = 0; i < numMarkets; i++) { // Load the corresponding market into memory nToken.cashGroup.loadMarket(market, i + 1, true, blockTime); PortfolioAsset memory liquidityToken = nToken.portfolioState.storedAssets[i]; uint256 maturity = liquidityToken.maturity; // Get the fCash claims and fCash assets. We do not use haircut versions here because // nTokenRedeem does not require it and getNTokenPV does not use it (a haircut is applied // at the end of the calculation to the entire PV instead). (int256 assetCashClaim, int256 fCashClaim) = AssetHandler.getCashClaims(liquidityToken, market); // fCash is denominated in underlying netfCash[i] = fCashClaim.add( BitmapAssetsHandler.getifCashNotional( nToken.tokenAddress, nToken.cashGroup.currencyId, maturity ) ); // This calculates for a single liquidity token: // assetCashClaim + convertToAssetCash(pv(netfCash)) int256 netAssetValueInMarket = assetCashClaim.add( nToken.cashGroup.assetRate.convertFromUnderlying( AssetHandler.getPresentfCashValue( netfCash[i], maturity, blockTime, // No need to call cash group for oracle rate, it is up to date here // and we are assured to be referring to this market. market.oracleRate ) ) ); // Calculate the running total totalAssetValue = totalAssetValue.add(netAssetValueInMarket); } } /// @notice Returns just the bits in a bitmap that are idiosyncratic function getNTokenifCashBits( address tokenAddress, uint256 currencyId, uint256 lastInitializedTime, uint256 blockTime, uint256 maxMarketIndex ) internal view returns (bytes32) { // If max market index is less than or equal to 2, there are never ifCash assets by construction if (maxMarketIndex <= 2) return bytes32(0); bytes32 assetsBitmap = BitmapAssetsHandler.getAssetsBitmap(tokenAddress, currencyId); // Handles the case when there are no assets at the first initialization if (assetsBitmap == 0) return assetsBitmap; uint256 tRef = DateTime.getReferenceTime(blockTime); if (tRef == lastInitializedTime) { // This is a more efficient way to turn off ifCash assets in the common case when the market is // initialized immediately return assetsBitmap & ~(Constants.ACTIVE_MARKETS_MASK); } else { // In this branch, initialize markets has occurred past the time above. It would occur in these // two scenarios (both should be exceedingly rare): // 1. initializing a cash group with 3+ markets for the first time (not beginning on the tRef) // 2. somehow initialize markets has been delayed for more than 24 hours for (uint i = 1; i <= maxMarketIndex; i++) { // In this loop we get the maturity of each active market and turn off the corresponding bit // one by one. It is less efficient than the option above. uint256 maturity = tRef + DateTime.getTradedMarket(i); (uint256 bitNum, /* */) = DateTime.getBitNumFromMaturity(lastInitializedTime, maturity); assetsBitmap = assetsBitmap.setBit(bitNum, false); } return assetsBitmap; } } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../global/Types.sol"; import "../../global/LibStorage.sol"; import "../../global/Constants.sol"; import "../../math/SafeInt256.sol"; import "../../../interfaces/notional/AssetRateAdapter.sol"; library AssetRate { using SafeInt256 for int256; event SetSettlementRate(uint256 indexed currencyId, uint256 indexed maturity, uint128 rate); // Asset rates are in 1e18 decimals (cToken exchange rates), internal balances // are in 1e8 decimals. Therefore we leave this as 1e18 / 1e8 = 1e10 int256 private constant ASSET_RATE_DECIMAL_DIFFERENCE = 1e10; /// @notice Converts an internal asset cash value to its underlying token value. /// @param ar exchange rate object between asset and underlying /// @param assetBalance amount to convert to underlying function convertToUnderlying(AssetRateParameters memory ar, int256 assetBalance) internal pure returns (int256) { // Calculation here represents: // rate * balance * internalPrecision / rateDecimals * underlyingPrecision int256 underlyingBalance = ar.rate .mul(assetBalance) .div(ASSET_RATE_DECIMAL_DIFFERENCE) .div(ar.underlyingDecimals); return underlyingBalance; } /// @notice Converts an internal underlying cash value to its asset cash value /// @param ar exchange rate object between asset and underlying /// @param underlyingBalance amount to convert to asset cash, denominated in internal token precision function convertFromUnderlying(AssetRateParameters memory ar, int256 underlyingBalance) internal pure returns (int256) { // Calculation here represents: // rateDecimals * balance * underlyingPrecision / rate * internalPrecision int256 assetBalance = underlyingBalance .mul(ASSET_RATE_DECIMAL_DIFFERENCE) .mul(ar.underlyingDecimals) .div(ar.rate); return assetBalance; } /// @notice Returns the current per block supply rate, is used when calculating oracle rates /// for idiosyncratic fCash with a shorter duration than the 3 month maturity. function getSupplyRate(AssetRateParameters memory ar) internal view returns (uint256) { // If the rate oracle is not set, the asset is not interest bearing and has an oracle rate of zero. if (address(ar.rateOracle) == address(0)) return 0; uint256 rate = ar.rateOracle.getAnnualizedSupplyRate(); // Zero supply rate is valid since this is an interest rate, we do not divide by // the supply rate so we do not get div by zero errors. require(rate >= 0); // dev: invalid supply rate return rate; } function _getAssetRateStorage(uint256 currencyId) private view returns (AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) { mapping(uint256 => AssetRateStorage) storage store = LibStorage.getAssetRateStorage(); AssetRateStorage storage ar = store[currencyId]; rateOracle = AssetRateAdapter(ar.rateOracle); underlyingDecimalPlaces = ar.underlyingDecimalPlaces; } /// @notice Gets an asset rate using a view function, does not accrue interest so the /// exchange rate will not be up to date. Should only be used for non-stateful methods function _getAssetRateView(uint256 currencyId) private view returns ( int256, AssetRateAdapter, uint8 ) { (AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStorage(currencyId); int256 rate; if (address(rateOracle) == address(0)) { // If no rate oracle is set, then set this to the identity rate = ASSET_RATE_DECIMAL_DIFFERENCE; // This will get raised to 10^x and return 1, will not end up with div by zero underlyingDecimalPlaces = 0; } else { rate = rateOracle.getExchangeRateView(); require(rate > 0); // dev: invalid exchange rate } return (rate, rateOracle, underlyingDecimalPlaces); } /// @notice Gets an asset rate using a stateful function, accrues interest so the /// exchange rate will be up to date for the current block. function _getAssetRateStateful(uint256 currencyId) private returns ( int256, AssetRateAdapter, uint8 ) { (AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStorage(currencyId); int256 rate; if (address(rateOracle) == address(0)) { // If no rate oracle is set, then set this to the identity rate = ASSET_RATE_DECIMAL_DIFFERENCE; // This will get raised to 10^x and return 1, will not end up with div by zero underlyingDecimalPlaces = 0; } else { rate = rateOracle.getExchangeRateStateful(); require(rate > 0); // dev: invalid exchange rate } return (rate, rateOracle, underlyingDecimalPlaces); } /// @notice Returns an asset rate object using the view method function buildAssetRateView(uint256 currencyId) internal view returns (AssetRateParameters memory) { (int256 rate, AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateView(currencyId); return AssetRateParameters({ rateOracle: rateOracle, rate: rate, // No overflow, restricted on storage underlyingDecimals: int256(10**underlyingDecimalPlaces) }); } /// @notice Returns an asset rate object using the stateful method function buildAssetRateStateful(uint256 currencyId) internal returns (AssetRateParameters memory) { (int256 rate, AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStateful(currencyId); return AssetRateParameters({ rateOracle: rateOracle, rate: rate, // No overflow, restricted on storage underlyingDecimals: int256(10**underlyingDecimalPlaces) }); } /// @dev Gets a settlement rate object function _getSettlementRateStorage(uint256 currencyId, uint256 maturity) private view returns ( int256 settlementRate, uint8 underlyingDecimalPlaces ) { mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store = LibStorage.getSettlementRateStorage(); SettlementRateStorage storage rateStorage = store[currencyId][maturity]; settlementRate = rateStorage.settlementRate; underlyingDecimalPlaces = rateStorage.underlyingDecimalPlaces; } /// @notice Returns a settlement rate object using the view method function buildSettlementRateView(uint256 currencyId, uint256 maturity) internal view returns (AssetRateParameters memory) { // prettier-ignore ( int256 settlementRate, uint8 underlyingDecimalPlaces ) = _getSettlementRateStorage(currencyId, maturity); // Asset exchange rates cannot be zero if (settlementRate == 0) { // If settlement rate has not been set then we need to fetch it // prettier-ignore ( settlementRate, /* address */, underlyingDecimalPlaces ) = _getAssetRateView(currencyId); } return AssetRateParameters( AssetRateAdapter(address(0)), settlementRate, // No overflow, restricted on storage int256(10**underlyingDecimalPlaces) ); } /// @notice Returns a settlement rate object and sets the rate if it has not been set yet function buildSettlementRateStateful( uint256 currencyId, uint256 maturity, uint256 blockTime ) internal returns (AssetRateParameters memory) { (int256 settlementRate, uint8 underlyingDecimalPlaces) = _getSettlementRateStorage(currencyId, maturity); if (settlementRate == 0) { // Settlement rate has not yet been set, set it in this branch AssetRateAdapter rateOracle; // If rate oracle == 0 then this will return the identity settlement rate // prettier-ignore ( settlementRate, rateOracle, underlyingDecimalPlaces ) = _getAssetRateStateful(currencyId); if (address(rateOracle) != address(0)) { mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store = LibStorage.getSettlementRateStorage(); // Only need to set settlement rates when the rate oracle is set (meaning the asset token has // a conversion rate to an underlying). If not set then the asset cash always settles to underlying at a 1-1 // rate since they are the same. require(0 < blockTime && maturity <= blockTime && blockTime <= type(uint40).max); // dev: settlement rate timestamp overflow require(0 < settlementRate && settlementRate <= type(uint128).max); // dev: settlement rate overflow SettlementRateStorage storage rateStorage = store[currencyId][maturity]; rateStorage.blockTime = uint40(blockTime); rateStorage.settlementRate = uint128(settlementRate); rateStorage.underlyingDecimalPlaces = underlyingDecimalPlaces; emit SetSettlementRate(currencyId, maturity, uint128(settlementRate)); } } return AssetRateParameters( AssetRateAdapter(address(0)), settlementRate, // No overflow, restricted on storage int256(10**underlyingDecimalPlaces) ); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./Incentives.sol"; import "./TokenHandler.sol"; import "../AccountContextHandler.sol"; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../../math/SafeInt256.sol"; import "../../math/FloatingPoint56.sol"; library BalanceHandler { using SafeInt256 for int256; using TokenHandler for Token; using AssetRate for AssetRateParameters; using AccountContextHandler for AccountContext; /// @notice Emitted when a cash balance changes event CashBalanceChange(address indexed account, uint16 indexed currencyId, int256 netCashChange); /// @notice Emitted when nToken supply changes (not the same as transfers) event nTokenSupplyChange(address indexed account, uint16 indexed currencyId, int256 tokenSupplyChange); /// @notice Emitted when reserve fees are accrued event ReserveFeeAccrued(uint16 indexed currencyId, int256 fee); /// @notice Emitted when reserve balance is updated event ReserveBalanceUpdated(uint16 indexed currencyId, int256 newBalance); /// @notice Emitted when reserve balance is harvested event ExcessReserveBalanceHarvested(uint16 indexed currencyId, int256 harvestAmount); /// @notice Deposits asset tokens into an account /// @dev Handles two special cases when depositing tokens into an account. /// - If a token has transfer fees then the amount specified does not equal the amount that the contract /// will receive. Complete the deposit here rather than in finalize so that the contract has the correct /// balance to work with. /// - Force a transfer before finalize to allow a different account to deposit into an account /// @return assetAmountInternal which is the converted asset amount accounting for transfer fees function depositAssetToken( BalanceState memory balanceState, address account, int256 assetAmountExternal, bool forceTransfer ) internal returns (int256 assetAmountInternal) { if (assetAmountExternal == 0) return 0; require(assetAmountExternal > 0); // dev: deposit asset token amount negative Token memory token = TokenHandler.getAssetToken(balanceState.currencyId); if (token.tokenType == TokenType.aToken) { // Handles special accounting requirements for aTokens assetAmountExternal = AaveHandler.convertToScaledBalanceExternal( balanceState.currencyId, assetAmountExternal ); } // Force transfer is used to complete the transfer before going to finalize if (token.hasTransferFee || forceTransfer) { // If the token has a transfer fee the deposit amount may not equal the actual amount // that the contract will receive. We handle the deposit here and then update the netCashChange // accordingly which is denominated in internal precision. int256 assetAmountExternalPrecisionFinal = token.transfer(account, balanceState.currencyId, assetAmountExternal); // Convert the external precision to internal, it's possible that we lose dust amounts here but // this is unavoidable because we do not know how transfer fees are calculated. assetAmountInternal = token.convertToInternal(assetAmountExternalPrecisionFinal); // Transfer has been called balanceState.netCashChange = balanceState.netCashChange.add(assetAmountInternal); return assetAmountInternal; } else { assetAmountInternal = token.convertToInternal(assetAmountExternal); // Otherwise add the asset amount here. It may be net off later and we want to only do // a single transfer during the finalize method. Use internal precision to ensure that internal accounting // and external account remain in sync. // Transfer will be deferred balanceState.netAssetTransferInternalPrecision = balanceState .netAssetTransferInternalPrecision .add(assetAmountInternal); // Returns the converted assetAmountExternal to the internal amount return assetAmountInternal; } } /// @notice Handle deposits of the underlying token /// @dev In this case we must wrap the underlying token into an asset token, ensuring that we do not end up /// with any underlying tokens left as dust on the contract. function depositUnderlyingToken( BalanceState memory balanceState, address account, int256 underlyingAmountExternal ) internal returns (int256) { if (underlyingAmountExternal == 0) return 0; require(underlyingAmountExternal > 0); // dev: deposit underlying token negative Token memory underlyingToken = TokenHandler.getUnderlyingToken(balanceState.currencyId); // This is the exact amount of underlying tokens the account has in external precision. if (underlyingToken.tokenType == TokenType.Ether) { // Underflow checked above require(uint256(underlyingAmountExternal) == msg.value, "ETH Balance"); } else { underlyingAmountExternal = underlyingToken.transfer(account, balanceState.currencyId, underlyingAmountExternal); } Token memory assetToken = TokenHandler.getAssetToken(balanceState.currencyId); int256 assetTokensReceivedExternalPrecision = assetToken.mint(balanceState.currencyId, SafeInt256.toUint(underlyingAmountExternal)); // cTokens match INTERNAL_TOKEN_PRECISION so this will short circuit but we leave this here in case a different // type of asset token is listed in the future. It's possible if those tokens have a different precision dust may // accrue but that is not relevant now. int256 assetTokensReceivedInternal = assetToken.convertToInternal(assetTokensReceivedExternalPrecision); // Transfer / mint has taken effect balanceState.netCashChange = balanceState.netCashChange.add(assetTokensReceivedInternal); return assetTokensReceivedInternal; } /// @notice Finalizes an account's balances, handling any transfer logic required /// @dev This method SHOULD NOT be used for nToken accounts, for that use setBalanceStorageForNToken /// as the nToken is limited in what types of balances it can hold. function finalize( BalanceState memory balanceState, address account, AccountContext memory accountContext, bool redeemToUnderlying ) internal returns (int256 transferAmountExternal) { bool mustUpdate; if (balanceState.netNTokenTransfer < 0) { require( balanceState.storedNTokenBalance .add(balanceState.netNTokenSupplyChange) .add(balanceState.netNTokenTransfer) >= 0, "Neg nToken" ); } if (balanceState.netAssetTransferInternalPrecision < 0) { require( balanceState.storedCashBalance .add(balanceState.netCashChange) .add(balanceState.netAssetTransferInternalPrecision) >= 0, "Neg Cash" ); } // Transfer amount is checked inside finalize transfers in case when converting to external we // round down to zero. This returns the actual net transfer in internal precision as well. ( transferAmountExternal, balanceState.netAssetTransferInternalPrecision ) = _finalizeTransfers(balanceState, account, redeemToUnderlying); // No changes to total cash after this point int256 totalCashChange = balanceState.netCashChange.add(balanceState.netAssetTransferInternalPrecision); if (totalCashChange != 0) { balanceState.storedCashBalance = balanceState.storedCashBalance.add(totalCashChange); mustUpdate = true; emit CashBalanceChange( account, uint16(balanceState.currencyId), totalCashChange ); } if (balanceState.netNTokenTransfer != 0 || balanceState.netNTokenSupplyChange != 0) { // Final nToken balance is used to calculate the account incentive debt int256 finalNTokenBalance = balanceState.storedNTokenBalance .add(balanceState.netNTokenTransfer) .add(balanceState.netNTokenSupplyChange); // The toUint() call here will ensure that nToken balances never become negative Incentives.claimIncentives(balanceState, account, finalNTokenBalance.toUint()); balanceState.storedNTokenBalance = finalNTokenBalance; if (balanceState.netNTokenSupplyChange != 0) { emit nTokenSupplyChange( account, uint16(balanceState.currencyId), balanceState.netNTokenSupplyChange ); } mustUpdate = true; } if (mustUpdate) { _setBalanceStorage( account, balanceState.currencyId, balanceState.storedCashBalance, balanceState.storedNTokenBalance, balanceState.lastClaimTime, balanceState.accountIncentiveDebt ); } accountContext.setActiveCurrency( balanceState.currencyId, // Set active currency to true if either balance is non-zero balanceState.storedCashBalance != 0 || balanceState.storedNTokenBalance != 0, Constants.ACTIVE_IN_BALANCES ); if (balanceState.storedCashBalance < 0) { // NOTE: HAS_CASH_DEBT cannot be extinguished except by a free collateral check where all balances // are examined accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT; } } /// @dev Returns the amount transferred in underlying or asset terms depending on how redeem to underlying /// is specified. function _finalizeTransfers( BalanceState memory balanceState, address account, bool redeemToUnderlying ) private returns (int256 actualTransferAmountExternal, int256 assetTransferAmountInternal) { Token memory assetToken = TokenHandler.getAssetToken(balanceState.currencyId); // Dust accrual to the protocol is possible if the token decimals is less than internal token precision. // See the comments in TokenHandler.convertToExternal and TokenHandler.convertToInternal int256 assetTransferAmountExternal = assetToken.convertToExternal(balanceState.netAssetTransferInternalPrecision); if (assetTransferAmountExternal == 0) { return (0, 0); } else if (redeemToUnderlying && assetTransferAmountExternal < 0) { // We only do the redeem to underlying if the asset transfer amount is less than zero. If it is greater than // zero then we will do a normal transfer instead. // We use the internal amount here and then scale it to the external amount so that there is // no loss of precision between our internal accounting and the external account. In this case // there will be no dust accrual in underlying tokens since we will transfer the exact amount // of underlying that was received. actualTransferAmountExternal = assetToken.redeem( balanceState.currencyId, account, // No overflow, checked above uint256(assetTransferAmountExternal.neg()) ); // In this case we're transferring underlying tokens, we want to convert the internal // asset transfer amount to store in cash balances assetTransferAmountInternal = assetToken.convertToInternal(assetTransferAmountExternal); } else { // NOTE: in the case of aTokens assetTransferAmountExternal is the scaledBalanceOf in external precision, it // will be converted to balanceOf denomination inside transfer actualTransferAmountExternal = assetToken.transfer(account, balanceState.currencyId, assetTransferAmountExternal); // Convert the actual transferred amount assetTransferAmountInternal = assetToken.convertToInternal(actualTransferAmountExternal); } } /// @notice Special method for settling negative current cash debts. This occurs when an account /// has a negative fCash balance settle to cash. A settler may come and force the account to borrow /// at the prevailing 3 month rate /// @dev Use this method to avoid any nToken and transfer logic in finalize which is unnecessary. function setBalanceStorageForSettleCashDebt( address account, CashGroupParameters memory cashGroup, int256 amountToSettleAsset, AccountContext memory accountContext ) internal returns (int256) { require(amountToSettleAsset >= 0); // dev: amount to settle negative (int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt) = getBalanceStorage(account, cashGroup.currencyId); // Prevents settlement of positive balances require(cashBalance < 0, "Invalid settle balance"); if (amountToSettleAsset == 0) { // Symbolizes that the entire debt should be settled amountToSettleAsset = cashBalance.neg(); cashBalance = 0; } else { // A partial settlement of the debt require(amountToSettleAsset <= cashBalance.neg(), "Invalid amount to settle"); cashBalance = cashBalance.add(amountToSettleAsset); } // NOTE: we do not update HAS_CASH_DEBT here because it is possible that the other balances // also have cash debts if (cashBalance == 0 && nTokenBalance == 0) { accountContext.setActiveCurrency( cashGroup.currencyId, false, Constants.ACTIVE_IN_BALANCES ); } _setBalanceStorage( account, cashGroup.currencyId, cashBalance, nTokenBalance, lastClaimTime, accountIncentiveDebt ); // Emit the event here, we do not call finalize emit CashBalanceChange(account, cashGroup.currencyId, amountToSettleAsset); return amountToSettleAsset; } /** * @notice A special balance storage method for fCash liquidation to reduce the bytecode size. */ function setBalanceStorageForfCashLiquidation( address account, AccountContext memory accountContext, uint16 currencyId, int256 netCashChange ) internal { (int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt) = getBalanceStorage(account, currencyId); int256 newCashBalance = cashBalance.add(netCashChange); // If a cash balance is negative already we cannot put an account further into debt. In this case // the netCashChange must be positive so that it is coming out of debt. if (newCashBalance < 0) { require(netCashChange > 0, "Neg Cash"); // NOTE: HAS_CASH_DEBT cannot be extinguished except by a free collateral check // where all balances are examined. In this case the has cash debt flag should // already be set (cash balances cannot get more negative) but we do it again // here just to be safe. accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT; } bool isActive = newCashBalance != 0 || nTokenBalance != 0; accountContext.setActiveCurrency(currencyId, isActive, Constants.ACTIVE_IN_BALANCES); // Emit the event here, we do not call finalize emit CashBalanceChange(account, currencyId, netCashChange); _setBalanceStorage( account, currencyId, newCashBalance, nTokenBalance, lastClaimTime, accountIncentiveDebt ); } /// @notice Helper method for settling the output of the SettleAssets method function finalizeSettleAmounts( address account, AccountContext memory accountContext, SettleAmount[] memory settleAmounts ) internal { for (uint256 i = 0; i < settleAmounts.length; i++) { SettleAmount memory amt = settleAmounts[i]; if (amt.netCashChange == 0) continue; ( int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt ) = getBalanceStorage(account, amt.currencyId); cashBalance = cashBalance.add(amt.netCashChange); accountContext.setActiveCurrency( amt.currencyId, cashBalance != 0 || nTokenBalance != 0, Constants.ACTIVE_IN_BALANCES ); if (cashBalance < 0) { accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT; } emit CashBalanceChange( account, uint16(amt.currencyId), amt.netCashChange ); _setBalanceStorage( account, amt.currencyId, cashBalance, nTokenBalance, lastClaimTime, accountIncentiveDebt ); } } /// @notice Special method for setting balance storage for nToken function setBalanceStorageForNToken( address nTokenAddress, uint256 currencyId, int256 cashBalance ) internal { require(cashBalance >= 0); // dev: invalid nToken cash balance _setBalanceStorage(nTokenAddress, currencyId, cashBalance, 0, 0, 0); } /// @notice increments fees to the reserve function incrementFeeToReserve(uint256 currencyId, int256 fee) internal { require(fee >= 0); // dev: invalid fee // prettier-ignore (int256 totalReserve, /* */, /* */, /* */) = getBalanceStorage(Constants.RESERVE, currencyId); totalReserve = totalReserve.add(fee); _setBalanceStorage(Constants.RESERVE, currencyId, totalReserve, 0, 0, 0); emit ReserveFeeAccrued(uint16(currencyId), fee); } /// @notice harvests excess reserve balance function harvestExcessReserveBalance(uint16 currencyId, int256 reserve, int256 assetInternalRedeemAmount) internal { // parameters are validated by the caller reserve = reserve.subNoNeg(assetInternalRedeemAmount); _setBalanceStorage(Constants.RESERVE, currencyId, reserve, 0, 0, 0); emit ExcessReserveBalanceHarvested(currencyId, assetInternalRedeemAmount); } /// @notice sets the reserve balance, see TreasuryAction.setReserveCashBalance function setReserveCashBalance(uint16 currencyId, int256 newBalance) internal { require(newBalance >= 0); // dev: invalid balance _setBalanceStorage(Constants.RESERVE, currencyId, newBalance, 0, 0, 0); emit ReserveBalanceUpdated(currencyId, newBalance); } /// @notice Sets internal balance storage. function _setBalanceStorage( address account, uint256 currencyId, int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt ) private { mapping(address => mapping(uint256 => BalanceStorage)) storage store = LibStorage.getBalanceStorage(); BalanceStorage storage balanceStorage = store[account][currencyId]; require(cashBalance >= type(int88).min && cashBalance <= type(int88).max); // dev: stored cash balance overflow // Allows for 12 quadrillion nToken balance in 1e8 decimals before overflow require(nTokenBalance >= 0 && nTokenBalance <= type(uint80).max); // dev: stored nToken balance overflow if (lastClaimTime == 0) { // In this case the account has migrated and we set the accountIncentiveDebt // The maximum NOTE supply is 100_000_000e8 (1e16) which is less than 2^56 (7.2e16) so we should never // encounter an overflow for accountIncentiveDebt require(accountIncentiveDebt <= type(uint56).max); // dev: account incentive debt overflow balanceStorage.accountIncentiveDebt = uint56(accountIncentiveDebt); } else { // In this case the last claim time has not changed and we do not update the last integral supply // (stored in the accountIncentiveDebt position) require(lastClaimTime == balanceStorage.lastClaimTime); } balanceStorage.lastClaimTime = uint32(lastClaimTime); balanceStorage.nTokenBalance = uint80(nTokenBalance); balanceStorage.cashBalance = int88(cashBalance); } /// @notice Gets internal balance storage, nTokens are stored alongside cash balances function getBalanceStorage(address account, uint256 currencyId) internal view returns ( int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt ) { mapping(address => mapping(uint256 => BalanceStorage)) storage store = LibStorage.getBalanceStorage(); BalanceStorage storage balanceStorage = store[account][currencyId]; nTokenBalance = balanceStorage.nTokenBalance; lastClaimTime = balanceStorage.lastClaimTime; if (lastClaimTime > 0) { // NOTE: this is only necessary to support the deprecated integral supply values, which are stored // in the accountIncentiveDebt slot accountIncentiveDebt = FloatingPoint56.unpackFrom56Bits(balanceStorage.accountIncentiveDebt); } else { accountIncentiveDebt = balanceStorage.accountIncentiveDebt; } cashBalance = balanceStorage.cashBalance; } /// @notice Loads a balance state memory object /// @dev Balance state objects occupy a lot of memory slots, so this method allows /// us to reuse them if possible function loadBalanceState( BalanceState memory balanceState, address account, uint16 currencyId, AccountContext memory accountContext ) internal view { require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id balanceState.currencyId = currencyId; if (accountContext.isActiveInBalances(currencyId)) { ( balanceState.storedCashBalance, balanceState.storedNTokenBalance, balanceState.lastClaimTime, balanceState.accountIncentiveDebt ) = getBalanceStorage(account, currencyId); } else { balanceState.storedCashBalance = 0; balanceState.storedNTokenBalance = 0; balanceState.lastClaimTime = 0; balanceState.accountIncentiveDebt = 0; } balanceState.netCashChange = 0; balanceState.netAssetTransferInternalPrecision = 0; balanceState.netNTokenTransfer = 0; balanceState.netNTokenSupplyChange = 0; } /// @notice Used when manually claiming incentives in nTokenAction. Also sets the balance state /// to storage to update the accountIncentiveDebt. lastClaimTime will be set to zero as accounts /// are migrated to the new incentive calculation function claimIncentivesManual(BalanceState memory balanceState, address account) internal returns (uint256 incentivesClaimed) { incentivesClaimed = Incentives.claimIncentives( balanceState, account, balanceState.storedNTokenBalance.toUint() ); _setBalanceStorage( account, balanceState.currencyId, balanceState.storedCashBalance, balanceState.storedNTokenBalance, balanceState.lastClaimTime, balanceState.accountIncentiveDebt ); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./TokenHandler.sol"; import "../nToken/nTokenHandler.sol"; import "../nToken/nTokenSupply.sol"; import "../../math/SafeInt256.sol"; import "../../external/MigrateIncentives.sol"; import "../../../interfaces/notional/IRewarder.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library Incentives { using SafeMath for uint256; using SafeInt256 for int256; /// @notice Calculates the total incentives to claim including those claimed under the previous /// less accurate calculation. Once an account is migrated it will only claim incentives under /// the more accurate regime function calculateIncentivesToClaim( BalanceState memory balanceState, address tokenAddress, uint256 accumulatedNOTEPerNToken, uint256 finalNTokenBalance ) internal view returns (uint256 incentivesToClaim) { if (balanceState.lastClaimTime > 0) { // If lastClaimTime is set then the account had incentives under the // previous regime. Will calculate the final amount of incentives to claim here // under the previous regime. incentivesToClaim = MigrateIncentives.migrateAccountFromPreviousCalculation( tokenAddress, balanceState.storedNTokenBalance.toUint(), balanceState.lastClaimTime, // In this case the accountIncentiveDebt is stored as lastClaimIntegralSupply under // the old calculation balanceState.accountIncentiveDebt ); // This marks the account as migrated and lastClaimTime will no longer be used balanceState.lastClaimTime = 0; // This value will be set immediately after this, set this to zero so that the calculation // establishes a new baseline. balanceState.accountIncentiveDebt = 0; } // If an account was migrated then they have no accountIncentivesDebt and should accumulate // incentives based on their share since the new regime calculation started. // If an account is just initiating their nToken balance then storedNTokenBalance will be zero // and they will have no incentives to claim. // This calculation uses storedNTokenBalance which is the balance of the account up until this point, // this is important to ensure that the account does not claim for nTokens that they will mint or // redeem on a going forward basis. // The calculation below has the following precision: // storedNTokenBalance (INTERNAL_TOKEN_PRECISION) // MUL accumulatedNOTEPerNToken (INCENTIVE_ACCUMULATION_PRECISION) // DIV INCENTIVE_ACCUMULATION_PRECISION // = INTERNAL_TOKEN_PRECISION - (accountIncentivesDebt) INTERNAL_TOKEN_PRECISION incentivesToClaim = incentivesToClaim.add( balanceState.storedNTokenBalance.toUint() .mul(accumulatedNOTEPerNToken) .div(Constants.INCENTIVE_ACCUMULATION_PRECISION) .sub(balanceState.accountIncentiveDebt) ); // Update accountIncentivesDebt denominated in INTERNAL_TOKEN_PRECISION which marks the portion // of the accumulatedNOTE that the account no longer has a claim over. Use the finalNTokenBalance // here instead of storedNTokenBalance to mark the overall incentives claim that the account // does not have a claim over. We do not aggregate this value with the previous accountIncentiveDebt // because accumulatedNOTEPerNToken is already an aggregated value. // The calculation below has the following precision: // finalNTokenBalance (INTERNAL_TOKEN_PRECISION) // MUL accumulatedNOTEPerNToken (INCENTIVE_ACCUMULATION_PRECISION) // DIV INCENTIVE_ACCUMULATION_PRECISION // = INTERNAL_TOKEN_PRECISION balanceState.accountIncentiveDebt = finalNTokenBalance .mul(accumulatedNOTEPerNToken) .div(Constants.INCENTIVE_ACCUMULATION_PRECISION); } /// @notice Incentives must be claimed every time nToken balance changes. /// @dev BalanceState.accountIncentiveDebt is updated in place here function claimIncentives( BalanceState memory balanceState, address account, uint256 finalNTokenBalance ) internal returns (uint256 incentivesToClaim) { uint256 blockTime = block.timestamp; address tokenAddress = nTokenHandler.nTokenAddress(balanceState.currencyId); // This will updated the nToken storage and return what the accumulatedNOTEPerNToken // is up until this current block time in 1e18 precision uint256 accumulatedNOTEPerNToken = nTokenSupply.changeNTokenSupply( tokenAddress, balanceState.netNTokenSupplyChange, blockTime ); incentivesToClaim = calculateIncentivesToClaim( balanceState, tokenAddress, accumulatedNOTEPerNToken, finalNTokenBalance ); // If a secondary incentive rewarder is set, then call it IRewarder rewarder = nTokenHandler.getSecondaryRewarder(tokenAddress); if (address(rewarder) != address(0)) { rewarder.claimRewards( account, balanceState.currencyId, // When this method is called from finalize, the storedNTokenBalance has not // been updated to finalNTokenBalance yet so this is the balance before the change. balanceState.storedNTokenBalance.toUint(), finalNTokenBalance, // When the rewarder is called, totalSupply has been updated already so may need to // adjust its calculation using the net supply change figure here. Supply change // may be zero when nTokens are transferred. balanceState.netNTokenSupplyChange, incentivesToClaim ); } if (incentivesToClaim > 0) TokenHandler.transferIncentive(account, incentivesToClaim); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; import "../global/Constants.sol"; library SafeInt256 { int256 private constant _INT256_MIN = type(int256).min; /// @dev Returns the multiplication of two signed integers, reverting on /// overflow. /// Counterpart to Solidity's `*` operator. /// Requirements: /// - Multiplication cannot overflow. function mul(int256 a, int256 b) internal pure returns (int256 c) { c = a * b; if (a == -1) require (b == 0 || c / b == a); else require (a == 0 || c / a == b); } /// @dev Returns the integer division of two signed 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(int256 a, int256 b) internal pure returns (int256 c) { require(!(b == -1 && a == _INT256_MIN)); // dev: int256 div overflow // NOTE: solidity will automatically revert on divide by zero c = a / b; } function sub(int256 x, int256 y) internal pure returns (int256 z) { // taken from uniswap v3 require((z = x - y) <= x == (y >= 0)); } function add(int256 x, int256 y) internal pure returns (int256 z) { require((z = x + y) >= x == (y >= 0)); } function neg(int256 x) internal pure returns (int256 y) { return mul(-1, x); } function abs(int256 x) internal pure returns (int256) { if (x < 0) return neg(x); else return x; } function subNoNeg(int256 x, int256 y) internal pure returns (int256 z) { z = sub(x, y); require(z >= 0); // dev: int256 sub to negative return z; } /// @dev Calculates x * RATE_PRECISION / y while checking overflows function divInRatePrecision(int256 x, int256 y) internal pure returns (int256) { return div(mul(x, Constants.RATE_PRECISION), y); } /// @dev Calculates x * y / RATE_PRECISION while checking overflows function mulInRatePrecision(int256 x, int256 y) internal pure returns (int256) { return div(mul(x, y), Constants.RATE_PRECISION); } function toUint(int256 x) internal pure returns (uint256) { require(x >= 0); return uint256(x); } function toInt(uint256 x) internal pure returns (int256) { require (x <= uint256(type(int256).max)); // dev: toInt overflow return int256(x); } function max(int256 x, int256 y) internal pure returns (int256) { return x > y ? x : y; } function min(int256 x, int256 y) internal pure returns (int256) { return x < y ? x : y; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./Types.sol"; /** * @notice Storage layout for the system. Do not change this file once deployed, future storage * layouts must inherit this and increment the version number. */ contract StorageLayoutV1 { // The current maximum currency id uint16 internal maxCurrencyId; // Sets the state of liquidations being enabled during a paused state. Each of the four lower // bits can be turned on to represent one of the liquidation types being enabled. bytes1 internal liquidationEnabledState; // Set to true once the system has been initialized bool internal hasInitialized; /* Authentication Mappings */ // This is set to the timelock contract to execute governance functions address public owner; // This is set to an address of a router that can only call governance actions address public pauseRouter; // This is set to an address of a router that can only call governance actions address public pauseGuardian; // On upgrades this is set in the case that the pause router is used to pass the rollback check address internal rollbackRouterImplementation; // A blanket allowance for a spender to transfer any of an account's nTokens. This would allow a user // to set an allowance on all nTokens for a particular integrating contract system. // owner => spender => transferAllowance mapping(address => mapping(address => uint256)) internal nTokenWhitelist; // Individual transfer allowances for nTokens used for ERC20 // owner => spender => currencyId => transferAllowance mapping(address => mapping(address => mapping(uint16 => uint256))) internal nTokenAllowance; // Transfer operators // Mapping from a global ERC1155 transfer operator contract to an approval value for it mapping(address => bool) internal globalTransferOperator; // Mapping from an account => operator => approval status for that operator. This is a specific // approval between two addresses for ERC1155 transfers. mapping(address => mapping(address => bool)) internal accountAuthorizedTransferOperator; // Approval for a specific contract to use the `batchBalanceAndTradeActionWithCallback` method in // BatchAction.sol, can only be set by governance mapping(address => bool) internal authorizedCallbackContract; // Reverse mapping from token addresses to currency ids, only used for referencing in views // and checking for duplicate token listings. mapping(address => uint16) internal tokenAddressToCurrencyId; // Reentrancy guard uint256 internal reentrancyStatus; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../external/SettleAssetsExternal.sol"; import "../internal/AccountContextHandler.sol"; import "../internal/valuation/FreeCollateral.sol"; /// @title Externally deployed library for free collateral calculations library FreeCollateralExternal { using AccountContextHandler for AccountContext; /// @notice Returns the ETH denominated free collateral of an account, represents the amount of /// debt that the account can incur before liquidation. If an account's assets need to be settled this /// will revert, either settle the account or use the off chain SDK to calculate free collateral. /// @dev Called via the Views.sol method to return an account's free collateral. Does not work /// for the nToken, the nToken does not have an account context. /// @param account account to calculate free collateral for /// @return total free collateral in ETH w/ 8 decimal places /// @return array of net local values in asset values ordered by currency id function getFreeCollateralView(address account) external view returns (int256, int256[] memory) { AccountContext memory accountContext = AccountContextHandler.getAccountContext(account); // The internal free collateral function does not account for settled assets. The Notional SDK // can calculate the free collateral off chain if required at this point. require(!accountContext.mustSettleAssets(), "Assets not settled"); return FreeCollateral.getFreeCollateralView(account, accountContext, block.timestamp); } /// @notice Calculates free collateral and will revert if it falls below zero. If the account context /// must be updated due to changes in debt settings, will update. Cannot check free collateral if assets /// need to be settled first. /// @dev Cannot be called directly by users, used during various actions that require an FC check. Must be /// called before the end of any transaction for accounts where FC can decrease. /// @param account account to calculate free collateral for function checkFreeCollateralAndRevert(address account) external { AccountContext memory accountContext = AccountContextHandler.getAccountContext(account); require(!accountContext.mustSettleAssets(), "Assets not settled"); (int256 ethDenominatedFC, bool updateContext) = FreeCollateral.getFreeCollateralStateful(account, accountContext, block.timestamp); if (updateContext) { accountContext.setAccountContext(account); } require(ethDenominatedFC >= 0, "Insufficient free collateral"); } /// @notice Calculates liquidation factors for an account /// @dev Only called internally by liquidation actions, does some initial validation of currencies. If a currency is /// specified that the account does not have, a asset available figure of zero will be returned. If this is the case then /// liquidation actions will revert. /// @dev an ntoken account will return 0 FC and revert if called /// @param account account to liquidate /// @param localCurrencyId currency that the debts are denominated in /// @param collateralCurrencyId collateral currency to liquidate against, set to zero in the case of local currency liquidation /// @return accountContext the accountContext of the liquidated account /// @return factors struct of relevant factors for liquidation /// @return portfolio the portfolio array of the account (bitmap accounts will return an empty array) function getLiquidationFactors( address account, uint256 localCurrencyId, uint256 collateralCurrencyId ) external returns ( AccountContext memory accountContext, LiquidationFactors memory factors, PortfolioAsset[] memory portfolio ) { accountContext = AccountContextHandler.getAccountContext(account); if (accountContext.mustSettleAssets()) { accountContext = SettleAssetsExternal.settleAccount(account, accountContext); } if (accountContext.isBitmapEnabled()) { // A bitmap currency can only ever hold debt in this currency require(localCurrencyId == accountContext.bitmapCurrencyId); } (factors, portfolio) = FreeCollateral.getLiquidationFactors( account, accountContext, block.timestamp, localCurrencyId, collateralCurrencyId ); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; interface nTokenERC20 { event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); function nTokenTotalSupply(address nTokenAddress) external view returns (uint256); function nTokenTransferAllowance( uint16 currencyId, address owner, address spender ) external view returns (uint256); function nTokenBalanceOf(uint16 currencyId, address account) external view returns (uint256); function nTokenTransferApprove( uint16 currencyId, address owner, address spender, uint256 amount ) external returns (bool); function nTokenTransfer( uint16 currencyId, address from, address to, uint256 amount ) external returns (bool); function nTokenTransferFrom( uint16 currencyId, address spender, address from, address to, uint256 amount ) external returns (bool); function nTokenTransferApproveAll(address spender, uint256 amount) external returns (bool); function nTokenClaimIncentives() external returns (uint256); function nTokenPresentValueAssetDenominated(uint16 currencyId) external view returns (int256); function nTokenPresentValueUnderlyingDenominated(uint16 currencyId) external view returns (int256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such 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. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.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, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { 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"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { 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, reverting 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) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * 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); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../interfaces/chainlink/AggregatorV2V3Interface.sol"; import "../../interfaces/notional/AssetRateAdapter.sol"; /// @notice Different types of internal tokens /// - UnderlyingToken: underlying asset for a cToken (except for Ether) /// - cToken: Compound interest bearing token /// - cETH: Special handling for cETH tokens /// - Ether: the one and only /// - NonMintable: tokens that do not have an underlying (therefore not cTokens) /// - aToken: Aave interest bearing tokens enum TokenType {UnderlyingToken, cToken, cETH, Ether, NonMintable, aToken} /// @notice Specifies the different trade action types in the system. Each trade action type is /// encoded in a tightly packed bytes32 object. Trade action type is the first big endian byte of the /// 32 byte trade action object. The schemas for each trade action type are defined below. enum TradeActionType { // (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 minImpliedRate, uint120 unused) Lend, // (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 maxImpliedRate, uint128 unused) Borrow, // (uint8 TradeActionType, uint8 MarketIndex, uint88 assetCashAmount, uint32 minImpliedRate, uint32 maxImpliedRate, uint88 unused) AddLiquidity, // (uint8 TradeActionType, uint8 MarketIndex, uint88 tokenAmount, uint32 minImpliedRate, uint32 maxImpliedRate, uint88 unused) RemoveLiquidity, // (uint8 TradeActionType, uint32 Maturity, int88 fCashResidualAmount, uint128 unused) PurchaseNTokenResidual, // (uint8 TradeActionType, address CounterpartyAddress, int88 fCashAmountToSettle) SettleCashDebt } /// @notice Specifies different deposit actions that can occur during BalanceAction or BalanceActionWithTrades enum DepositActionType { // No deposit action None, // Deposit asset cash, depositActionAmount is specified in asset cash external precision DepositAsset, // Deposit underlying tokens that are mintable to asset cash, depositActionAmount is specified in underlying token // external precision DepositUnderlying, // Deposits specified asset cash external precision amount into an nToken and mints the corresponding amount of // nTokens into the account DepositAssetAndMintNToken, // Deposits specified underlying in external precision, mints asset cash, and uses that asset cash to mint nTokens DepositUnderlyingAndMintNToken, // Redeems an nToken balance to asset cash. depositActionAmount is specified in nToken precision. Considered a deposit action // because it deposits asset cash into an account. If there are fCash residuals that cannot be sold off, will revert. RedeemNToken, // Converts specified amount of asset cash balance already in Notional to nTokens. depositActionAmount is specified in // Notional internal 8 decimal precision. ConvertCashToNToken } /// @notice Used internally for PortfolioHandler state enum AssetStorageState {NoChange, Update, Delete, RevertIfStored} /****** Calldata objects ******/ /// @notice Defines a balance action for batchAction struct BalanceAction { // Deposit action to take (if any) DepositActionType actionType; uint16 currencyId; // Deposit action amount must correspond to the depositActionType, see documentation above. uint256 depositActionAmount; // Withdraw an amount of asset cash specified in Notional internal 8 decimal precision uint256 withdrawAmountInternalPrecision; // If set to true, will withdraw entire cash balance. Useful if there may be an unknown amount of asset cash // residual left from trading. bool withdrawEntireCashBalance; // If set to true, will redeem asset cash to the underlying token on withdraw. bool redeemToUnderlying; } /// @notice Defines a balance action with a set of trades to do as well struct BalanceActionWithTrades { DepositActionType actionType; uint16 currencyId; uint256 depositActionAmount; uint256 withdrawAmountInternalPrecision; bool withdrawEntireCashBalance; bool redeemToUnderlying; // Array of tightly packed 32 byte objects that represent trades. See TradeActionType documentation bytes32[] trades; } /****** In memory objects ******/ /// @notice Internal object that represents settled cash balances struct SettleAmount { uint256 currencyId; int256 netCashChange; } /// @notice Internal object that represents a token struct Token { address tokenAddress; bool hasTransferFee; int256 decimals; TokenType tokenType; uint256 maxCollateralBalance; } /// @notice Internal object that represents an nToken portfolio struct nTokenPortfolio { CashGroupParameters cashGroup; PortfolioState portfolioState; int256 totalSupply; int256 cashBalance; uint256 lastInitializedTime; bytes6 parameters; address tokenAddress; } /// @notice Internal object used during liquidation struct LiquidationFactors { address account; // Aggregate free collateral of the account denominated in ETH underlying, 8 decimal precision int256 netETHValue; // Amount of net local currency asset cash before haircuts and buffers available int256 localAssetAvailable; // Amount of net collateral currency asset cash before haircuts and buffers available int256 collateralAssetAvailable; // Haircut value of nToken holdings denominated in asset cash, will be local or collateral nTokens based // on liquidation type int256 nTokenHaircutAssetValue; // nToken parameters for calculating liquidation amount bytes6 nTokenParameters; // ETH exchange rate from local currency to ETH ETHRate localETHRate; // ETH exchange rate from collateral currency to ETH ETHRate collateralETHRate; // Asset rate for the local currency, used in cross currency calculations to calculate local asset cash required AssetRateParameters localAssetRate; // Used during currency liquidations if the account has liquidity tokens CashGroupParameters collateralCashGroup; // Used during currency liquidations if it is only a calculation, defaults to false bool isCalculation; } /// @notice Internal asset array portfolio state struct PortfolioState { // Array of currently stored assets PortfolioAsset[] storedAssets; // Array of new assets to add PortfolioAsset[] newAssets; uint256 lastNewAssetIndex; // Holds the length of stored assets after accounting for deleted assets uint256 storedAssetLength; } /// @notice In memory ETH exchange rate used during free collateral calculation. struct ETHRate { // The decimals (i.e. 10^rateDecimalPlaces) of the exchange rate, defined by the rate oracle int256 rateDecimals; // The exchange rate from base to ETH (if rate invert is required it is already done) int256 rate; // Amount of buffer as a multiple with a basis of 100 applied to negative balances. int256 buffer; // Amount of haircut as a multiple with a basis of 100 applied to positive balances int256 haircut; // Liquidation discount as a multiple with a basis of 100 applied to the exchange rate // as an incentive given to liquidators. int256 liquidationDiscount; } /// @notice Internal object used to handle balance state during a transaction struct BalanceState { uint16 currencyId; // Cash balance stored in balance state at the beginning of the transaction int256 storedCashBalance; // nToken balance stored at the beginning of the transaction int256 storedNTokenBalance; // The net cash change as a result of asset settlement or trading int256 netCashChange; // Net asset transfers into or out of the account int256 netAssetTransferInternalPrecision; // Net token transfers into or out of the account int256 netNTokenTransfer; // Net token supply change from minting or redeeming int256 netNTokenSupplyChange; // The last time incentives were claimed for this currency uint256 lastClaimTime; // Accumulator for incentives that the account no longer has a claim over uint256 accountIncentiveDebt; } /// @dev Asset rate used to convert between underlying cash and asset cash struct AssetRateParameters { // Address of the asset rate oracle AssetRateAdapter rateOracle; // The exchange rate from base to quote (if invert is required it is already done) int256 rate; // The decimals of the underlying, the rate converts to the underlying decimals int256 underlyingDecimals; } /// @dev Cash group when loaded into memory struct CashGroupParameters { uint16 currencyId; uint256 maxMarketIndex; AssetRateParameters assetRate; bytes32 data; } /// @dev A portfolio asset when loaded in memory struct PortfolioAsset { // Asset currency id uint256 currencyId; uint256 maturity; // Asset type, fCash or liquidity token. uint256 assetType; // fCash amount or liquidity token amount int256 notional; // Used for managing portfolio asset state uint256 storageSlot; // The state of the asset for when it is written to storage AssetStorageState storageState; } /// @dev Market object as represented in memory struct MarketParameters { bytes32 storageSlot; uint256 maturity; // Total amount of fCash available for purchase in the market. int256 totalfCash; // Total amount of cash available for purchase in the market. int256 totalAssetCash; // Total amount of liquidity tokens (representing a claim on liquidity) in the market. int256 totalLiquidity; // This is the previous annualized interest rate in RATE_PRECISION that the market traded // at. This is used to calculate the rate anchor to smooth interest rates over time. uint256 lastImpliedRate; // Time lagged version of lastImpliedRate, used to value fCash assets at market rates while // remaining resistent to flash loan attacks. uint256 oracleRate; // This is the timestamp of the previous trade uint256 previousTradeTime; } /****** Storage objects ******/ /// @dev Token object in storage: /// 20 bytes for token address /// 1 byte for hasTransferFee /// 1 byte for tokenType /// 1 byte for tokenDecimals /// 9 bytes for maxCollateralBalance (may not always be set) struct TokenStorage { // Address of the token address tokenAddress; // Transfer fees will change token deposit behavior bool hasTransferFee; TokenType tokenType; uint8 decimalPlaces; // Upper limit on how much of this token the contract can hold at any time uint72 maxCollateralBalance; } /// @dev Exchange rate object as it is represented in storage, total storage is 25 bytes. struct ETHRateStorage { // Address of the rate oracle AggregatorV2V3Interface rateOracle; // The decimal places of precision that the rate oracle uses uint8 rateDecimalPlaces; // True of the exchange rate must be inverted bool mustInvert; // NOTE: both of these governance values are set with BUFFER_DECIMALS precision // Amount of buffer to apply to the exchange rate for negative balances. uint8 buffer; // Amount of haircut to apply to the exchange rate for positive balances uint8 haircut; // Liquidation discount in percentage point terms, 106 means a 6% discount uint8 liquidationDiscount; } /// @dev Asset rate oracle object as it is represented in storage, total storage is 21 bytes. struct AssetRateStorage { // Address of the rate oracle AssetRateAdapter rateOracle; // The decimal places of the underlying asset uint8 underlyingDecimalPlaces; } /// @dev Governance parameters for a cash group, total storage is 9 bytes + 7 bytes for liquidity token haircuts /// and 7 bytes for rate scalars, total of 23 bytes. Note that this is stored packed in the storage slot so there /// are no indexes stored for liquidityTokenHaircuts or rateScalars, maxMarketIndex is used instead to determine the /// length. struct CashGroupSettings { // Index of the AMMs on chain that will be made available. Idiosyncratic fCash // that is dated less than the longest AMM will be tradable. uint8 maxMarketIndex; // Time window in 5 minute increments that the rate oracle will be averaged over uint8 rateOracleTimeWindow5Min; // Total fees per trade, specified in BPS uint8 totalFeeBPS; // Share of the fees given to the protocol, denominated in percentage uint8 reserveFeeShare; // Debt buffer specified in 5 BPS increments uint8 debtBuffer5BPS; // fCash haircut specified in 5 BPS increments uint8 fCashHaircut5BPS; // If an account has a negative cash balance, it can be settled by incurring debt at the 3 month market. This // is the basis points for the penalty rate that will be added the current 3 month oracle rate. uint8 settlementPenaltyRate5BPS; // If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for uint8 liquidationfCashHaircut5BPS; // If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for uint8 liquidationDebtBuffer5BPS; // Liquidity token haircut applied to cash claims, specified as a percentage between 0 and 100 uint8[] liquidityTokenHaircuts; // Rate scalar used to determine the slippage of the market uint8[] rateScalars; } /// @dev Holds account level context information used to determine settlement and /// free collateral actions. Total storage is 28 bytes struct AccountContext { // Used to check when settlement must be triggered on an account uint40 nextSettleTime; // For lenders that never incur debt, we use this flag to skip the free collateral check. bytes1 hasDebt; // Length of the account's asset array uint8 assetArrayLength; // If this account has bitmaps set, this is the corresponding currency id uint16 bitmapCurrencyId; // 9 total active currencies possible (2 bytes each) bytes18 activeCurrencies; } /// @dev Holds nToken context information mapped via the nToken address, total storage is /// 16 bytes struct nTokenContext { // Currency id that the nToken represents uint16 currencyId; // Annual incentive emission rate denominated in WHOLE TOKENS (multiply by // INTERNAL_TOKEN_PRECISION to get the actual rate) uint32 incentiveAnnualEmissionRate; // The last block time at utc0 that the nToken was initialized at, zero if it // has never been initialized uint32 lastInitializedTime; // Length of the asset array, refers to the number of liquidity tokens an nToken // currently holds uint8 assetArrayLength; // Each byte is a specific nToken parameter bytes5 nTokenParameters; // Reserved bytes for future usage bytes15 _unused; // Set to true if a secondary rewarder is set bool hasSecondaryRewarder; } /// @dev Holds account balance information, total storage 32 bytes struct BalanceStorage { // Number of nTokens held by the account uint80 nTokenBalance; // Last time the account claimed their nTokens uint32 lastClaimTime; // Incentives that the account no longer has a claim over uint56 accountIncentiveDebt; // Cash balance of the account int88 cashBalance; } /// @dev Holds information about a settlement rate, total storage 25 bytes struct SettlementRateStorage { uint40 blockTime; uint128 settlementRate; uint8 underlyingDecimalPlaces; } /// @dev Holds information about a market, total storage is 42 bytes so this spans /// two storage words struct MarketStorage { // Total fCash in the market uint80 totalfCash; // Total asset cash in the market uint80 totalAssetCash; // Last annualized interest rate the market traded at uint32 lastImpliedRate; // Last recorded oracle rate for the market uint32 oracleRate; // Last time a trade was made uint32 previousTradeTime; // This is stored in slot + 1 uint80 totalLiquidity; } struct ifCashStorage { // Notional amount of fCash at the slot, limited to int128 to allow for // future expansion int128 notional; } /// @dev A single portfolio asset in storage, total storage of 19 bytes struct PortfolioAssetStorage { // Currency Id for the asset uint16 currencyId; // Maturity of the asset uint40 maturity; // Asset type (fCash or Liquidity Token marker) uint8 assetType; // Notional int88 notional; } /// @dev nToken total supply factors for the nToken, includes factors related /// to claiming incentives, total storage 32 bytes. This is the deprecated version struct nTokenTotalSupplyStorage_deprecated { // Total supply of the nToken uint96 totalSupply; // Integral of the total supply used for calculating the average total supply uint128 integralTotalSupply; // Last timestamp the supply value changed, used for calculating the integralTotalSupply uint32 lastSupplyChangeTime; } /// @dev nToken total supply factors for the nToken, includes factors related /// to claiming incentives, total storage 32 bytes. struct nTokenTotalSupplyStorage { // Total supply of the nToken uint96 totalSupply; // How many NOTE incentives should be issued per nToken in 1e18 precision uint128 accumulatedNOTEPerNToken; // Last timestamp when the accumulation happened uint32 lastAccumulatedTime; } /// @dev Used in view methods to return account balances in a developer friendly manner struct AccountBalance { uint16 currencyId; int256 cashBalance; int256 nTokenBalance; uint256 lastClaimTime; uint256 accountIncentiveDebt; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; import "./AggregatorInterface.sol"; import "./AggregatorV3Interface.sol"; interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface { } // SPDX-License-Identifier: GPL-v3 pragma solidity >=0.7.0; /// @notice Used as a wrapper for tokens that are interest bearing for an /// underlying token. Follows the cToken interface, however, can be adapted /// for other interest bearing tokens. interface AssetRateAdapter { function token() external view returns (address); function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); function underlying() external view returns (address); function getExchangeRateStateful() external returns (int256); function getExchangeRateView() external view returns (int256); function getAnnualizedSupplyRate() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; interface AggregatorInterface { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); function latestRound() external view returns (uint256); function getAnswer(uint256 roundId) external view returns (int256); function getTimestamp(uint256 roundId) external view returns (uint256); event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt); event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./Market.sol"; import "./AssetRate.sol"; import "./DateTime.sol"; import "../../global/LibStorage.sol"; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../../math/SafeInt256.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library CashGroup { using SafeMath for uint256; using SafeInt256 for int256; using AssetRate for AssetRateParameters; using Market for MarketParameters; // Bit number references for each parameter in the 32 byte word (0-indexed) uint256 private constant MARKET_INDEX_BIT = 31; uint256 private constant RATE_ORACLE_TIME_WINDOW_BIT = 30; uint256 private constant TOTAL_FEE_BIT = 29; uint256 private constant RESERVE_FEE_SHARE_BIT = 28; uint256 private constant DEBT_BUFFER_BIT = 27; uint256 private constant FCASH_HAIRCUT_BIT = 26; uint256 private constant SETTLEMENT_PENALTY_BIT = 25; uint256 private constant LIQUIDATION_FCASH_HAIRCUT_BIT = 24; uint256 private constant LIQUIDATION_DEBT_BUFFER_BIT = 23; // 7 bytes allocated, one byte per market for the liquidity token haircut uint256 private constant LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT = 22; // 7 bytes allocated, one byte per market for the rate scalar uint256 private constant RATE_SCALAR_FIRST_BIT = 15; // Offsets for the bytes of the different parameters uint256 private constant MARKET_INDEX = (31 - MARKET_INDEX_BIT) * 8; uint256 private constant RATE_ORACLE_TIME_WINDOW = (31 - RATE_ORACLE_TIME_WINDOW_BIT) * 8; uint256 private constant TOTAL_FEE = (31 - TOTAL_FEE_BIT) * 8; uint256 private constant RESERVE_FEE_SHARE = (31 - RESERVE_FEE_SHARE_BIT) * 8; uint256 private constant DEBT_BUFFER = (31 - DEBT_BUFFER_BIT) * 8; uint256 private constant FCASH_HAIRCUT = (31 - FCASH_HAIRCUT_BIT) * 8; uint256 private constant SETTLEMENT_PENALTY = (31 - SETTLEMENT_PENALTY_BIT) * 8; uint256 private constant LIQUIDATION_FCASH_HAIRCUT = (31 - LIQUIDATION_FCASH_HAIRCUT_BIT) * 8; uint256 private constant LIQUIDATION_DEBT_BUFFER = (31 - LIQUIDATION_DEBT_BUFFER_BIT) * 8; uint256 private constant LIQUIDITY_TOKEN_HAIRCUT = (31 - LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT) * 8; uint256 private constant RATE_SCALAR = (31 - RATE_SCALAR_FIRST_BIT) * 8; /// @notice Returns the rate scalar scaled by time to maturity. The rate scalar multiplies /// the ln() portion of the liquidity curve as an inverse so it increases with time to /// maturity. The effect of the rate scalar on slippage must decrease with time to maturity. function getRateScalar( CashGroupParameters memory cashGroup, uint256 marketIndex, uint256 timeToMaturity ) internal pure returns (int256) { require(1 <= marketIndex && marketIndex <= cashGroup.maxMarketIndex); // dev: invalid market index uint256 offset = RATE_SCALAR + 8 * (marketIndex - 1); int256 scalar = int256(uint8(uint256(cashGroup.data >> offset))) * Constants.RATE_PRECISION; int256 rateScalar = scalar.mul(int256(Constants.IMPLIED_RATE_TIME)).div(SafeInt256.toInt(timeToMaturity)); // Rate scalar is denominated in RATE_PRECISION, it is unlikely to underflow in the // division above. require(rateScalar > 0); // dev: rate scalar underflow return rateScalar; } /// @notice Haircut on liquidity tokens to account for the risk associated with changes in the /// proportion of cash to fCash within the pool. This is set as a percentage less than or equal to 100. function getLiquidityHaircut(CashGroupParameters memory cashGroup, uint256 assetType) internal pure returns (uint8) { require( Constants.MIN_LIQUIDITY_TOKEN_INDEX <= assetType && assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX ); // dev: liquidity haircut invalid asset type uint256 offset = LIQUIDITY_TOKEN_HAIRCUT + 8 * (assetType - Constants.MIN_LIQUIDITY_TOKEN_INDEX); return uint8(uint256(cashGroup.data >> offset)); } /// @notice Total trading fee denominated in RATE_PRECISION with basis point increments function getTotalFee(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> TOTAL_FEE))) * Constants.BASIS_POINT; } /// @notice Percentage of the total trading fee that goes to the reserve function getReserveFeeShare(CashGroupParameters memory cashGroup) internal pure returns (int256) { return uint8(uint256(cashGroup.data >> RESERVE_FEE_SHARE)); } /// @notice fCash haircut for valuation denominated in rate precision with five basis point increments function getfCashHaircut(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> FCASH_HAIRCUT))) * Constants.FIVE_BASIS_POINTS; } /// @notice fCash debt buffer for valuation denominated in rate precision with five basis point increments function getDebtBuffer(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> DEBT_BUFFER))) * Constants.FIVE_BASIS_POINTS; } /// @notice Time window factor for the rate oracle denominated in seconds with five minute increments. function getRateOracleTimeWindow(CashGroupParameters memory cashGroup) internal pure returns (uint256) { // This is denominated in 5 minute increments in storage return uint256(uint8(uint256(cashGroup.data >> RATE_ORACLE_TIME_WINDOW))) * Constants.FIVE_MINUTES; } /// @notice Penalty rate for settling cash debts denominated in basis points function getSettlementPenalty(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> SETTLEMENT_PENALTY))) * Constants.FIVE_BASIS_POINTS; } /// @notice Haircut for positive fCash during liquidation denominated rate precision /// with five basis point increments function getLiquidationfCashHaircut(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> LIQUIDATION_FCASH_HAIRCUT))) * Constants.FIVE_BASIS_POINTS; } /// @notice Haircut for negative fCash during liquidation denominated rate precision /// with five basis point increments function getLiquidationDebtBuffer(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> LIQUIDATION_DEBT_BUFFER))) * Constants.FIVE_BASIS_POINTS; } function loadMarket( CashGroupParameters memory cashGroup, MarketParameters memory market, uint256 marketIndex, bool needsLiquidity, uint256 blockTime ) internal view { require(1 <= marketIndex && marketIndex <= cashGroup.maxMarketIndex, "Invalid market"); uint256 maturity = DateTime.getReferenceTime(blockTime).add(DateTime.getTradedMarket(marketIndex)); market.loadMarket( cashGroup.currencyId, maturity, blockTime, needsLiquidity, getRateOracleTimeWindow(cashGroup) ); } /// @notice Returns the linear interpolation between two market rates. The formula is /// slope = (longMarket.oracleRate - shortMarket.oracleRate) / (longMarket.maturity - shortMarket.maturity) /// interpolatedRate = slope * (assetMaturity - shortMarket.maturity) + shortMarket.oracleRate function interpolateOracleRate( uint256 shortMaturity, uint256 longMaturity, uint256 shortRate, uint256 longRate, uint256 assetMaturity ) internal pure returns (uint256) { require(shortMaturity < assetMaturity); // dev: cash group interpolation error, short maturity require(assetMaturity < longMaturity); // dev: cash group interpolation error, long maturity // It's possible that the rates are inverted where the short market rate > long market rate and // we will get an underflow here so we check for that if (longRate >= shortRate) { return (longRate - shortRate) .mul(assetMaturity - shortMaturity) // No underflow here, checked above .div(longMaturity - shortMaturity) .add(shortRate); } else { // In this case the slope is negative so: // interpolatedRate = shortMarket.oracleRate - slope * (assetMaturity - shortMarket.maturity) // NOTE: this subtraction should never overflow, the linear interpolation between two points above zero // cannot go below zero return shortRate.sub( // This is reversed to keep it it positive (shortRate - longRate) .mul(assetMaturity - shortMaturity) // No underflow here, checked above .div(longMaturity - shortMaturity) ); } } /// @dev Gets an oracle rate given any valid maturity. function calculateOracleRate( CashGroupParameters memory cashGroup, uint256 maturity, uint256 blockTime ) internal view returns (uint256) { (uint256 marketIndex, bool idiosyncratic) = DateTime.getMarketIndex(cashGroup.maxMarketIndex, maturity, blockTime); uint256 timeWindow = getRateOracleTimeWindow(cashGroup); if (!idiosyncratic) { return Market.getOracleRate(cashGroup.currencyId, maturity, timeWindow, blockTime); } else { uint256 referenceTime = DateTime.getReferenceTime(blockTime); // DateTime.getMarketIndex returns the market that is past the maturity if idiosyncratic uint256 longMaturity = referenceTime.add(DateTime.getTradedMarket(marketIndex)); uint256 longRate = Market.getOracleRate(cashGroup.currencyId, longMaturity, timeWindow, blockTime); uint256 shortMaturity; uint256 shortRate; if (marketIndex == 1) { // In this case the short market is the annualized asset supply rate shortMaturity = blockTime; shortRate = cashGroup.assetRate.getSupplyRate(); } else { // Minimum value for marketIndex here is 2 shortMaturity = referenceTime.add(DateTime.getTradedMarket(marketIndex - 1)); shortRate = Market.getOracleRate( cashGroup.currencyId, shortMaturity, timeWindow, blockTime ); } return interpolateOracleRate(shortMaturity, longMaturity, shortRate, longRate, maturity); } } function _getCashGroupStorageBytes(uint256 currencyId) private view returns (bytes32 data) { mapping(uint256 => bytes32) storage store = LibStorage.getCashGroupStorage(); return store[currencyId]; } /// @dev Helper method for validating maturities in ERC1155Action function getMaxMarketIndex(uint256 currencyId) internal view returns (uint8) { bytes32 data = _getCashGroupStorageBytes(currencyId); return uint8(data[MARKET_INDEX_BIT]); } /// @notice Checks all cash group settings for invalid values and sets them into storage function setCashGroupStorage(uint256 currencyId, CashGroupSettings calldata cashGroup) internal { // Due to the requirements of the yield curve we do not allow a cash group to have solely a 3 month market. // The reason is that borrowers will not have a further maturity to roll from their 3 month fixed to a 6 month // fixed. It also complicates the logic in the nToken initialization method. Additionally, we cannot have cash // groups with 0 market index, it has no effect. require(2 <= cashGroup.maxMarketIndex && cashGroup.maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: invalid market index" ); require( cashGroup.reserveFeeShare <= Constants.PERCENTAGE_DECIMALS, "CG: invalid reserve share" ); require(cashGroup.liquidityTokenHaircuts.length == cashGroup.maxMarketIndex); require(cashGroup.rateScalars.length == cashGroup.maxMarketIndex); // This is required so that fCash liquidation can proceed correctly require(cashGroup.liquidationfCashHaircut5BPS < cashGroup.fCashHaircut5BPS); require(cashGroup.liquidationDebtBuffer5BPS < cashGroup.debtBuffer5BPS); // Market indexes cannot decrease or they will leave fCash assets stranded in the future with no valuation curve uint8 previousMaxMarketIndex = getMaxMarketIndex(currencyId); require( previousMaxMarketIndex <= cashGroup.maxMarketIndex, "CG: market index cannot decrease" ); // Per cash group settings bytes32 data = (bytes32(uint256(cashGroup.maxMarketIndex)) | (bytes32(uint256(cashGroup.rateOracleTimeWindow5Min)) << RATE_ORACLE_TIME_WINDOW) | (bytes32(uint256(cashGroup.totalFeeBPS)) << TOTAL_FEE) | (bytes32(uint256(cashGroup.reserveFeeShare)) << RESERVE_FEE_SHARE) | (bytes32(uint256(cashGroup.debtBuffer5BPS)) << DEBT_BUFFER) | (bytes32(uint256(cashGroup.fCashHaircut5BPS)) << FCASH_HAIRCUT) | (bytes32(uint256(cashGroup.settlementPenaltyRate5BPS)) << SETTLEMENT_PENALTY) | (bytes32(uint256(cashGroup.liquidationfCashHaircut5BPS)) << LIQUIDATION_FCASH_HAIRCUT) | (bytes32(uint256(cashGroup.liquidationDebtBuffer5BPS)) << LIQUIDATION_DEBT_BUFFER)); // Per market group settings for (uint256 i = 0; i < cashGroup.liquidityTokenHaircuts.length; i++) { require( cashGroup.liquidityTokenHaircuts[i] <= Constants.PERCENTAGE_DECIMALS, "CG: invalid token haircut" ); data = data | (bytes32(uint256(cashGroup.liquidityTokenHaircuts[i])) << (LIQUIDITY_TOKEN_HAIRCUT + i * 8)); } for (uint256 i = 0; i < cashGroup.rateScalars.length; i++) { // Causes a divide by zero error require(cashGroup.rateScalars[i] != 0, "CG: invalid rate scalar"); data = data | (bytes32(uint256(cashGroup.rateScalars[i])) << (RATE_SCALAR + i * 8)); } mapping(uint256 => bytes32) storage store = LibStorage.getCashGroupStorage(); store[currencyId] = data; } /// @notice Deserialize the cash group storage bytes into a user friendly object function deserializeCashGroupStorage(uint256 currencyId) internal view returns (CashGroupSettings memory) { bytes32 data = _getCashGroupStorageBytes(currencyId); uint8 maxMarketIndex = uint8(data[MARKET_INDEX_BIT]); uint8[] memory tokenHaircuts = new uint8[](uint256(maxMarketIndex)); uint8[] memory rateScalars = new uint8[](uint256(maxMarketIndex)); for (uint8 i = 0; i < maxMarketIndex; i++) { tokenHaircuts[i] = uint8(data[LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT - i]); rateScalars[i] = uint8(data[RATE_SCALAR_FIRST_BIT - i]); } return CashGroupSettings({ maxMarketIndex: maxMarketIndex, rateOracleTimeWindow5Min: uint8(data[RATE_ORACLE_TIME_WINDOW_BIT]), totalFeeBPS: uint8(data[TOTAL_FEE_BIT]), reserveFeeShare: uint8(data[RESERVE_FEE_SHARE_BIT]), debtBuffer5BPS: uint8(data[DEBT_BUFFER_BIT]), fCashHaircut5BPS: uint8(data[FCASH_HAIRCUT_BIT]), settlementPenaltyRate5BPS: uint8(data[SETTLEMENT_PENALTY_BIT]), liquidationfCashHaircut5BPS: uint8(data[LIQUIDATION_FCASH_HAIRCUT_BIT]), liquidationDebtBuffer5BPS: uint8(data[LIQUIDATION_DEBT_BUFFER_BIT]), liquidityTokenHaircuts: tokenHaircuts, rateScalars: rateScalars }); } function _buildCashGroup(uint16 currencyId, AssetRateParameters memory assetRate) private view returns (CashGroupParameters memory) { bytes32 data = _getCashGroupStorageBytes(currencyId); uint256 maxMarketIndex = uint8(data[MARKET_INDEX_BIT]); return CashGroupParameters({ currencyId: currencyId, maxMarketIndex: maxMarketIndex, assetRate: assetRate, data: data }); } /// @notice Builds a cash group using a view version of the asset rate function buildCashGroupView(uint16 currencyId) internal view returns (CashGroupParameters memory) { AssetRateParameters memory assetRate = AssetRate.buildAssetRateView(currencyId); return _buildCashGroup(currencyId, assetRate); } /// @notice Builds a cash group using a stateful version of the asset rate function buildCashGroupStateful(uint16 currencyId) internal returns (CashGroupParameters memory) { AssetRateParameters memory assetRate = AssetRate.buildAssetRateStateful(currencyId); return _buildCashGroup(currencyId, assetRate); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./TransferAssets.sol"; import "../valuation/AssetHandler.sol"; import "../../math/SafeInt256.sol"; import "../../global/LibStorage.sol"; /// @notice Handles the management of an array of assets including reading from storage, inserting /// updating, deleting and writing back to storage. library PortfolioHandler { using SafeInt256 for int256; using AssetHandler for PortfolioAsset; // Mirror of LibStorage.MAX_PORTFOLIO_ASSETS uint256 private constant MAX_PORTFOLIO_ASSETS = 16; /// @notice Primarily used by the TransferAssets library function addMultipleAssets(PortfolioState memory portfolioState, PortfolioAsset[] memory assets) internal pure { for (uint256 i = 0; i < assets.length; i++) { PortfolioAsset memory asset = assets[i]; if (asset.notional == 0) continue; addAsset( portfolioState, asset.currencyId, asset.maturity, asset.assetType, asset.notional ); } } function _mergeAssetIntoArray( PortfolioAsset[] memory assetArray, uint256 currencyId, uint256 maturity, uint256 assetType, int256 notional ) private pure returns (bool) { for (uint256 i = 0; i < assetArray.length; i++) { PortfolioAsset memory asset = assetArray[i]; if ( asset.assetType != assetType || asset.currencyId != currencyId || asset.maturity != maturity ) continue; // Either of these storage states mean that some error in logic has occurred, we cannot // store this portfolio require( asset.storageState != AssetStorageState.Delete && asset.storageState != AssetStorageState.RevertIfStored ); // dev: portfolio handler deleted storage int256 newNotional = asset.notional.add(notional); // Liquidity tokens cannot be reduced below zero. if (AssetHandler.isLiquidityToken(assetType)) { require(newNotional >= 0); // dev: portfolio handler negative liquidity token balance } require(newNotional >= type(int88).min && newNotional <= type(int88).max); // dev: portfolio handler notional overflow asset.notional = newNotional; asset.storageState = AssetStorageState.Update; return true; } return false; } /// @notice Adds an asset to a portfolio state in memory (does not write to storage) /// @dev Ensures that only one version of an asset exists in a portfolio (i.e. does not allow two fCash assets of the same maturity /// to exist in a single portfolio). Also ensures that liquidity tokens do not have a negative notional. function addAsset( PortfolioState memory portfolioState, uint256 currencyId, uint256 maturity, uint256 assetType, int256 notional ) internal pure { if ( // Will return true if merged _mergeAssetIntoArray( portfolioState.storedAssets, currencyId, maturity, assetType, notional ) ) return; if (portfolioState.lastNewAssetIndex > 0) { bool merged = _mergeAssetIntoArray( portfolioState.newAssets, currencyId, maturity, assetType, notional ); if (merged) return; } // At this point if we have not merged the asset then append to the array // Cannot remove liquidity that the portfolio does not have if (AssetHandler.isLiquidityToken(assetType)) { require(notional >= 0); // dev: portfolio handler negative liquidity token balance } require(notional >= type(int88).min && notional <= type(int88).max); // dev: portfolio handler notional overflow // Need to provision a new array at this point if (portfolioState.lastNewAssetIndex == portfolioState.newAssets.length) { portfolioState.newAssets = _extendNewAssetArray(portfolioState.newAssets); } // Otherwise add to the new assets array. It should not be possible to add matching assets in a single transaction, we will // check this again when we write to storage. Assigning to memory directly here, do not allocate new memory via struct. PortfolioAsset memory newAsset = portfolioState.newAssets[portfolioState.lastNewAssetIndex]; newAsset.currencyId = currencyId; newAsset.maturity = maturity; newAsset.assetType = assetType; newAsset.notional = notional; newAsset.storageState = AssetStorageState.NoChange; portfolioState.lastNewAssetIndex += 1; } /// @dev Extends the new asset array if it is not large enough, this is likely to get a bit expensive if we do /// it too much function _extendNewAssetArray(PortfolioAsset[] memory newAssets) private pure returns (PortfolioAsset[] memory) { // Double the size of the new asset array every time we have to extend to reduce the number of times // that we have to extend it. This will go: 0, 1, 2, 4, 8 (probably stops there). uint256 newLength = newAssets.length == 0 ? 1 : newAssets.length * 2; PortfolioAsset[] memory extendedArray = new PortfolioAsset[](newLength); for (uint256 i = 0; i < newAssets.length; i++) { extendedArray[i] = newAssets[i]; } return extendedArray; } /// @notice Takes a portfolio state and writes it to storage. /// @dev This method should only be called directly by the nToken. Account updates to portfolios should happen via /// the storeAssetsAndUpdateContext call in the AccountContextHandler.sol library. /// @return updated variables to update the account context with /// hasDebt: whether or not the portfolio has negative fCash assets /// portfolioActiveCurrencies: a byte32 word with all the currencies in the portfolio /// uint8: the length of the storage array /// uint40: the new nextSettleTime for the portfolio function storeAssets(PortfolioState memory portfolioState, address account) internal returns ( bool, bytes32, uint8, uint40 ) { bool hasDebt; // NOTE: cannot have more than 16 assets or this byte object will overflow. Max assets is // set to 7 and the worst case during liquidation would be 7 liquidity tokens that generate // 7 additional fCash assets for a total of 14 assets. Although even in this case all assets // would be of the same currency so it would not change the end result of the active currency // calculation. bytes32 portfolioActiveCurrencies; uint256 nextSettleTime; for (uint256 i = 0; i < portfolioState.storedAssets.length; i++) { PortfolioAsset memory asset = portfolioState.storedAssets[i]; // NOTE: this is to prevent the storage of assets that have been modified in the AssetHandler // during valuation. require(asset.storageState != AssetStorageState.RevertIfStored); // Mark any zero notional assets as deleted if (asset.storageState != AssetStorageState.Delete && asset.notional == 0) { deleteAsset(portfolioState, i); } } // First delete assets from asset storage to maintain asset storage indexes for (uint256 i = 0; i < portfolioState.storedAssets.length; i++) { PortfolioAsset memory asset = portfolioState.storedAssets[i]; if (asset.storageState == AssetStorageState.Delete) { // Delete asset from storage uint256 currentSlot = asset.storageSlot; assembly { sstore(currentSlot, 0x00) } } else { if (asset.storageState == AssetStorageState.Update) { PortfolioAssetStorage storage assetStorage; uint256 currentSlot = asset.storageSlot; assembly { assetStorage.slot := currentSlot } _storeAsset(asset, assetStorage); } // Update portfolio context for every asset that is in storage, whether it is // updated in storage or not. (hasDebt, portfolioActiveCurrencies, nextSettleTime) = _updatePortfolioContext( asset, hasDebt, portfolioActiveCurrencies, nextSettleTime ); } } // Add new assets uint256 assetStorageLength = portfolioState.storedAssetLength; mapping(address => PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store = LibStorage.getPortfolioArrayStorage(); PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS] storage storageArray = store[account]; for (uint256 i = 0; i < portfolioState.newAssets.length; i++) { PortfolioAsset memory asset = portfolioState.newAssets[i]; if (asset.notional == 0) continue; require( asset.storageState != AssetStorageState.Delete && asset.storageState != AssetStorageState.RevertIfStored ); // dev: store assets deleted storage (hasDebt, portfolioActiveCurrencies, nextSettleTime) = _updatePortfolioContext( asset, hasDebt, portfolioActiveCurrencies, nextSettleTime ); _storeAsset(asset, storageArray[assetStorageLength]); assetStorageLength += 1; } // 16 is the maximum number of assets or portfolio active currencies will overflow at 32 bytes with // 2 bytes per currency require(assetStorageLength <= 16 && nextSettleTime <= type(uint40).max); // dev: portfolio return value overflow return ( hasDebt, portfolioActiveCurrencies, uint8(assetStorageLength), uint40(nextSettleTime) ); } /// @notice Updates context information during the store assets method function _updatePortfolioContext( PortfolioAsset memory asset, bool hasDebt, bytes32 portfolioActiveCurrencies, uint256 nextSettleTime ) private pure returns ( bool, bytes32, uint256 ) { uint256 settlementDate = asset.getSettlementDate(); // Tis will set it to the minimum settlement date if (nextSettleTime == 0 || nextSettleTime > settlementDate) { nextSettleTime = settlementDate; } hasDebt = hasDebt || asset.notional < 0; require(uint16(uint256(portfolioActiveCurrencies)) == 0); // dev: portfolio active currencies overflow portfolioActiveCurrencies = (portfolioActiveCurrencies >> 16) | (bytes32(asset.currencyId) << 240); return (hasDebt, portfolioActiveCurrencies, nextSettleTime); } /// @dev Encodes assets for storage function _storeAsset( PortfolioAsset memory asset, PortfolioAssetStorage storage assetStorage ) internal { require(0 < asset.currencyId && asset.currencyId <= Constants.MAX_CURRENCIES); // dev: encode asset currency id overflow require(0 < asset.maturity && asset.maturity <= type(uint40).max); // dev: encode asset maturity overflow require(0 < asset.assetType && asset.assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); // dev: encode asset type invalid require(type(int88).min <= asset.notional && asset.notional <= type(int88).max); // dev: encode asset notional overflow assetStorage.currencyId = uint16(asset.currencyId); assetStorage.maturity = uint40(asset.maturity); assetStorage.assetType = uint8(asset.assetType); assetStorage.notional = int88(asset.notional); } /// @notice Deletes an asset from a portfolio /// @dev This method should only be called during settlement, assets can only be removed from a portfolio before settlement /// by adding the offsetting negative position function deleteAsset(PortfolioState memory portfolioState, uint256 index) internal pure { require(index < portfolioState.storedAssets.length); // dev: stored assets bounds require(portfolioState.storedAssetLength > 0); // dev: stored assets length is zero PortfolioAsset memory assetToDelete = portfolioState.storedAssets[index]; require( assetToDelete.storageState != AssetStorageState.Delete && assetToDelete.storageState != AssetStorageState.RevertIfStored ); // dev: cannot delete asset portfolioState.storedAssetLength -= 1; uint256 maxActiveSlotIndex; uint256 maxActiveSlot; // The max active slot is the last storage slot where an asset exists, it's not clear where this will be in the // array so we search for it here. for (uint256 i; i < portfolioState.storedAssets.length; i++) { PortfolioAsset memory a = portfolioState.storedAssets[i]; if (a.storageSlot > maxActiveSlot && a.storageState != AssetStorageState.Delete) { maxActiveSlot = a.storageSlot; maxActiveSlotIndex = i; } } if (index == maxActiveSlotIndex) { // In this case we are deleting the asset with the max storage slot so no swap is necessary. assetToDelete.storageState = AssetStorageState.Delete; return; } // Swap the storage slots of the deleted asset with the last non-deleted asset in the array. Mark them accordingly // so that when we call store assets they will be updated appropriately PortfolioAsset memory assetToSwap = portfolioState.storedAssets[maxActiveSlotIndex]; ( assetToSwap.storageSlot, assetToDelete.storageSlot ) = ( assetToDelete.storageSlot, assetToSwap.storageSlot ); assetToSwap.storageState = AssetStorageState.Update; assetToDelete.storageState = AssetStorageState.Delete; } /// @notice Returns a portfolio array, will be sorted function getSortedPortfolio(address account, uint8 assetArrayLength) internal view returns (PortfolioAsset[] memory) { PortfolioAsset[] memory assets = _loadAssetArray(account, assetArrayLength); // No sorting required for length of 1 if (assets.length <= 1) return assets; _sortInPlace(assets); return assets; } /// @notice Builds a portfolio array from storage. The new assets hint parameter will /// be used to provision a new array for the new assets. This will increase gas efficiency /// so that we don't have to make copies when we extend the array. function buildPortfolioState( address account, uint8 assetArrayLength, uint256 newAssetsHint ) internal view returns (PortfolioState memory) { PortfolioState memory state; if (assetArrayLength == 0) return state; state.storedAssets = getSortedPortfolio(account, assetArrayLength); state.storedAssetLength = assetArrayLength; state.newAssets = new PortfolioAsset[](newAssetsHint); return state; } function _sortInPlace(PortfolioAsset[] memory assets) private pure { uint256 length = assets.length; uint256[] memory ids = new uint256[](length); for (uint256 k; k < length; k++) { PortfolioAsset memory asset = assets[k]; // Prepopulate the ids to calculate just once ids[k] = TransferAssets.encodeAssetId(asset.currencyId, asset.maturity, asset.assetType); } // Uses insertion sort uint256 i = 1; while (i < length) { uint256 j = i; while (j > 0 && ids[j - 1] > ids[j]) { // Swap j - 1 and j (ids[j - 1], ids[j]) = (ids[j], ids[j - 1]); (assets[j - 1], assets[j]) = (assets[j], assets[j - 1]); j--; } i++; } } function _loadAssetArray(address account, uint8 length) private view returns (PortfolioAsset[] memory) { // This will overflow the storage pointer require(length <= MAX_PORTFOLIO_ASSETS); mapping(address => PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store = LibStorage.getPortfolioArrayStorage(); PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS] storage storageArray = store[account]; PortfolioAsset[] memory assets = new PortfolioAsset[](length); for (uint256 i = 0; i < length; i++) { PortfolioAssetStorage storage assetStorage = storageArray[i]; PortfolioAsset memory asset = assets[i]; uint256 slot; assembly { slot := assetStorage.slot } asset.currencyId = assetStorage.currencyId; asset.maturity = assetStorage.maturity; asset.assetType = assetStorage.assetType; asset.notional = assetStorage.notional; asset.storageSlot = slot; } return assets; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./Types.sol"; import "./Constants.sol"; import "../../interfaces/notional/IRewarder.sol"; import "../../interfaces/aave/ILendingPool.sol"; library LibStorage { /// @dev Offset for the initial slot in lib storage, gives us this number of storage slots /// available in StorageLayoutV1 and all subsequent storage layouts that inherit from it. uint256 private constant STORAGE_SLOT_BASE = 1000000; /// @dev Set to MAX_TRADED_MARKET_INDEX * 2, Solidity does not allow assigning constants from imported values uint256 private constant NUM_NTOKEN_MARKET_FACTORS = 14; /// @dev Theoretical maximum for MAX_PORTFOLIO_ASSETS, however, we limit this to MAX_TRADED_MARKET_INDEX /// in practice. It is possible to exceed that value during liquidation up to 14 potential assets. uint256 private constant MAX_PORTFOLIO_ASSETS = 16; /// @dev Storage IDs for storage buckets. Each id maps to an internal storage /// slot used for a particular mapping /// WARNING: APPEND ONLY enum StorageId { Unused, AccountStorage, nTokenContext, nTokenAddress, nTokenDeposit, nTokenInitialization, Balance, Token, SettlementRate, CashGroup, Market, AssetsBitmap, ifCashBitmap, PortfolioArray, // WARNING: this nTokenTotalSupply storage object was used for a buggy version // of the incentives calculation. It should only be used for accounts who have // not claimed before the migration nTokenTotalSupply_deprecated, AssetRate, ExchangeRate, nTokenTotalSupply, SecondaryIncentiveRewarder, LendingPool } /// @dev Mapping from an account address to account context function getAccountStorage() internal pure returns (mapping(address => AccountContext) storage store) { uint256 slot = _getStorageSlot(StorageId.AccountStorage); assembly { store.slot := slot } } /// @dev Mapping from an nToken address to nTokenContext function getNTokenContextStorage() internal pure returns (mapping(address => nTokenContext) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenContext); assembly { store.slot := slot } } /// @dev Mapping from currency id to nTokenAddress function getNTokenAddressStorage() internal pure returns (mapping(uint256 => address) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenAddress); assembly { store.slot := slot } } /// @dev Mapping from currency id to uint32 fixed length array of /// deposit factors. Deposit shares and leverage thresholds are stored striped to /// reduce the number of storage reads. function getNTokenDepositStorage() internal pure returns (mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenDeposit); assembly { store.slot := slot } } /// @dev Mapping from currency id to fixed length array of initialization factors, /// stored striped like deposit shares. function getNTokenInitStorage() internal pure returns (mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenInitialization); assembly { store.slot := slot } } /// @dev Mapping from account to currencyId to it's balance storage for that currency function getBalanceStorage() internal pure returns (mapping(address => mapping(uint256 => BalanceStorage)) storage store) { uint256 slot = _getStorageSlot(StorageId.Balance); assembly { store.slot := slot } } /// @dev Mapping from currency id to a boolean for underlying or asset token to /// the TokenStorage function getTokenStorage() internal pure returns (mapping(uint256 => mapping(bool => TokenStorage)) storage store) { uint256 slot = _getStorageSlot(StorageId.Token); assembly { store.slot := slot } } /// @dev Mapping from currency id to maturity to its corresponding SettlementRate function getSettlementRateStorage() internal pure returns (mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store) { uint256 slot = _getStorageSlot(StorageId.SettlementRate); assembly { store.slot := slot } } /// @dev Mapping from currency id to maturity to its tightly packed cash group parameters function getCashGroupStorage() internal pure returns (mapping(uint256 => bytes32) storage store) { uint256 slot = _getStorageSlot(StorageId.CashGroup); assembly { store.slot := slot } } /// @dev Mapping from currency id to maturity to settlement date for a market function getMarketStorage() internal pure returns (mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store) { uint256 slot = _getStorageSlot(StorageId.Market); assembly { store.slot := slot } } /// @dev Mapping from account to currency id to its assets bitmap function getAssetsBitmapStorage() internal pure returns (mapping(address => mapping(uint256 => bytes32)) storage store) { uint256 slot = _getStorageSlot(StorageId.AssetsBitmap); assembly { store.slot := slot } } /// @dev Mapping from account to currency id to its maturity to its corresponding ifCash balance function getifCashBitmapStorage() internal pure returns (mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store) { uint256 slot = _getStorageSlot(StorageId.ifCashBitmap); assembly { store.slot := slot } } /// @dev Mapping from account to its fixed length array of portfolio assets function getPortfolioArrayStorage() internal pure returns (mapping(address => PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store) { uint256 slot = _getStorageSlot(StorageId.PortfolioArray); assembly { store.slot := slot } } function getDeprecatedNTokenTotalSupplyStorage() internal pure returns (mapping(address => nTokenTotalSupplyStorage_deprecated) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenTotalSupply_deprecated); assembly { store.slot := slot } } /// @dev Mapping from nToken address to its total supply values function getNTokenTotalSupplyStorage() internal pure returns (mapping(address => nTokenTotalSupplyStorage) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenTotalSupply); assembly { store.slot := slot } } /// @dev Returns the exchange rate between an underlying currency and asset for trading /// and free collateral. Mapping is from currency id to rate storage object. function getAssetRateStorage() internal pure returns (mapping(uint256 => AssetRateStorage) storage store) { uint256 slot = _getStorageSlot(StorageId.AssetRate); assembly { store.slot := slot } } /// @dev Returns the exchange rate between an underlying currency and ETH for free /// collateral purposes. Mapping is from currency id to rate storage object. function getExchangeRateStorage() internal pure returns (mapping(uint256 => ETHRateStorage) storage store) { uint256 slot = _getStorageSlot(StorageId.ExchangeRate); assembly { store.slot := slot } } /// @dev Returns the address of a secondary incentive rewarder for an nToken if it exists function getSecondaryIncentiveRewarder() internal pure returns (mapping(address => IRewarder) storage store) { uint256 slot = _getStorageSlot(StorageId.SecondaryIncentiveRewarder); assembly { store.slot := slot } } /// @dev Returns the address of the lending pool function getLendingPool() internal pure returns (LendingPoolStorage storage store) { uint256 slot = _getStorageSlot(StorageId.LendingPool); assembly { store.slot := slot } } /// @dev Get the storage slot given a storage ID. /// @param storageId An entry in `StorageId` /// @return slot The storage slot. function _getStorageSlot(StorageId storageId) private pure returns (uint256 slot) { // This should never overflow with a reasonable `STORAGE_SLOT_EXP` // because Solidity will do a range check on `storageId` during the cast. return uint256(storageId) + STORAGE_SLOT_BASE; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./AssetRate.sol"; import "./CashGroup.sol"; import "./DateTime.sol"; import "../balances/BalanceHandler.sol"; import "../../global/LibStorage.sol"; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../../math/SafeInt256.sol"; import "../../math/ABDKMath64x64.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library Market { using SafeMath for uint256; using SafeInt256 for int256; using CashGroup for CashGroupParameters; using AssetRate for AssetRateParameters; // Max positive value for a ABDK64x64 integer int256 private constant MAX64 = 0x7FFFFFFFFFFFFFFF; /// @notice Add liquidity to a market, assuming that it is initialized. If not then /// this method will revert and the market must be initialized first. /// Return liquidityTokens and negative fCash to the portfolio function addLiquidity(MarketParameters memory market, int256 assetCash) internal returns (int256 liquidityTokens, int256 fCash) { require(market.totalLiquidity > 0, "M: zero liquidity"); if (assetCash == 0) return (0, 0); require(assetCash > 0); // dev: negative asset cash liquidityTokens = market.totalLiquidity.mul(assetCash).div(market.totalAssetCash); // No need to convert this to underlying, assetCash / totalAssetCash is a unitless proportion. fCash = market.totalfCash.mul(assetCash).div(market.totalAssetCash); market.totalLiquidity = market.totalLiquidity.add(liquidityTokens); market.totalfCash = market.totalfCash.add(fCash); market.totalAssetCash = market.totalAssetCash.add(assetCash); _setMarketStorageForLiquidity(market); // Flip the sign to represent the LP's net position fCash = fCash.neg(); } /// @notice Remove liquidity from a market, assuming that it is initialized. /// Return assetCash and positive fCash to the portfolio function removeLiquidity(MarketParameters memory market, int256 tokensToRemove) internal returns (int256 assetCash, int256 fCash) { if (tokensToRemove == 0) return (0, 0); require(tokensToRemove > 0); // dev: negative tokens to remove assetCash = market.totalAssetCash.mul(tokensToRemove).div(market.totalLiquidity); fCash = market.totalfCash.mul(tokensToRemove).div(market.totalLiquidity); market.totalLiquidity = market.totalLiquidity.subNoNeg(tokensToRemove); market.totalfCash = market.totalfCash.subNoNeg(fCash); market.totalAssetCash = market.totalAssetCash.subNoNeg(assetCash); _setMarketStorageForLiquidity(market); } function executeTrade( MarketParameters memory market, CashGroupParameters memory cashGroup, int256 fCashToAccount, uint256 timeToMaturity, uint256 marketIndex ) internal returns (int256 netAssetCash) { int256 netAssetCashToReserve; (netAssetCash, netAssetCashToReserve) = calculateTrade( market, cashGroup, fCashToAccount, timeToMaturity, marketIndex ); MarketStorage storage marketStorage = _getMarketStoragePointer(market); _setMarketStorage( marketStorage, market.totalfCash, market.totalAssetCash, market.lastImpliedRate, market.oracleRate, market.previousTradeTime ); BalanceHandler.incrementFeeToReserve(cashGroup.currencyId, netAssetCashToReserve); } /// @notice Calculates the asset cash amount the results from trading fCashToAccount with the market. A positive /// fCashToAccount is equivalent of lending, a negative is borrowing. Updates the market state in memory. /// @param market the current market state /// @param cashGroup cash group configuration parameters /// @param fCashToAccount the fCash amount that will be deposited into the user's portfolio. The net change /// to the market is in the opposite direction. /// @param timeToMaturity number of seconds until maturity /// @return netAssetCash, netAssetCashToReserve function calculateTrade( MarketParameters memory market, CashGroupParameters memory cashGroup, int256 fCashToAccount, uint256 timeToMaturity, uint256 marketIndex ) internal view returns (int256, int256) { // We return false if there is not enough fCash to support this trade. // if fCashToAccount > 0 and totalfCash - fCashToAccount <= 0 then the trade will fail // if fCashToAccount < 0 and totalfCash > 0 then this will always pass if (market.totalfCash <= fCashToAccount) return (0, 0); // Calculates initial rate factors for the trade (int256 rateScalar, int256 totalCashUnderlying, int256 rateAnchor) = getExchangeRateFactors(market, cashGroup, timeToMaturity, marketIndex); // Calculates the exchange rate from cash to fCash before any liquidity fees // are applied int256 preFeeExchangeRate; { bool success; (preFeeExchangeRate, success) = _getExchangeRate( market.totalfCash, totalCashUnderlying, rateScalar, rateAnchor, fCashToAccount ); if (!success) return (0, 0); } // Given the exchange rate, returns the net cash amounts to apply to each of the // three relevant balances. (int256 netCashToAccount, int256 netCashToMarket, int256 netCashToReserve) = _getNetCashAmountsUnderlying( cashGroup, preFeeExchangeRate, fCashToAccount, timeToMaturity ); // Signifies a failed net cash amount calculation if (netCashToAccount == 0) return (0, 0); { // Set the new implied interest rate after the trade has taken effect, this // will be used to calculate the next trader's interest rate. market.totalfCash = market.totalfCash.subNoNeg(fCashToAccount); market.lastImpliedRate = getImpliedRate( market.totalfCash, totalCashUnderlying.add(netCashToMarket), rateScalar, rateAnchor, timeToMaturity ); // It's technically possible that the implied rate is actually exactly zero (or // more accurately the natural log rounds down to zero) but we will still fail // in this case. If this does happen we may assume that markets are not initialized. if (market.lastImpliedRate == 0) return (0, 0); } return _setNewMarketState( market, cashGroup.assetRate, netCashToAccount, netCashToMarket, netCashToReserve ); } /// @notice Returns factors for calculating exchange rates /// @return /// rateScalar: a scalar value in rate precision that defines the slope of the line /// totalCashUnderlying: the converted asset cash to underlying cash for calculating /// the exchange rates for the trade /// rateAnchor: an offset from the x axis to maintain interest rate continuity over time function getExchangeRateFactors( MarketParameters memory market, CashGroupParameters memory cashGroup, uint256 timeToMaturity, uint256 marketIndex ) internal pure returns ( int256, int256, int256 ) { int256 rateScalar = cashGroup.getRateScalar(marketIndex, timeToMaturity); int256 totalCashUnderlying = cashGroup.assetRate.convertToUnderlying(market.totalAssetCash); // This would result in a divide by zero if (market.totalfCash == 0 || totalCashUnderlying == 0) return (0, 0, 0); // Get the rate anchor given the market state, this will establish the baseline for where // the exchange rate is set. int256 rateAnchor; { bool success; (rateAnchor, success) = _getRateAnchor( market.totalfCash, market.lastImpliedRate, totalCashUnderlying, rateScalar, timeToMaturity ); if (!success) return (0, 0, 0); } return (rateScalar, totalCashUnderlying, rateAnchor); } /// @dev Returns net asset cash amounts to the account, the market and the reserve /// @return /// netCashToAccount: this is a positive or negative amount of cash change to the account /// netCashToMarket: this is a positive or negative amount of cash change in the market // netCashToReserve: this is always a positive amount of cash accrued to the reserve function _getNetCashAmountsUnderlying( CashGroupParameters memory cashGroup, int256 preFeeExchangeRate, int256 fCashToAccount, uint256 timeToMaturity ) private pure returns ( int256, int256, int256 ) { // Fees are specified in basis points which is an rate precision denomination. We convert this to // an exchange rate denomination for the given time to maturity. (i.e. get e^(fee * t) and multiply // or divide depending on the side of the trade). // tradeExchangeRate = exp((tradeInterestRateNoFee +/- fee) * timeToMaturity) // tradeExchangeRate = tradeExchangeRateNoFee (* or /) exp(fee * timeToMaturity) // cash = fCash / exchangeRate, exchangeRate > 1 int256 preFeeCashToAccount = fCashToAccount.divInRatePrecision(preFeeExchangeRate).neg(); int256 fee = getExchangeRateFromImpliedRate(cashGroup.getTotalFee(), timeToMaturity); if (fCashToAccount > 0) { // Lending // Dividing reduces exchange rate, lending should receive less fCash for cash int256 postFeeExchangeRate = preFeeExchangeRate.divInRatePrecision(fee); // It's possible that the fee pushes exchange rates into negative territory. This is not possible // when borrowing. If this happens then the trade has failed. if (postFeeExchangeRate < Constants.RATE_PRECISION) return (0, 0, 0); // cashToAccount = -(fCashToAccount / exchangeRate) // postFeeExchangeRate = preFeeExchangeRate / feeExchangeRate // preFeeCashToAccount = -(fCashToAccount / preFeeExchangeRate) // postFeeCashToAccount = -(fCashToAccount / postFeeExchangeRate) // netFee = preFeeCashToAccount - postFeeCashToAccount // netFee = (fCashToAccount / postFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate) // netFee = ((fCashToAccount * feeExchangeRate) / preFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate) // netFee = (fCashToAccount / preFeeExchangeRate) * (feeExchangeRate - 1) // netFee = -(preFeeCashToAccount) * (feeExchangeRate - 1) // netFee = preFeeCashToAccount * (1 - feeExchangeRate) // RATE_PRECISION - fee will be negative here, preFeeCashToAccount < 0, fee > 0 fee = preFeeCashToAccount.mulInRatePrecision(Constants.RATE_PRECISION.sub(fee)); } else { // Borrowing // cashToAccount = -(fCashToAccount / exchangeRate) // postFeeExchangeRate = preFeeExchangeRate * feeExchangeRate // netFee = preFeeCashToAccount - postFeeCashToAccount // netFee = (fCashToAccount / postFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate) // netFee = ((fCashToAccount / (feeExchangeRate * preFeeExchangeRate)) - (fCashToAccount / preFeeExchangeRate) // netFee = (fCashToAccount / preFeeExchangeRate) * (1 / feeExchangeRate - 1) // netFee = preFeeCashToAccount * ((1 - feeExchangeRate) / feeExchangeRate) // NOTE: preFeeCashToAccount is negative in this branch so we negate it to ensure that fee is a positive number // preFee * (1 - fee) / fee will be negative, use neg() to flip to positive // RATE_PRECISION - fee will be negative fee = preFeeCashToAccount.mul(Constants.RATE_PRECISION.sub(fee)).div(fee).neg(); } int256 cashToReserve = fee.mul(cashGroup.getReserveFeeShare()).div(Constants.PERCENTAGE_DECIMALS); return ( // postFeeCashToAccount = preFeeCashToAccount - fee preFeeCashToAccount.sub(fee), // netCashToMarket = -(preFeeCashToAccount - fee + cashToReserve) (preFeeCashToAccount.sub(fee).add(cashToReserve)).neg(), cashToReserve ); } /// @notice Sets the new market state /// @return /// netAssetCashToAccount: the positive or negative change in asset cash to the account /// assetCashToReserve: the positive amount of cash that accrues to the reserve function _setNewMarketState( MarketParameters memory market, AssetRateParameters memory assetRate, int256 netCashToAccount, int256 netCashToMarket, int256 netCashToReserve ) private view returns (int256, int256) { int256 netAssetCashToMarket = assetRate.convertFromUnderlying(netCashToMarket); // Set storage checks that total asset cash is above zero market.totalAssetCash = market.totalAssetCash.add(netAssetCashToMarket); // Sets the trade time for the next oracle update market.previousTradeTime = block.timestamp; int256 assetCashToReserve = assetRate.convertFromUnderlying(netCashToReserve); int256 netAssetCashToAccount = assetRate.convertFromUnderlying(netCashToAccount); return (netAssetCashToAccount, assetCashToReserve); } /// @notice Rate anchors update as the market gets closer to maturity. Rate anchors are not comparable /// across time or markets but implied rates are. The goal here is to ensure that the implied rate /// before and after the rate anchor update is the same. Therefore, the market will trade at the same implied /// rate that it last traded at. If these anchors do not update then it opens up the opportunity for arbitrage /// which will hurt the liquidity providers. /// /// The rate anchor will update as the market rolls down to maturity. The calculation is: /// newExchangeRate = e^(lastImpliedRate * timeToMaturity / Constants.IMPLIED_RATE_TIME) /// newAnchor = newExchangeRate - ln((proportion / (1 - proportion)) / rateScalar /// /// where: /// lastImpliedRate = ln(exchangeRate') * (Constants.IMPLIED_RATE_TIME / timeToMaturity') /// (calculated when the last trade in the market was made) /// @return the new rate anchor and a boolean that signifies success function _getRateAnchor( int256 totalfCash, uint256 lastImpliedRate, int256 totalCashUnderlying, int256 rateScalar, uint256 timeToMaturity ) internal pure returns (int256, bool) { // This is the exchange rate at the new time to maturity int256 newExchangeRate = getExchangeRateFromImpliedRate(lastImpliedRate, timeToMaturity); if (newExchangeRate < Constants.RATE_PRECISION) return (0, false); int256 rateAnchor; { // totalfCash / (totalfCash + totalCashUnderlying) int256 proportion = totalfCash.divInRatePrecision(totalfCash.add(totalCashUnderlying)); (int256 lnProportion, bool success) = _logProportion(proportion); if (!success) return (0, false); // newExchangeRate - ln(proportion / (1 - proportion)) / rateScalar rateAnchor = newExchangeRate.sub(lnProportion.divInRatePrecision(rateScalar)); } return (rateAnchor, true); } /// @notice Calculates the current market implied rate. /// @return the implied rate and a bool that is true on success function getImpliedRate( int256 totalfCash, int256 totalCashUnderlying, int256 rateScalar, int256 rateAnchor, uint256 timeToMaturity ) internal pure returns (uint256) { // This will check for exchange rates < Constants.RATE_PRECISION (int256 exchangeRate, bool success) = _getExchangeRate(totalfCash, totalCashUnderlying, rateScalar, rateAnchor, 0); if (!success) return 0; // Uses continuous compounding to calculate the implied rate: // ln(exchangeRate) * Constants.IMPLIED_RATE_TIME / timeToMaturity int128 rate = ABDKMath64x64.fromInt(exchangeRate); // Scales down to a floating point for LN int128 rateScaled = ABDKMath64x64.div(rate, Constants.RATE_PRECISION_64x64); // We will not have a negative log here because we check that exchangeRate > Constants.RATE_PRECISION // inside getExchangeRate int128 lnRateScaled = ABDKMath64x64.ln(rateScaled); // Scales up to a fixed point uint256 lnRate = ABDKMath64x64.toUInt(ABDKMath64x64.mul(lnRateScaled, Constants.RATE_PRECISION_64x64)); // lnRate * IMPLIED_RATE_TIME / ttm uint256 impliedRate = lnRate.mul(Constants.IMPLIED_RATE_TIME).div(timeToMaturity); // Implied rates over 429% will overflow, this seems like a safe assumption if (impliedRate > type(uint32).max) return 0; return impliedRate; } /// @notice Converts an implied rate to an exchange rate given a time to maturity. The /// formula is E = e^rt function getExchangeRateFromImpliedRate(uint256 impliedRate, uint256 timeToMaturity) internal pure returns (int256) { int128 expValue = ABDKMath64x64.fromUInt( impliedRate.mul(timeToMaturity).div(Constants.IMPLIED_RATE_TIME) ); int128 expValueScaled = ABDKMath64x64.div(expValue, Constants.RATE_PRECISION_64x64); int128 expResult = ABDKMath64x64.exp(expValueScaled); int128 expResultScaled = ABDKMath64x64.mul(expResult, Constants.RATE_PRECISION_64x64); return ABDKMath64x64.toInt(expResultScaled); } /// @notice Returns the exchange rate between fCash and cash for the given market /// Calculates the following exchange rate: /// (1 / rateScalar) * ln(proportion / (1 - proportion)) + rateAnchor /// where: /// proportion = totalfCash / (totalfCash + totalUnderlyingCash) /// @dev has an underscore to denote as private but is marked internal for the mock function _getExchangeRate( int256 totalfCash, int256 totalCashUnderlying, int256 rateScalar, int256 rateAnchor, int256 fCashToAccount ) internal pure returns (int256, bool) { int256 numerator = totalfCash.subNoNeg(fCashToAccount); // This is the proportion scaled by Constants.RATE_PRECISION // (totalfCash + fCash) / (totalfCash + totalCashUnderlying) int256 proportion = numerator.divInRatePrecision(totalfCash.add(totalCashUnderlying)); // This limit is here to prevent the market from reaching extremely high interest rates via an // excessively large proportion (high amounts of fCash relative to cash). // Market proportion can only increase via borrowing (fCash is added to the market and cash is // removed). Over time, the returns from asset cash will slightly decrease the proportion (the // value of cash underlying in the market must be monotonically increasing). Therefore it is not // possible for the proportion to go over max market proportion unless borrowing occurs. if (proportion > Constants.MAX_MARKET_PROPORTION) return (0, false); (int256 lnProportion, bool success) = _logProportion(proportion); if (!success) return (0, false); // lnProportion / rateScalar + rateAnchor int256 rate = lnProportion.divInRatePrecision(rateScalar).add(rateAnchor); // Do not succeed if interest rates fall below 1 if (rate < Constants.RATE_PRECISION) { return (0, false); } else { return (rate, true); } } /// @dev This method calculates the log of the proportion inside the logit function which is /// defined as ln(proportion / (1 - proportion)). Special handling here is required to deal with /// fixed point precision and the ABDK library. function _logProportion(int256 proportion) internal pure returns (int256, bool) { // This will result in divide by zero, short circuit if (proportion == Constants.RATE_PRECISION) return (0, false); // Convert proportion to what is used inside the logit function (p / (1-p)) int256 logitP = proportion.divInRatePrecision(Constants.RATE_PRECISION.sub(proportion)); // ABDK does not handle log of numbers that are less than 1, in order to get the right value // scaled by RATE_PRECISION we use the log identity: // (ln(logitP / RATE_PRECISION)) * RATE_PRECISION = (ln(logitP) - ln(RATE_PRECISION)) * RATE_PRECISION int128 abdkProportion = ABDKMath64x64.fromInt(logitP); // Here, abdk will revert due to negative log so abort if (abdkProportion <= 0) return (0, false); int256 result = ABDKMath64x64.toInt( ABDKMath64x64.mul( ABDKMath64x64.sub( ABDKMath64x64.ln(abdkProportion), Constants.LOG_RATE_PRECISION_64x64 ), Constants.RATE_PRECISION_64x64 ) ); return (result, true); } /// @notice Oracle rate protects against short term price manipulation. Time window will be set to a value /// on the order of minutes to hours. This is to protect fCash valuations from market manipulation. For example, /// a trader could use a flash loan to dump a large amount of cash into the market and depress interest rates. /// Since we value fCash in portfolios based on these rates, portfolio values will decrease and they may then /// be liquidated. /// /// Oracle rates are calculated when the market is loaded from storage. /// /// The oracle rate is a lagged weighted average over a short term price window. If we are past /// the short term window then we just set the rate to the lastImpliedRate, otherwise we take the /// weighted average: /// lastImpliedRatePreTrade * (currentTs - previousTs) / timeWindow + /// oracleRatePrevious * (1 - (currentTs - previousTs) / timeWindow) function _updateRateOracle( uint256 previousTradeTime, uint256 lastImpliedRate, uint256 oracleRate, uint256 rateOracleTimeWindow, uint256 blockTime ) private pure returns (uint256) { require(rateOracleTimeWindow > 0); // dev: update rate oracle, time window zero // This can occur when using a view function get to a market state in the past if (previousTradeTime > blockTime) return lastImpliedRate; uint256 timeDiff = blockTime.sub(previousTradeTime); if (timeDiff > rateOracleTimeWindow) { // If past the time window just return the lastImpliedRate return lastImpliedRate; } // (currentTs - previousTs) / timeWindow uint256 lastTradeWeight = timeDiff.mul(uint256(Constants.RATE_PRECISION)).div(rateOracleTimeWindow); // 1 - (currentTs - previousTs) / timeWindow uint256 oracleWeight = uint256(Constants.RATE_PRECISION).sub(lastTradeWeight); uint256 newOracleRate = (lastImpliedRate.mul(lastTradeWeight).add(oracleRate.mul(oracleWeight))).div( uint256(Constants.RATE_PRECISION) ); return newOracleRate; } function getOracleRate( uint256 currencyId, uint256 maturity, uint256 rateOracleTimeWindow, uint256 blockTime ) internal view returns (uint256) { mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage(); uint256 settlementDate = DateTime.getReferenceTime(blockTime) + Constants.QUARTER; MarketStorage storage marketStorage = store[currencyId][maturity][settlementDate]; uint256 lastImpliedRate = marketStorage.lastImpliedRate; uint256 oracleRate = marketStorage.oracleRate; uint256 previousTradeTime = marketStorage.previousTradeTime; // If the oracle rate is set to zero this can only be because the markets have past their settlement // date but the new set of markets has not yet been initialized. This means that accounts cannot be liquidated // during this time, but market initialization can be called by anyone so the actual time that this condition // exists for should be quite short. require(oracleRate > 0, "Market not initialized"); return _updateRateOracle( previousTradeTime, lastImpliedRate, oracleRate, rateOracleTimeWindow, blockTime ); } /// @notice Reads a market object directly from storage. `loadMarket` should be called instead of this method /// which ensures that the rate oracle is set properly. function _loadMarketStorage( MarketParameters memory market, uint256 currencyId, uint256 maturity, bool needsLiquidity, uint256 settlementDate ) private view { // Market object always uses the most current reference time as the settlement date mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage(); MarketStorage storage marketStorage = store[currencyId][maturity][settlementDate]; bytes32 slot; assembly { slot := marketStorage.slot } market.storageSlot = slot; market.maturity = maturity; market.totalfCash = marketStorage.totalfCash; market.totalAssetCash = marketStorage.totalAssetCash; market.lastImpliedRate = marketStorage.lastImpliedRate; market.oracleRate = marketStorage.oracleRate; market.previousTradeTime = marketStorage.previousTradeTime; if (needsLiquidity) { market.totalLiquidity = marketStorage.totalLiquidity; } else { market.totalLiquidity = 0; } } function _getMarketStoragePointer( MarketParameters memory market ) private pure returns (MarketStorage storage marketStorage) { bytes32 slot = market.storageSlot; assembly { marketStorage.slot := slot } } function _setMarketStorageForLiquidity(MarketParameters memory market) internal { MarketStorage storage marketStorage = _getMarketStoragePointer(market); // Oracle rate does not change on liquidity uint32 storedOracleRate = marketStorage.oracleRate; _setMarketStorage( marketStorage, market.totalfCash, market.totalAssetCash, market.lastImpliedRate, storedOracleRate, market.previousTradeTime ); _setTotalLiquidity(marketStorage, market.totalLiquidity); } function setMarketStorageForInitialize( MarketParameters memory market, uint256 currencyId, uint256 settlementDate ) internal { // On initialization we have not yet calculated the storage slot so we get it here. mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage(); MarketStorage storage marketStorage = store[currencyId][market.maturity][settlementDate]; _setMarketStorage( marketStorage, market.totalfCash, market.totalAssetCash, market.lastImpliedRate, market.oracleRate, market.previousTradeTime ); _setTotalLiquidity(marketStorage, market.totalLiquidity); } function _setTotalLiquidity( MarketStorage storage marketStorage, int256 totalLiquidity ) internal { require(totalLiquidity >= 0 && totalLiquidity <= type(uint80).max); // dev: market storage totalLiquidity overflow marketStorage.totalLiquidity = uint80(totalLiquidity); } function _setMarketStorage( MarketStorage storage marketStorage, int256 totalfCash, int256 totalAssetCash, uint256 lastImpliedRate, uint256 oracleRate, uint256 previousTradeTime ) private { require(totalfCash >= 0 && totalfCash <= type(uint80).max); // dev: storage totalfCash overflow require(totalAssetCash >= 0 && totalAssetCash <= type(uint80).max); // dev: storage totalAssetCash overflow require(0 < lastImpliedRate && lastImpliedRate <= type(uint32).max); // dev: storage lastImpliedRate overflow require(0 < oracleRate && oracleRate <= type(uint32).max); // dev: storage oracleRate overflow require(0 <= previousTradeTime && previousTradeTime <= type(uint32).max); // dev: storage previous trade time overflow marketStorage.totalfCash = uint80(totalfCash); marketStorage.totalAssetCash = uint80(totalAssetCash); marketStorage.lastImpliedRate = uint32(lastImpliedRate); marketStorage.oracleRate = uint32(oracleRate); marketStorage.previousTradeTime = uint32(previousTradeTime); } /// @notice Creates a market object and ensures that the rate oracle time window is updated appropriately. function loadMarket( MarketParameters memory market, uint256 currencyId, uint256 maturity, uint256 blockTime, bool needsLiquidity, uint256 rateOracleTimeWindow ) internal view { // Always reference the current settlement date uint256 settlementDate = DateTime.getReferenceTime(blockTime) + Constants.QUARTER; loadMarketWithSettlementDate( market, currencyId, maturity, blockTime, needsLiquidity, rateOracleTimeWindow, settlementDate ); } /// @notice Creates a market object and ensures that the rate oracle time window is updated appropriately, this /// is mainly used in the InitializeMarketAction contract. function loadMarketWithSettlementDate( MarketParameters memory market, uint256 currencyId, uint256 maturity, uint256 blockTime, bool needsLiquidity, uint256 rateOracleTimeWindow, uint256 settlementDate ) internal view { _loadMarketStorage(market, currencyId, maturity, needsLiquidity, settlementDate); market.oracleRate = _updateRateOracle( market.previousTradeTime, market.lastImpliedRate, market.oracleRate, rateOracleTimeWindow, blockTime ); } function loadSettlementMarket( MarketParameters memory market, uint256 currencyId, uint256 maturity, uint256 settlementDate ) internal view { _loadMarketStorage(market, currencyId, maturity, true, settlementDate); } /// Uses Newton's method to converge on an fCash amount given the amount of /// cash. The relation between cash and fcash is: /// cashAmount * exchangeRate * fee + fCash = 0 /// where exchangeRate(fCash) = (rateScalar ^ -1) * ln(p / (1 - p)) + rateAnchor /// p = (totalfCash - fCash) / (totalfCash + totalCash) /// if cashAmount < 0: fee = feeRate ^ -1 /// if cashAmount > 0: fee = feeRate /// /// Newton's method is: /// fCash_(n+1) = fCash_n - f(fCash) / f'(fCash) /// /// f(fCash) = cashAmount * exchangeRate(fCash) * fee + fCash /// /// (totalfCash + totalCash) /// exchangeRate'(fCash) = - ------------------------------------------ /// (totalfCash - fCash) * (totalCash + fCash) /// /// https://www.wolframalpha.com/input/?i=ln%28%28%28a-x%29%2F%28a%2Bb%29%29%2F%281-%28a-x%29%2F%28a%2Bb%29%29%29 /// /// (cashAmount * fee) * (totalfCash + totalCash) /// f'(fCash) = 1 - ------------------------------------------------------ /// rateScalar * (totalfCash - fCash) * (totalCash + fCash) /// /// NOTE: each iteration costs about 11.3k so this is only done via a view function. function getfCashGivenCashAmount( int256 totalfCash, int256 netCashToAccount, int256 totalCashUnderlying, int256 rateScalar, int256 rateAnchor, int256 feeRate, int256 maxDelta ) internal pure returns (int256) { require(maxDelta >= 0); int256 fCashChangeToAccountGuess = netCashToAccount.mulInRatePrecision(rateAnchor).neg(); for (uint8 i = 0; i < 250; i++) { (int256 exchangeRate, bool success) = _getExchangeRate( totalfCash, totalCashUnderlying, rateScalar, rateAnchor, fCashChangeToAccountGuess ); require(success); // dev: invalid exchange rate int256 delta = _calculateDelta( netCashToAccount, totalfCash, totalCashUnderlying, rateScalar, fCashChangeToAccountGuess, exchangeRate, feeRate ); if (delta.abs() <= maxDelta) return fCashChangeToAccountGuess; fCashChangeToAccountGuess = fCashChangeToAccountGuess.sub(delta); } revert("No convergence"); } /// @dev Calculates: f(fCash) / f'(fCash) /// f(fCash) = cashAmount * exchangeRate * fee + fCash /// (cashAmount * fee) * (totalfCash + totalCash) /// f'(fCash) = 1 - ------------------------------------------------------ /// rateScalar * (totalfCash - fCash) * (totalCash + fCash) function _calculateDelta( int256 cashAmount, int256 totalfCash, int256 totalCashUnderlying, int256 rateScalar, int256 fCashGuess, int256 exchangeRate, int256 feeRate ) private pure returns (int256) { int256 derivative; // rateScalar * (totalfCash - fCash) * (totalCash + fCash) // Precision: TOKEN_PRECISION ^ 2 int256 denominator = rateScalar.mulInRatePrecision( (totalfCash.sub(fCashGuess)).mul(totalCashUnderlying.add(fCashGuess)) ); if (fCashGuess > 0) { // Lending exchangeRate = exchangeRate.divInRatePrecision(feeRate); require(exchangeRate >= Constants.RATE_PRECISION); // dev: rate underflow // (cashAmount / fee) * (totalfCash + totalCash) // Precision: TOKEN_PRECISION ^ 2 derivative = cashAmount .mul(totalfCash.add(totalCashUnderlying)) .divInRatePrecision(feeRate); } else { // Borrowing exchangeRate = exchangeRate.mulInRatePrecision(feeRate); require(exchangeRate >= Constants.RATE_PRECISION); // dev: rate underflow // (cashAmount * fee) * (totalfCash + totalCash) // Precision: TOKEN_PRECISION ^ 2 derivative = cashAmount.mulInRatePrecision( feeRate.mul(totalfCash.add(totalCashUnderlying)) ); } // 1 - numerator / denominator // Precision: TOKEN_PRECISION derivative = Constants.INTERNAL_TOKEN_PRECISION.sub(derivative.div(denominator)); // f(fCash) = cashAmount * exchangeRate * fee + fCash // NOTE: exchangeRate at this point already has the fee taken into account int256 numerator = cashAmount.mulInRatePrecision(exchangeRate); numerator = numerator.add(fCashGuess); // f(fCash) / f'(fCash), note that they are both denominated as cashAmount so use TOKEN_PRECISION // here instead of RATE_PRECISION return numerator.mul(Constants.INTERNAL_TOKEN_PRECISION).div(derivative); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../global/Constants.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library DateTime { using SafeMath for uint256; /// @notice Returns the current reference time which is how all the AMM dates are calculated. function getReferenceTime(uint256 blockTime) internal pure returns (uint256) { require(blockTime >= Constants.QUARTER); return blockTime - (blockTime % Constants.QUARTER); } /// @notice Truncates a date to midnight UTC time function getTimeUTC0(uint256 time) internal pure returns (uint256) { require(time >= Constants.DAY); return time - (time % Constants.DAY); } /// @notice These are the predetermined market offsets for trading /// @dev Markets are 1-indexed because the 0 index means that no markets are listed for the cash group. function getTradedMarket(uint256 index) internal pure returns (uint256) { if (index == 1) return Constants.QUARTER; if (index == 2) return 2 * Constants.QUARTER; if (index == 3) return Constants.YEAR; if (index == 4) return 2 * Constants.YEAR; if (index == 5) return 5 * Constants.YEAR; if (index == 6) return 10 * Constants.YEAR; if (index == 7) return 20 * Constants.YEAR; revert("Invalid index"); } /// @notice Determines if the maturity falls on one of the valid on chain market dates. function isValidMarketMaturity( uint256 maxMarketIndex, uint256 maturity, uint256 blockTime ) internal pure returns (bool) { require(maxMarketIndex > 0, "CG: no markets listed"); require(maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: market index bound"); if (maturity % Constants.QUARTER != 0) return false; uint256 tRef = DateTime.getReferenceTime(blockTime); for (uint256 i = 1; i <= maxMarketIndex; i++) { if (maturity == tRef.add(DateTime.getTradedMarket(i))) return true; } return false; } /// @notice Determines if an idiosyncratic maturity is valid and returns the bit reference that is the case. function isValidMaturity( uint256 maxMarketIndex, uint256 maturity, uint256 blockTime ) internal pure returns (bool) { uint256 tRef = DateTime.getReferenceTime(blockTime); uint256 maxMaturity = tRef.add(DateTime.getTradedMarket(maxMarketIndex)); // Cannot trade past max maturity if (maturity > maxMaturity) return false; // prettier-ignore (/* */, bool isValid) = DateTime.getBitNumFromMaturity(blockTime, maturity); return isValid; } /// @notice Returns the market index for a given maturity, if the maturity is idiosyncratic /// will return the nearest market index that is larger than the maturity. /// @return uint marketIndex, bool isIdiosyncratic function getMarketIndex( uint256 maxMarketIndex, uint256 maturity, uint256 blockTime ) internal pure returns (uint256, bool) { require(maxMarketIndex > 0, "CG: no markets listed"); require(maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: market index bound"); uint256 tRef = DateTime.getReferenceTime(blockTime); for (uint256 i = 1; i <= maxMarketIndex; i++) { uint256 marketMaturity = tRef.add(DateTime.getTradedMarket(i)); // If market matches then is not idiosyncratic if (marketMaturity == maturity) return (i, false); // Returns the market that is immediately greater than the maturity if (marketMaturity > maturity) return (i, true); } revert("CG: no market found"); } /// @notice Given a bit number and the reference time of the first bit, returns the bit number /// of a given maturity. /// @return bitNum and a true or false if the maturity falls on the exact bit function getBitNumFromMaturity(uint256 blockTime, uint256 maturity) internal pure returns (uint256, bool) { uint256 blockTimeUTC0 = getTimeUTC0(blockTime); // Maturities must always divide days evenly if (maturity % Constants.DAY != 0) return (0, false); // Maturity cannot be in the past if (blockTimeUTC0 >= maturity) return (0, false); // Overflow check done above // daysOffset has no remainders, checked above uint256 daysOffset = (maturity - blockTimeUTC0) / Constants.DAY; // These if statements need to fall through to the next one if (daysOffset <= Constants.MAX_DAY_OFFSET) { return (daysOffset, true); } else if (daysOffset <= Constants.MAX_WEEK_OFFSET) { // (daysOffset - MAX_DAY_OFFSET) is the days overflow into the week portion, must be > 0 // (blockTimeUTC0 % WEEK) / DAY is the offset into the week portion // This returns the offset from the previous max offset in days uint256 offsetInDays = daysOffset - Constants.MAX_DAY_OFFSET + (blockTimeUTC0 % Constants.WEEK) / Constants.DAY; return ( // This converts the offset in days to its corresponding bit position, truncating down // if it does not divide evenly into DAYS_IN_WEEK Constants.WEEK_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_WEEK, (offsetInDays % Constants.DAYS_IN_WEEK) == 0 ); } else if (daysOffset <= Constants.MAX_MONTH_OFFSET) { uint256 offsetInDays = daysOffset - Constants.MAX_WEEK_OFFSET + (blockTimeUTC0 % Constants.MONTH) / Constants.DAY; return ( Constants.MONTH_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_MONTH, (offsetInDays % Constants.DAYS_IN_MONTH) == 0 ); } else if (daysOffset <= Constants.MAX_QUARTER_OFFSET) { uint256 offsetInDays = daysOffset - Constants.MAX_MONTH_OFFSET + (blockTimeUTC0 % Constants.QUARTER) / Constants.DAY; return ( Constants.QUARTER_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_QUARTER, (offsetInDays % Constants.DAYS_IN_QUARTER) == 0 ); } // This is the maximum 1-indexed bit num, it is never valid because it is beyond the 20 // year max maturity return (256, false); } /// @notice Given a bit number and a block time returns the maturity that the bit number /// should reference. Bit numbers are one indexed. function getMaturityFromBitNum(uint256 blockTime, uint256 bitNum) internal pure returns (uint256) { require(bitNum != 0); // dev: cash group get maturity from bit num is zero require(bitNum <= 256); // dev: cash group get maturity from bit num overflow uint256 blockTimeUTC0 = getTimeUTC0(blockTime); uint256 firstBit; if (bitNum <= Constants.WEEK_BIT_OFFSET) { return blockTimeUTC0 + bitNum * Constants.DAY; } else if (bitNum <= Constants.MONTH_BIT_OFFSET) { firstBit = blockTimeUTC0 + Constants.MAX_DAY_OFFSET * Constants.DAY - // This backs up to the day that is divisible by a week (blockTimeUTC0 % Constants.WEEK); return firstBit + (bitNum - Constants.WEEK_BIT_OFFSET) * Constants.WEEK; } else if (bitNum <= Constants.QUARTER_BIT_OFFSET) { firstBit = blockTimeUTC0 + Constants.MAX_WEEK_OFFSET * Constants.DAY - (blockTimeUTC0 % Constants.MONTH); return firstBit + (bitNum - Constants.MONTH_BIT_OFFSET) * Constants.MONTH; } else { firstBit = blockTimeUTC0 + Constants.MAX_MONTH_OFFSET * Constants.DAY - (blockTimeUTC0 % Constants.QUARTER); return firstBit + (bitNum - Constants.QUARTER_BIT_OFFSET) * Constants.QUARTER; } } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; /// @title All shared constants for the Notional system should be declared here. library Constants { uint8 internal constant CETH_DECIMAL_PLACES = 8; // Token precision used for all internal balances, TokenHandler library ensures that we // limit the dust amount caused by precision mismatches int256 internal constant INTERNAL_TOKEN_PRECISION = 1e8; uint256 internal constant INCENTIVE_ACCUMULATION_PRECISION = 1e18; // ETH will be initialized as the first currency uint256 internal constant ETH_CURRENCY_ID = 1; uint8 internal constant ETH_DECIMAL_PLACES = 18; int256 internal constant ETH_DECIMALS = 1e18; // Used to prevent overflow when converting decimal places to decimal precision values via // 10**decimalPlaces. This is a safe value for int256 and uint256 variables. We apply this // constraint when storing decimal places in governance. uint256 internal constant MAX_DECIMAL_PLACES = 36; // Address of the reserve account address internal constant RESERVE = address(0); // Most significant bit bytes32 internal constant MSB = 0x8000000000000000000000000000000000000000000000000000000000000000; // Each bit set in this mask marks where an active market should be in the bitmap // if the first bit refers to the reference time. Used to detect idiosyncratic // fcash in the nToken accounts bytes32 internal constant ACTIVE_MARKETS_MASK = ( MSB >> ( 90 - 1) | // 3 month MSB >> (105 - 1) | // 6 month MSB >> (135 - 1) | // 1 year MSB >> (147 - 1) | // 2 year MSB >> (183 - 1) | // 5 year MSB >> (211 - 1) | // 10 year MSB >> (251 - 1) // 20 year ); // Basis for percentages int256 internal constant PERCENTAGE_DECIMALS = 100; // Max number of traded markets, also used as the maximum number of assets in a portfolio array uint256 internal constant MAX_TRADED_MARKET_INDEX = 7; // Max number of fCash assets in a bitmap, this is based on the gas costs of calculating free collateral // for a bitmap portfolio uint256 internal constant MAX_BITMAP_ASSETS = 20; uint256 internal constant FIVE_MINUTES = 300; // Internal date representations, note we use a 6/30/360 week/month/year convention here uint256 internal constant DAY = 86400; // We use six day weeks to ensure that all time references divide evenly uint256 internal constant WEEK = DAY * 6; uint256 internal constant MONTH = WEEK * 5; uint256 internal constant QUARTER = MONTH * 3; uint256 internal constant YEAR = QUARTER * 4; // These constants are used in DateTime.sol uint256 internal constant DAYS_IN_WEEK = 6; uint256 internal constant DAYS_IN_MONTH = 30; uint256 internal constant DAYS_IN_QUARTER = 90; // Offsets for each time chunk denominated in days uint256 internal constant MAX_DAY_OFFSET = 90; uint256 internal constant MAX_WEEK_OFFSET = 360; uint256 internal constant MAX_MONTH_OFFSET = 2160; uint256 internal constant MAX_QUARTER_OFFSET = 7650; // Offsets for each time chunk denominated in bits uint256 internal constant WEEK_BIT_OFFSET = 90; uint256 internal constant MONTH_BIT_OFFSET = 135; uint256 internal constant QUARTER_BIT_OFFSET = 195; // This is a constant that represents the time period that all rates are normalized by, 360 days uint256 internal constant IMPLIED_RATE_TIME = 360 * DAY; // Number of decimal places that rates are stored in, equals 100% int256 internal constant RATE_PRECISION = 1e9; // One basis point in RATE_PRECISION terms uint256 internal constant BASIS_POINT = uint256(RATE_PRECISION / 10000); // Used to when calculating the amount to deleverage of a market when minting nTokens uint256 internal constant DELEVERAGE_BUFFER = 300 * BASIS_POINT; // Used for scaling cash group factors uint256 internal constant FIVE_BASIS_POINTS = 5 * BASIS_POINT; // Used for residual purchase incentive and cash withholding buffer uint256 internal constant TEN_BASIS_POINTS = 10 * BASIS_POINT; // This is the ABDK64x64 representation of RATE_PRECISION // RATE_PRECISION_64x64 = ABDKMath64x64.fromUint(RATE_PRECISION) int128 internal constant RATE_PRECISION_64x64 = 0x3b9aca000000000000000000; int128 internal constant LOG_RATE_PRECISION_64x64 = 382276781265598821176; // Limit the market proportion so that borrowing cannot hit extremely high interest rates int256 internal constant MAX_MARKET_PROPORTION = RATE_PRECISION * 99 / 100; uint8 internal constant FCASH_ASSET_TYPE = 1; // Liquidity token asset types are 1 + marketIndex (where marketIndex is 1-indexed) uint8 internal constant MIN_LIQUIDITY_TOKEN_INDEX = 2; uint8 internal constant MAX_LIQUIDITY_TOKEN_INDEX = 8; // Used for converting bool to bytes1, solidity does not have a native conversion // method for this bytes1 internal constant BOOL_FALSE = 0x00; bytes1 internal constant BOOL_TRUE = 0x01; // Account context flags bytes1 internal constant HAS_ASSET_DEBT = 0x01; bytes1 internal constant HAS_CASH_DEBT = 0x02; bytes2 internal constant ACTIVE_IN_PORTFOLIO = 0x8000; bytes2 internal constant ACTIVE_IN_BALANCES = 0x4000; bytes2 internal constant UNMASK_FLAGS = 0x3FFF; uint16 internal constant MAX_CURRENCIES = uint16(UNMASK_FLAGS); // Equal to 100% of all deposit amounts for nToken liquidity across fCash markets. int256 internal constant DEPOSIT_PERCENT_BASIS = 1e8; // nToken Parameters: there are offsets in the nTokenParameters bytes6 variable returned // in nTokenHandler. Each constant represents a position in the byte array. uint8 internal constant LIQUIDATION_HAIRCUT_PERCENTAGE = 0; uint8 internal constant CASH_WITHHOLDING_BUFFER = 1; uint8 internal constant RESIDUAL_PURCHASE_TIME_BUFFER = 2; uint8 internal constant PV_HAIRCUT_PERCENTAGE = 3; uint8 internal constant RESIDUAL_PURCHASE_INCENTIVE = 4; // Liquidation parameters // Default percentage of collateral that a liquidator is allowed to liquidate, will be higher if the account // requires more collateral to be liquidated int256 internal constant DEFAULT_LIQUIDATION_PORTION = 40; // Percentage of local liquidity token cash claim delivered to the liquidator for liquidating liquidity tokens int256 internal constant TOKEN_REPO_INCENTIVE_PERCENT = 30; // Pause Router liquidation enabled states bytes1 internal constant LOCAL_CURRENCY_ENABLED = 0x01; bytes1 internal constant COLLATERAL_CURRENCY_ENABLED = 0x02; bytes1 internal constant LOCAL_FCASH_ENABLED = 0x04; bytes1 internal constant CROSS_CURRENCY_FCASH_ENABLED = 0x08; } // SPDX-License-Identifier: BSD-4-Clause /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.5.0 || ^0.6.0 || ^0.7.0; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /* * Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /* * Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt (int256 x) internal pure returns (int128) { require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt (int128 x) internal pure returns (int64) { return int64 (x >> 64); } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt (uint256 x) internal pure returns (int128) { require (x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt (int128 x) internal pure returns (uint64) { require (x >= 0); return uint64 (x >> 64); } /** * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point * number rounding down. Revert on overflow. * * @param x signed 128.128-bin fixed point number * @return signed 64.64-bit fixed point number */ function from128x128 (int256 x) internal pure returns (int128) { int256 result = x >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Convert signed 64.64 fixed point number into signed 128.128 fixed point * number. * * @param x signed 64.64-bit fixed point number * @return signed 128.128 fixed point number */ function to128x128 (int128 x) internal pure returns (int256) { return int256 (x) << 64; } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) + y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) - y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) * y >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point * number and y is signed 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y signed 256-bit integer number * @return signed 256-bit integer number */ function muli (int128 x, int256 y) internal pure returns (int256) { if (x == MIN_64x64) { require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF && y <= 0x1000000000000000000000000000000000000000000000000); return -y << 63; } else { bool negativeResult = false; if (x < 0) { x = -x; negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint256 absoluteResult = mulu (x, uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000); return -int256 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int256 (absoluteResult); } } } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu (int128 x, uint256 y) internal pure returns (uint256) { if (y == 0) return 0; require (x >= 0); uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256 (x) * (y >> 128); require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo); return hi + lo; } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function div (int128 x, int128 y) internal pure returns (int128) { require (y != 0); int256 result = (int256 (x) << 64) / y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x / y rounding towards zero, where x and y are signed 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x signed 256-bit integer number * @param y signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function divi (int256 x, int256 y) internal pure returns (int128) { require (y != 0); bool negativeResult = false; if (x < 0) { x = -x; // We rely on overflow behavior here negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint128 absoluteResult = divuu (uint256 (x), uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu (uint256 x, uint256 y) internal pure returns (int128) { require (y != 0); uint128 result = divuu (x, y); require (result <= uint128 (MAX_64x64)); return int128 (result); } /** * Calculate -x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function neg (int128 x) internal pure returns (int128) { require (x != MIN_64x64); return -x; } /** * Calculate |x|. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function abs (int128 x) internal pure returns (int128) { require (x != MIN_64x64); return x < 0 ? -x : x; } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv (int128 x) internal pure returns (int128) { require (x != 0); int256 result = int256 (0x100000000000000000000000000000000) / x; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function avg (int128 x, int128 y) internal pure returns (int128) { return int128 ((int256 (x) + int256 (y)) >> 1); } /** * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down. * Revert on overflow or in case x * y is negative. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function gavg (int128 x, int128 y) internal pure returns (int128) { int256 m = int256 (x) * int256 (y); require (m >= 0); require (m < 0x4000000000000000000000000000000000000000000000000000000000000000); return int128 (sqrtu (uint256 (m))); } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow (int128 x, uint256 y) internal pure returns (int128) { bool negative = x < 0 && y & 1 == 1; uint256 absX = uint128 (x < 0 ? -x : x); uint256 absResult; absResult = 0x100000000000000000000000000000000; if (absX <= 0x10000000000000000) { absX <<= 63; while (y != 0) { if (y & 0x1 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x2 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x4 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x8 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; y >>= 4; } absResult >>= 64; } else { uint256 absXShift = 63; if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; } if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; } if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; } if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; } if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; } if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; } uint256 resultShift = 0; while (y != 0) { require (absXShift < 64); if (y & 0x1 != 0) { absResult = absResult * absX >> 127; resultShift += absXShift; if (absResult > 0x100000000000000000000000000000000) { absResult >>= 1; resultShift += 1; } } absX = absX * absX >> 127; absXShift <<= 1; if (absX >= 0x100000000000000000000000000000000) { absX >>= 1; absXShift += 1; } y >>= 1; } require (resultShift < 64); absResult >>= 64 - resultShift; } int256 result = negative ? -int256 (absResult) : int256 (absResult); require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate sqrt (x) rounding down. Revert if x < 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sqrt (int128 x) internal pure returns (int128) { require (x >= 0); return int128 (sqrtu (uint256 (x) << 64)); } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2 (int128 x) internal pure returns (int128) { require (x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = msb - 64 << 64; uint256 ux = uint256 (x) << uint256 (127 - msb); for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256 (b); } return int128 (result); } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln (int128 x) internal pure returns (int128) { require (x > 0); return int128 ( uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128); } /** * Calculate binary exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp_2 (int128 x) internal pure returns (int128) { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow uint256 result = 0x80000000000000000000000000000000; if (x & 0x8000000000000000 > 0) result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128; if (x & 0x4000000000000000 > 0) result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128; if (x & 0x2000000000000000 > 0) result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128; if (x & 0x1000000000000000 > 0) result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128; if (x & 0x800000000000000 > 0) result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128; if (x & 0x400000000000000 > 0) result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128; if (x & 0x200000000000000 > 0) result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128; if (x & 0x100000000000000 > 0) result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128; if (x & 0x80000000000000 > 0) result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128; if (x & 0x40000000000000 > 0) result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128; if (x & 0x20000000000000 > 0) result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128; if (x & 0x10000000000000 > 0) result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128; if (x & 0x8000000000000 > 0) result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128; if (x & 0x4000000000000 > 0) result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128; if (x & 0x2000000000000 > 0) result = result * 0x1000162E525EE054754457D5995292026 >> 128; if (x & 0x1000000000000 > 0) result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128; if (x & 0x800000000000 > 0) result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128; if (x & 0x400000000000 > 0) result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128; if (x & 0x200000000000 > 0) result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128; if (x & 0x100000000000 > 0) result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128; if (x & 0x80000000000 > 0) result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128; if (x & 0x40000000000 > 0) result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128; if (x & 0x20000000000 > 0) result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128; if (x & 0x10000000000 > 0) result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128; if (x & 0x8000000000 > 0) result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128; if (x & 0x4000000000 > 0) result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128; if (x & 0x2000000000 > 0) result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128; if (x & 0x1000000000 > 0) result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128; if (x & 0x800000000 > 0) result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128; if (x & 0x400000000 > 0) result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128; if (x & 0x200000000 > 0) result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128; if (x & 0x100000000 > 0) result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128; if (x & 0x80000000 > 0) result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128; if (x & 0x40000000 > 0) result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128; if (x & 0x20000000 > 0) result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128; if (x & 0x10000000 > 0) result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128; if (x & 0x8000000 > 0) result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128; if (x & 0x4000000 > 0) result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128; if (x & 0x2000000 > 0) result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128; if (x & 0x1000000 > 0) result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128; if (x & 0x800000 > 0) result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128; if (x & 0x400000 > 0) result = result * 0x100000000002C5C85FDF477B662B26945 >> 128; if (x & 0x200000 > 0) result = result * 0x10000000000162E42FEFA3AE53369388C >> 128; if (x & 0x100000 > 0) result = result * 0x100000000000B17217F7D1D351A389D40 >> 128; if (x & 0x80000 > 0) result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128; if (x & 0x40000 > 0) result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128; if (x & 0x20000 > 0) result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128; if (x & 0x10000 > 0) result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128; if (x & 0x8000 > 0) result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128; if (x & 0x4000 > 0) result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128; if (x & 0x2000 > 0) result = result * 0x1000000000000162E42FEFA39F02B772C >> 128; if (x & 0x1000 > 0) result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128; if (x & 0x800 > 0) result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128; if (x & 0x400 > 0) result = result * 0x100000000000002C5C85FDF473DEA871F >> 128; if (x & 0x200 > 0) result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128; if (x & 0x100 > 0) result = result * 0x100000000000000B17217F7D1CF79E949 >> 128; if (x & 0x80 > 0) result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128; if (x & 0x40 > 0) result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128; if (x & 0x20 > 0) result = result * 0x100000000000000162E42FEFA39EF366F >> 128; if (x & 0x10 > 0) result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128; if (x & 0x8 > 0) result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128; if (x & 0x4 > 0) result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128; if (x & 0x2 > 0) result = result * 0x1000000000000000162E42FEFA39EF358 >> 128; if (x & 0x1 > 0) result = result * 0x10000000000000000B17217F7D1CF79AB >> 128; result >>= uint256 (63 - (x >> 64)); require (result <= uint256 (MAX_64x64)); return int128 (result); } /** * Calculate natural exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp (int128 x) internal pure returns (int128) { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow return exp_2 ( int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128)); } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu (uint256 x, uint256 y) private pure returns (uint128) { require (y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1); require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert (xh == hi >> 128); result += xl / y; } require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128 (result); } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu (uint256 x) private pure returns (uint128) { if (x == 0) return 0; else { uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return uint128 (r < r1 ? r : r1); } } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; interface IRewarder { function claimRewards( address account, uint16 currencyId, uint256 nTokenBalanceBefore, uint256 nTokenBalanceAfter, int256 netNTokenSupplyChange, uint256 NOTETokensClaimed ) external; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; struct LendingPoolStorage { ILendingPool lendingPool; } interface ILendingPool { /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external returns (uint256); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (ReserveData memory); // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } struct UserConfigurationMap { uint256 data; } enum InterestRateMode {NONE, STABLE, VARIABLE} } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../math/SafeInt256.sol"; import "../../global/LibStorage.sol"; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../../global/Deployments.sol"; import "./protocols/AaveHandler.sol"; import "./protocols/CompoundHandler.sol"; import "./protocols/GenericToken.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /// @notice Handles all external token transfers and events library TokenHandler { using SafeInt256 for int256; using SafeMath for uint256; function setMaxCollateralBalance(uint256 currencyId, uint72 maxCollateralBalance) internal { mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage(); TokenStorage storage tokenStorage = store[currencyId][false]; tokenStorage.maxCollateralBalance = maxCollateralBalance; } function getAssetToken(uint256 currencyId) internal view returns (Token memory) { return _getToken(currencyId, false); } function getUnderlyingToken(uint256 currencyId) internal view returns (Token memory) { return _getToken(currencyId, true); } /// @notice Gets token data for a particular currency id, if underlying is set to true then returns /// the underlying token. (These may not always exist) function _getToken(uint256 currencyId, bool underlying) private view returns (Token memory) { mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage(); TokenStorage storage tokenStorage = store[currencyId][underlying]; return Token({ tokenAddress: tokenStorage.tokenAddress, hasTransferFee: tokenStorage.hasTransferFee, // No overflow, restricted on storage decimals: int256(10**tokenStorage.decimalPlaces), tokenType: tokenStorage.tokenType, maxCollateralBalance: tokenStorage.maxCollateralBalance }); } /// @notice Sets a token for a currency id. function setToken( uint256 currencyId, bool underlying, TokenStorage memory tokenStorage ) internal { mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage(); if (tokenStorage.tokenType == TokenType.Ether && currencyId == Constants.ETH_CURRENCY_ID) { // Hardcoded parameters for ETH just to make sure we don't get it wrong. TokenStorage storage ts = store[currencyId][true]; ts.tokenAddress = address(0); ts.hasTransferFee = false; ts.tokenType = TokenType.Ether; ts.decimalPlaces = Constants.ETH_DECIMAL_PLACES; ts.maxCollateralBalance = 0; return; } // Check token address require(tokenStorage.tokenAddress != address(0), "TH: address is zero"); // Once a token is set we cannot override it. In the case that we do need to do change a token address // then we should explicitly upgrade this method to allow for a token to be changed. Token memory token = _getToken(currencyId, underlying); require( token.tokenAddress == tokenStorage.tokenAddress || token.tokenAddress == address(0), "TH: token cannot be reset" ); require(0 < tokenStorage.decimalPlaces && tokenStorage.decimalPlaces <= Constants.MAX_DECIMAL_PLACES, "TH: invalid decimals"); // Validate token type require(tokenStorage.tokenType != TokenType.Ether); // dev: ether can only be set once if (underlying) { // Underlying tokens cannot have max collateral balances, the contract only has a balance temporarily // during mint and redeem actions. require(tokenStorage.maxCollateralBalance == 0); // dev: underlying cannot have max collateral balance require(tokenStorage.tokenType == TokenType.UnderlyingToken); // dev: underlying token inconsistent } else { require(tokenStorage.tokenType != TokenType.UnderlyingToken); // dev: underlying token inconsistent } if (tokenStorage.tokenType == TokenType.cToken || tokenStorage.tokenType == TokenType.aToken) { // Set the approval for the underlying so that we can mint cTokens or aTokens Token memory underlyingToken = getUnderlyingToken(currencyId); // cTokens call transfer from the tokenAddress, but aTokens use the LendingPool // to initiate all transfers address approvalAddress = tokenStorage.tokenType == TokenType.cToken ? tokenStorage.tokenAddress : address(LibStorage.getLendingPool().lendingPool); // ERC20 tokens should return true on success for an approval, but Tether // does not return a value here so we use the NonStandard interface here to // check that the approval was successful. IEIP20NonStandard(underlyingToken.tokenAddress).approve( approvalAddress, type(uint256).max ); GenericToken.checkReturnCode(); } store[currencyId][underlying] = tokenStorage; } /** * @notice If a token is mintable then will mint it. At this point we expect to have the underlying * balance in the contract already. * @param assetToken the asset token to mint * @param underlyingAmountExternal the amount of underlying to transfer to the mintable token * @return the amount of asset tokens minted, will always be a positive integer */ function mint(Token memory assetToken, uint16 currencyId, uint256 underlyingAmountExternal) internal returns (int256) { // aTokens return the principal plus interest value when calling the balanceOf selector. We cannot use this // value in internal accounting since it will not allow individual users to accrue aToken interest. Use the // scaledBalanceOf function call instead for internal accounting. bytes4 balanceOfSelector = assetToken.tokenType == TokenType.aToken ? AaveHandler.scaledBalanceOfSelector : GenericToken.defaultBalanceOfSelector; uint256 startingBalance = GenericToken.checkBalanceViaSelector(assetToken.tokenAddress, address(this), balanceOfSelector); if (assetToken.tokenType == TokenType.aToken) { Token memory underlyingToken = getUnderlyingToken(currencyId); AaveHandler.mint(underlyingToken, underlyingAmountExternal); } else if (assetToken.tokenType == TokenType.cToken) { CompoundHandler.mint(assetToken, underlyingAmountExternal); } else if (assetToken.tokenType == TokenType.cETH) { CompoundHandler.mintCETH(assetToken); } else { revert(); // dev: non mintable token } uint256 endingBalance = GenericToken.checkBalanceViaSelector(assetToken.tokenAddress, address(this), balanceOfSelector); // This is the starting and ending balance in external precision return SafeInt256.toInt(endingBalance.sub(startingBalance)); } /** * @notice If a token is redeemable to underlying will redeem it and transfer the underlying balance * to the account * @param assetToken asset token to redeem * @param currencyId the currency id of the token * @param account account to transfer the underlying to * @param assetAmountExternal the amount to transfer in asset token denomination and external precision * @return the actual amount of underlying tokens transferred. this is used as a return value back to the * user, is not used for internal accounting purposes */ function redeem( Token memory assetToken, uint256 currencyId, address account, uint256 assetAmountExternal ) internal returns (int256) { uint256 transferAmount; if (assetToken.tokenType == TokenType.cETH) { transferAmount = CompoundHandler.redeemCETH(assetToken, account, assetAmountExternal); } else { Token memory underlyingToken = getUnderlyingToken(currencyId); if (assetToken.tokenType == TokenType.aToken) { transferAmount = AaveHandler.redeem(underlyingToken, account, assetAmountExternal); } else if (assetToken.tokenType == TokenType.cToken) { transferAmount = CompoundHandler.redeem(assetToken, underlyingToken, account, assetAmountExternal); } else { revert(); // dev: non redeemable token } } // Use the negative value here to signify that assets have left the protocol return SafeInt256.toInt(transferAmount).neg(); } /// @notice Handles transfers into and out of the system denominated in the external token decimal /// precision. function transfer( Token memory token, address account, uint256 currencyId, int256 netTransferExternal ) internal returns (int256 actualTransferExternal) { // This will be true in all cases except for deposits where the token has transfer fees. For // aTokens this value is set before convert from scaled balances to principal plus interest actualTransferExternal = netTransferExternal; if (token.tokenType == TokenType.aToken) { Token memory underlyingToken = getUnderlyingToken(currencyId); // aTokens need to be converted when we handle the transfer since the external balance format // is not the same as the internal balance format that we use netTransferExternal = AaveHandler.convertFromScaledBalanceExternal( underlyingToken.tokenAddress, netTransferExternal ); } if (netTransferExternal > 0) { // Deposits must account for transfer fees. int256 netDeposit = _deposit(token, account, uint256(netTransferExternal)); // If an aToken has a transfer fee this will still return a balance figure // in scaledBalanceOf terms due to the selector if (token.hasTransferFee) actualTransferExternal = netDeposit; } else if (token.tokenType == TokenType.Ether) { // netTransferExternal can only be negative or zero at this point GenericToken.transferNativeTokenOut(account, uint256(netTransferExternal.neg())); } else { GenericToken.safeTransferOut( token.tokenAddress, account, // netTransferExternal is zero or negative here uint256(netTransferExternal.neg()) ); } } /// @notice Handles token deposits into Notional. If there is a transfer fee then we must /// calculate the net balance after transfer. Amounts are denominated in the destination token's /// precision. function _deposit( Token memory token, address account, uint256 amount ) private returns (int256) { uint256 startingBalance; uint256 endingBalance; bytes4 balanceOfSelector = token.tokenType == TokenType.aToken ? AaveHandler.scaledBalanceOfSelector : GenericToken.defaultBalanceOfSelector; if (token.hasTransferFee) { startingBalance = GenericToken.checkBalanceViaSelector(token.tokenAddress, address(this), balanceOfSelector); } GenericToken.safeTransferIn(token.tokenAddress, account, amount); if (token.hasTransferFee || token.maxCollateralBalance > 0) { // If aTokens have a max collateral balance then it will be applied against the scaledBalanceOf. This is probably // the correct behavior because if collateral accrues interest over time we should not somehow go over the // maxCollateralBalance due to the passage of time. endingBalance = GenericToken.checkBalanceViaSelector(token.tokenAddress, address(this), balanceOfSelector); } if (token.maxCollateralBalance > 0) { int256 internalPrecisionBalance = convertToInternal(token, SafeInt256.toInt(endingBalance)); // Max collateral balance is stored as uint72, no overflow require(internalPrecisionBalance <= SafeInt256.toInt(token.maxCollateralBalance)); // dev: over max collateral balance } // Math is done in uint inside these statements and will revert on negative if (token.hasTransferFee) { return SafeInt256.toInt(endingBalance.sub(startingBalance)); } else { return SafeInt256.toInt(amount); } } function convertToInternal(Token memory token, int256 amount) internal pure returns (int256) { // If token decimals > INTERNAL_TOKEN_PRECISION: // on deposit: resulting dust will accumulate to protocol // on withdraw: protocol may lose dust amount. However, withdraws are only calculated based // on a conversion from internal token precision to external token precision so therefore dust // amounts cannot be specified for withdraws. // If token decimals < INTERNAL_TOKEN_PRECISION then this will add zeros to the // end of amount and will not result in dust. if (token.decimals == Constants.INTERNAL_TOKEN_PRECISION) return amount; return amount.mul(Constants.INTERNAL_TOKEN_PRECISION).div(token.decimals); } function convertToExternal(Token memory token, int256 amount) internal pure returns (int256) { if (token.decimals == Constants.INTERNAL_TOKEN_PRECISION) return amount; // If token decimals > INTERNAL_TOKEN_PRECISION then this will increase amount // by adding a number of zeros to the end and will not result in dust. // If token decimals < INTERNAL_TOKEN_PRECISION: // on deposit: Deposits are specified in external token precision and there is no loss of precision when // tokens are converted from external to internal precision // on withdraw: this calculation will round down such that the protocol retains the residual cash balance return amount.mul(token.decimals).div(Constants.INTERNAL_TOKEN_PRECISION); } function transferIncentive(address account, uint256 tokensToTransfer) internal { GenericToken.safeTransferOut(Deployments.NOTE_TOKEN_ADDRESS, account, tokensToTransfer); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../global/LibStorage.sol"; import "./balances/BalanceHandler.sol"; import "./portfolio/BitmapAssetsHandler.sol"; import "./portfolio/PortfolioHandler.sol"; library AccountContextHandler { using PortfolioHandler for PortfolioState; bytes18 private constant TURN_OFF_PORTFOLIO_FLAGS = 0x7FFF7FFF7FFF7FFF7FFF7FFF7FFF7FFF7FFF; event AccountContextUpdate(address indexed account); /// @notice Returns the account context of a given account function getAccountContext(address account) internal view returns (AccountContext memory) { mapping(address => AccountContext) storage store = LibStorage.getAccountStorage(); return store[account]; } /// @notice Sets the account context of a given account function setAccountContext(AccountContext memory accountContext, address account) internal { mapping(address => AccountContext) storage store = LibStorage.getAccountStorage(); store[account] = accountContext; emit AccountContextUpdate(account); } function isBitmapEnabled(AccountContext memory accountContext) internal pure returns (bool) { return accountContext.bitmapCurrencyId != 0; } /// @notice Enables a bitmap type portfolio for an account. A bitmap type portfolio allows /// an account to hold more fCash than a normal portfolio, except only in a single currency. /// Once enabled, it cannot be disabled or changed. An account can only enable a bitmap if /// it has no assets or debt so that we ensure no assets are left stranded. /// @param accountContext refers to the account where the bitmap will be enabled /// @param currencyId the id of the currency to enable /// @param blockTime the current block time to set the next settle time function enableBitmapForAccount( AccountContext memory accountContext, uint16 currencyId, uint256 blockTime ) internal view { require(!isBitmapEnabled(accountContext), "Cannot change bitmap"); require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES, "Invalid currency id"); // Account cannot have assets or debts require(accountContext.assetArrayLength == 0, "Cannot have assets"); require(accountContext.hasDebt == 0x00, "Cannot have debt"); // Ensure that the active currency is set to false in the array so that there is no double // counting during FreeCollateral setActiveCurrency(accountContext, currencyId, false, Constants.ACTIVE_IN_BALANCES); accountContext.bitmapCurrencyId = currencyId; // Setting this is required to initialize the assets bitmap uint256 nextSettleTime = DateTime.getTimeUTC0(blockTime); require(nextSettleTime < type(uint40).max); // dev: blockTime overflow accountContext.nextSettleTime = uint40(nextSettleTime); } /// @notice Returns true if the context needs to settle function mustSettleAssets(AccountContext memory accountContext) internal view returns (bool) { uint256 blockTime = block.timestamp; if (isBitmapEnabled(accountContext)) { // nextSettleTime will be set to utc0 after settlement so we // settle if this is strictly less than utc0 return accountContext.nextSettleTime < DateTime.getTimeUTC0(blockTime); } else { // 0 value occurs on an uninitialized account // Assets mature exactly on the blockTime (not one second past) so in this // case we settle on the block timestamp return 0 < accountContext.nextSettleTime && accountContext.nextSettleTime <= blockTime; } } /// @notice Checks if a currency id (uint16 max) is in the 9 slots in the account /// context active currencies list. /// @dev NOTE: this may be more efficient as a binary search since we know that the array /// is sorted function isActiveInBalances(AccountContext memory accountContext, uint256 currencyId) internal pure returns (bool) { require(currencyId != 0 && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id bytes18 currencies = accountContext.activeCurrencies; if (accountContext.bitmapCurrencyId == currencyId) return true; while (currencies != 0x00) { uint256 cid = uint16(bytes2(currencies) & Constants.UNMASK_FLAGS); if (cid == currencyId) { // Currency found, return if it is active in balances or not return bytes2(currencies) & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES; } currencies = currencies << 16; } return false; } /// @notice Iterates through the active currency list and removes, inserts or does nothing /// to ensure that the active currency list is an ordered byte array of uint16 currency ids /// that refer to the currencies that an account is active in. /// /// This is called to ensure that currencies are active when the account has a non zero cash balance, /// a non zero nToken balance or a portfolio asset. function setActiveCurrency( AccountContext memory accountContext, uint256 currencyId, bool isActive, bytes2 flags ) internal pure { require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id // If the bitmapped currency is already set then return here. Turning off the bitmap currency // id requires other logical handling so we will do it elsewhere. if (isActive && accountContext.bitmapCurrencyId == currencyId) return; bytes18 prefix; bytes18 suffix = accountContext.activeCurrencies; uint256 shifts; /// There are six possible outcomes from this search: /// 1. The currency id is in the list /// - it must be set to active, do nothing /// - it must be set to inactive, shift suffix and concatenate /// 2. The current id is greater than the one in the search: /// - it must be set to active, append to prefix and then concatenate the suffix, /// ensure that we do not lose the last 2 bytes if set. /// - it must be set to inactive, it is not in the list, do nothing /// 3. Reached the end of the list: /// - it must be set to active, check that the last two bytes are not set and then /// append to the prefix /// - it must be set to inactive, do nothing while (suffix != 0x00) { uint256 cid = uint256(uint16(bytes2(suffix) & Constants.UNMASK_FLAGS)); // if matches and isActive then return, already in list if (cid == currencyId && isActive) { // set flag and return accountContext.activeCurrencies = accountContext.activeCurrencies | (bytes18(flags) >> (shifts * 16)); return; } // if matches and not active then shift suffix to remove if (cid == currencyId && !isActive) { // turn off flag, if both flags are off then remove suffix = suffix & ~bytes18(flags); if (bytes2(suffix) & ~Constants.UNMASK_FLAGS == 0x0000) suffix = suffix << 16; accountContext.activeCurrencies = prefix | (suffix >> (shifts * 16)); return; } // if greater than and isActive then insert into prefix if (cid > currencyId && isActive) { prefix = prefix | (bytes18(bytes2(uint16(currencyId)) | flags) >> (shifts * 16)); // check that the total length is not greater than 9, meaning that the last // two bytes of the active currencies array should be zero require((accountContext.activeCurrencies << 128) == 0x00); // dev: AC: too many currencies // append the suffix accountContext.activeCurrencies = prefix | (suffix >> ((shifts + 1) * 16)); return; } // if past the point of the currency id and not active, not in list if (cid > currencyId && !isActive) return; prefix = prefix | (bytes18(bytes2(suffix)) >> (shifts * 16)); suffix = suffix << 16; shifts += 1; } // If reached this point and not active then return if (!isActive) return; // if end and isActive then insert into suffix, check max length require(shifts < 9); // dev: AC: too many currencies accountContext.activeCurrencies = prefix | (bytes18(bytes2(uint16(currencyId)) | flags) >> (shifts * 16)); } function _clearPortfolioActiveFlags(bytes18 activeCurrencies) internal pure returns (bytes18) { bytes18 result; // This is required to clear the suffix as we append below bytes18 suffix = activeCurrencies & TURN_OFF_PORTFOLIO_FLAGS; uint256 shifts; // This loop will append all currencies that are active in balances into the result. while (suffix != 0x00) { if (bytes2(suffix) & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES) { // If any flags are active, then append. result = result | (bytes18(bytes2(suffix)) >> shifts); shifts += 16; } suffix = suffix << 16; } return result; } /// @notice Stores a portfolio array and updates the account context information, this method should /// be used whenever updating a portfolio array except in the case of nTokens function storeAssetsAndUpdateContext( AccountContext memory accountContext, address account, PortfolioState memory portfolioState, bool isLiquidation ) internal { // Each of these parameters is recalculated based on the entire array of assets in store assets, // regardless of whether or not they have been updated. (bool hasDebt, bytes32 portfolioCurrencies, uint8 assetArrayLength, uint40 nextSettleTime) = portfolioState.storeAssets(account); accountContext.nextSettleTime = nextSettleTime; require(mustSettleAssets(accountContext) == false); // dev: cannot store matured assets accountContext.assetArrayLength = assetArrayLength; // During liquidation it is possible for an array to go over the max amount of assets allowed due to // liquidity tokens being withdrawn into fCash. if (!isLiquidation) { require(assetArrayLength <= uint8(Constants.MAX_TRADED_MARKET_INDEX)); // dev: max assets allowed } // Sets the hasDebt flag properly based on whether or not portfolio has asset debt, meaning // a negative fCash balance. if (hasDebt) { accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT; } else { // Turns off the ASSET_DEBT flag accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_ASSET_DEBT; } // Clear the active portfolio active flags and they will be recalculated in the next step accountContext.activeCurrencies = _clearPortfolioActiveFlags(accountContext.activeCurrencies); uint256 lastCurrency; while (portfolioCurrencies != 0) { // Portfolio currencies will not have flags, it is just an byte array of all the currencies found // in a portfolio. They are appended in a sorted order so we can compare to the previous currency // and only set it if they are different. uint256 currencyId = uint16(bytes2(portfolioCurrencies)); if (currencyId != lastCurrency) { setActiveCurrency(accountContext, currencyId, true, Constants.ACTIVE_IN_PORTFOLIO); } lastCurrency = currencyId; portfolioCurrencies = portfolioCurrencies << 16; } } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; import "./Bitmap.sol"; /** * Packs an uint value into a "floating point" storage slot. Used for storing * lastClaimIntegralSupply values in balance storage. For these values, we don't need * to maintain exact precision but we don't want to be limited by storage size overflows. * * A floating point value is defined by the 48 most significant bits and an 8 bit number * of bit shifts required to restore its precision. The unpacked value will always be less * than the packed value with a maximum absolute loss of precision of (2 ** bitShift) - 1. */ library FloatingPoint56 { function packTo56Bits(uint256 value) internal pure returns (uint56) { uint256 bitShift; // If the value is over the uint48 max value then we will shift it down // given the index of the most significant bit. We store this bit shift // in the least significant byte of the 56 bit slot available. if (value > type(uint48).max) bitShift = (Bitmap.getMSB(value) - 47); uint256 shiftedValue = value >> bitShift; return uint56((shiftedValue << 8) | bitShift); } function unpackFrom56Bits(uint256 value) internal pure returns (uint256) { // The least significant 8 bits will be the amount to bit shift uint256 bitShift = uint256(uint8(value)); return ((value >> 8) << bitShift); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../global/LibStorage.sol"; import "../internal/nToken/nTokenHandler.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @notice Deployed library for migration of incentives from the old (inaccurate) calculation * to a newer, more accurate calculation based on SushiSwap MasterChef math. The more accurate * calculation is inside `Incentives.sol` and this library holds the legacy calculation. System * migration code can be found in `MigrateIncentivesFix.sol` */ library MigrateIncentives { using SafeMath for uint256; /// @notice Calculates the claimable incentives for a particular nToken and account in the /// previous regime. This should only ever be called ONCE for an account / currency combination /// to get the incentives accrued up until the migration date. function migrateAccountFromPreviousCalculation( address tokenAddress, uint256 nTokenBalance, uint256 lastClaimTime, uint256 lastClaimIntegralSupply ) external view returns (uint256) { ( uint256 finalEmissionRatePerYear, uint256 finalTotalIntegralSupply, uint256 finalMigrationTime ) = _getMigratedIncentiveValues(tokenAddress); // This if statement should never be true but we return 0 just in case if (lastClaimTime == 0 || lastClaimTime >= finalMigrationTime) return 0; // No overflow here, checked above. All incentives are claimed up until finalMigrationTime // using the finalTotalIntegralSupply. Both these values are set on migration and will not // change. uint256 timeSinceMigration = finalMigrationTime - lastClaimTime; // (timeSinceMigration * INTERNAL_TOKEN_PRECISION * finalEmissionRatePerYear) / YEAR uint256 incentiveRate = timeSinceMigration .mul(uint256(Constants.INTERNAL_TOKEN_PRECISION)) // Migration emission rate is stored as is, denominated in whole tokens .mul(finalEmissionRatePerYear).mul(uint256(Constants.INTERNAL_TOKEN_PRECISION)) .div(Constants.YEAR); // Returns the average supply using the integral of the total supply. uint256 avgTotalSupply = finalTotalIntegralSupply.sub(lastClaimIntegralSupply).div(timeSinceMigration); if (avgTotalSupply == 0) return 0; uint256 incentivesToClaim = nTokenBalance.mul(incentiveRate).div(avgTotalSupply); // incentiveRate has a decimal basis of 1e16 so divide by token precision to reduce to 1e8 incentivesToClaim = incentivesToClaim.div(uint256(Constants.INTERNAL_TOKEN_PRECISION)); return incentivesToClaim; } function _getMigratedIncentiveValues( address tokenAddress ) private view returns ( uint256 finalEmissionRatePerYear, uint256 finalTotalIntegralSupply, uint256 finalMigrationTime ) { mapping(address => nTokenTotalSupplyStorage_deprecated) storage store = LibStorage.getDeprecatedNTokenTotalSupplyStorage(); nTokenTotalSupplyStorage_deprecated storage d_nTokenStorage = store[tokenAddress]; // The total supply value is overridden as emissionRatePerYear during the initialization finalEmissionRatePerYear = d_nTokenStorage.totalSupply; finalTotalIntegralSupply = d_nTokenStorage.integralTotalSupply; finalMigrationTime = d_nTokenStorage.lastSupplyChangeTime; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; /// @title Hardcoded deployed contracts are listed here. These are hardcoded to reduce /// gas costs for immutable addresses. They must be updated per environment that Notional /// is deployed to. library Deployments { address internal constant NOTE_TOKEN_ADDRESS = 0xCFEAead4947f0705A14ec42aC3D44129E1Ef3eD5; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../../global/Types.sol"; import "../../../global/LibStorage.sol"; import "../../../math/SafeInt256.sol"; import "../TokenHandler.sol"; import "../../../../interfaces/aave/IAToken.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library AaveHandler { using SafeMath for uint256; using SafeInt256 for int256; int256 internal constant RAY = 1e27; int256 internal constant halfRAY = RAY / 2; bytes4 internal constant scaledBalanceOfSelector = IAToken.scaledBalanceOf.selector; /** * @notice Mints an amount of aTokens corresponding to the the underlying. * @param underlyingToken address of the underlying token to pass to Aave * @param underlyingAmountExternal amount of underlying to deposit, in external precision */ function mint(Token memory underlyingToken, uint256 underlyingAmountExternal) internal { // In AaveV3 this method is renamed to supply() but deposit() is still available for // backwards compatibility: https://github.com/aave/aave-v3-core/blob/master/contracts/protocol/pool/Pool.sol#L755 // We use deposit here so that mainnet-fork tests against Aave v2 will pass. LibStorage.getLendingPool().lendingPool.deposit( underlyingToken.tokenAddress, underlyingAmountExternal, address(this), 0 ); } /** * @notice Redeems and sends an amount of aTokens to the specified account * @param underlyingToken address of the underlying token to pass to Aave * @param account account to receive the underlying * @param assetAmountExternal amount of aTokens in scaledBalanceOf terms */ function redeem( Token memory underlyingToken, address account, uint256 assetAmountExternal ) internal returns (uint256 underlyingAmountExternal) { underlyingAmountExternal = convertFromScaledBalanceExternal( underlyingToken.tokenAddress, SafeInt256.toInt(assetAmountExternal) ).toUint(); LibStorage.getLendingPool().lendingPool.withdraw( underlyingToken.tokenAddress, underlyingAmountExternal, account ); } /** * @notice Takes an assetAmountExternal (in this case is the Aave balanceOf representing principal plus interest) * and returns another assetAmountExternal value which represents the Aave scaledBalanceOf (representing a proportional * claim on Aave principal plus interest onto the future). This conversion ensures that depositors into Notional will * receive future Aave interest. * @dev There is no loss of precision within this function since it does the exact same calculation as Aave. * @param currencyId is the currency id * @param assetAmountExternal an Aave token amount representing principal plus interest supplied by the user. This must * be positive in this function, this method is only called when depositing aTokens directly * @return scaledAssetAmountExternal the Aave scaledBalanceOf equivalent. The decimal precision of this value will * be in external precision. */ function convertToScaledBalanceExternal(uint256 currencyId, int256 assetAmountExternal) internal view returns (int256) { if (assetAmountExternal == 0) return 0; require(assetAmountExternal > 0); Token memory underlyingToken = TokenHandler.getUnderlyingToken(currencyId); // We know that this value must be positive int256 index = _getReserveNormalizedIncome(underlyingToken.tokenAddress); // Mimic the WadRay math performed by Aave (but do it in int256 instead) int256 halfIndex = index / 2; // Overflow will occur when: (a * RAY + halfIndex) > int256.max require(assetAmountExternal <= (type(int256).max - halfIndex) / RAY); // if index is zero then this will revert return (assetAmountExternal * RAY + halfIndex) / index; } /** * @notice Takes an assetAmountExternal (in this case is the internal scaledBalanceOf in external decimal precision) * and returns another assetAmountExternal value which represents the Aave balanceOf representing the principal plus interest * that will be transferred. This is required to maintain compatibility with Aave's ERC20 transfer functions. * @dev There is no loss of precision because this does exactly what Aave's calculation would do * @param underlyingToken token address of the underlying asset * @param netScaledBalanceExternal an amount representing the scaledBalanceOf in external decimal precision calculated from * Notional cash balances. This amount may be positive or negative depending on if assets are being deposited (positive) or * withdrawn (negative). * @return netBalanceExternal the Aave balanceOf equivalent as a signed integer */ function convertFromScaledBalanceExternal(address underlyingToken, int256 netScaledBalanceExternal) internal view returns (int256 netBalanceExternal) { if (netScaledBalanceExternal == 0) return 0; // We know that this value must be positive int256 index = _getReserveNormalizedIncome(underlyingToken); // Use the absolute value here so that the halfRay rounding is applied correctly for negative values int256 abs = netScaledBalanceExternal.abs(); // Mimic the WadRay math performed by Aave (but do it in int256 instead) // Overflow will occur when: (abs * index + halfRay) > int256.max // Here the first term is computed at compile time so it just does a division. If index is zero then // solidity will revert. require(abs <= (type(int256).max - halfRAY) / index); int256 absScaled = (abs * index + halfRAY) / RAY; return netScaledBalanceExternal > 0 ? absScaled : absScaled.neg(); } /// @dev getReserveNormalizedIncome returns a uint256, so we know that the return value here is /// always positive even though we are converting to a signed int function _getReserveNormalizedIncome(address underlyingAsset) private view returns (int256) { return SafeInt256.toInt( LibStorage.getLendingPool().lendingPool.getReserveNormalizedIncome(underlyingAsset) ); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./GenericToken.sol"; import "../../../../interfaces/compound/CErc20Interface.sol"; import "../../../../interfaces/compound/CEtherInterface.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../global/Types.sol"; library CompoundHandler { using SafeMath for uint256; // Return code for cTokens that represents no error uint256 internal constant COMPOUND_RETURN_CODE_NO_ERROR = 0; function mintCETH(Token memory token) internal { // Reverts on error CEtherInterface(token.tokenAddress).mint{value: msg.value}(); } function mint(Token memory token, uint256 underlyingAmountExternal) internal returns (int256) { uint256 success = CErc20Interface(token.tokenAddress).mint(underlyingAmountExternal); require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Mint"); } function redeemCETH( Token memory assetToken, address account, uint256 assetAmountExternal ) internal returns (uint256 underlyingAmountExternal) { // Although the contract should never end with any ETH or underlying token balances, we still do this // starting and ending check in the case that tokens are accidentally sent to the contract address. They // will not be sent to some lucky address in a windfall. uint256 startingBalance = address(this).balance; uint256 success = CErc20Interface(assetToken.tokenAddress).redeem(assetAmountExternal); require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Redeem"); uint256 endingBalance = address(this).balance; underlyingAmountExternal = endingBalance.sub(startingBalance); // Withdraws the underlying amount out to the destination account GenericToken.transferNativeTokenOut(account, underlyingAmountExternal); } function redeem( Token memory assetToken, Token memory underlyingToken, address account, uint256 assetAmountExternal ) internal returns (uint256 underlyingAmountExternal) { // Although the contract should never end with any ETH or underlying token balances, we still do this // starting and ending check in the case that tokens are accidentally sent to the contract address. They // will not be sent to some lucky address in a windfall. uint256 startingBalance = GenericToken.checkBalanceViaSelector(underlyingToken.tokenAddress, address(this), GenericToken.defaultBalanceOfSelector); uint256 success = CErc20Interface(assetToken.tokenAddress).redeem(assetAmountExternal); require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Redeem"); uint256 endingBalance = GenericToken.checkBalanceViaSelector(underlyingToken.tokenAddress, address(this), GenericToken.defaultBalanceOfSelector); underlyingAmountExternal = endingBalance.sub(startingBalance); // Withdraws the underlying amount out to the destination account GenericToken.safeTransferOut(underlyingToken.tokenAddress, account, underlyingAmountExternal); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; import "../../../../interfaces/IEIP20NonStandard.sol"; library GenericToken { bytes4 internal constant defaultBalanceOfSelector = IEIP20NonStandard.balanceOf.selector; /** * @dev Manually checks the balance of an account using the method selector. Reduces bytecode size and allows * for overriding the balanceOf selector to use scaledBalanceOf for aTokens */ function checkBalanceViaSelector( address token, address account, bytes4 balanceOfSelector ) internal returns (uint256 balance) { (bool success, bytes memory returnData) = token.staticcall(abi.encodeWithSelector(balanceOfSelector, account)); require(success); (balance) = abi.decode(returnData, (uint256)); } function transferNativeTokenOut( address account, uint256 amount ) internal { // This does not work with contracts, but is reentrancy safe. If contracts want to withdraw underlying // ETH they will have to withdraw the cETH token and then redeem it manually. payable(account).transfer(amount); } function safeTransferOut( address token, address account, uint256 amount ) internal { IEIP20NonStandard(token).transfer(account, amount); checkReturnCode(); } function safeTransferIn( address token, address account, uint256 amount ) internal { IEIP20NonStandard(token).transferFrom(account, address(this), amount); checkReturnCode(); } function checkReturnCode() internal pure { bool success; uint256[1] memory result; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := 1 // set success to true } case 32 { // This is a compliant ERC-20 returndatacopy(result, 0, 32) success := mload(result) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "ERC20"); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @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); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); 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].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 virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); 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 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); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _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 virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(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); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(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 Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @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 to 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 { } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IAToken { /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view returns (uint256); function UNDERLYING_ASSET_ADDRESS() external view returns (address); function symbol() external view returns (string memory); } interface IScaledBalanceToken { /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view returns (uint256); /** * @dev Returns the scaled balance of the user and the scaled total supply. * @param user The address of the user * @return The scaled balance of the user * @return The scaled balance and the scaled total supply **/ function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256); /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return The scaled total supply **/ function scaledTotalSupply() external view returns (uint256); } interface IATokenFull is IScaledBalanceToken, IERC20 { function decimals() external view returns (uint8); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.7.0; import "./CTokenInterface.sol"; interface CErc20Interface { /*** 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, CTokenInterface cTokenCollateral) external returns (uint); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.7.0; interface CEtherInterface { function mint() external payable; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ interface IEIP20NonStandard { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return balance */ function balanceOf(address owner) external view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @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 */ function transfer(address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @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 */ function transferFrom(address src, address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `approve` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @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 */ function approve(address spender, uint256 amount) external; /** * @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 remaining The number of tokens allowed to be spent */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.7.0; interface CTokenInterface { /*** User Interface ***/ function underlying() external view returns (address); 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) external view returns (uint); function exchangeRateCurrent() external returns (uint); function exchangeRateStored() external view returns (uint); function getCash() external view returns (uint); function accrueInterest() external returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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 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; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./PortfolioHandler.sol"; import "./BitmapAssetsHandler.sol"; import "../AccountContextHandler.sol"; import "../../global/Types.sol"; import "../../math/SafeInt256.sol"; /// @notice Helper library for transferring assets from one portfolio to another library TransferAssets { using AccountContextHandler for AccountContext; using PortfolioHandler for PortfolioState; using SafeInt256 for int256; /// @notice Decodes asset ids function decodeAssetId(uint256 id) internal pure returns ( uint256 currencyId, uint256 maturity, uint256 assetType ) { assetType = uint8(id); maturity = uint40(id >> 8); currencyId = uint16(id >> 48); } /// @notice Encodes asset ids function encodeAssetId( uint256 currencyId, uint256 maturity, uint256 assetType ) internal pure returns (uint256) { require(currencyId <= Constants.MAX_CURRENCIES); require(maturity <= type(uint40).max); require(assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); return uint256( (bytes32(uint256(uint16(currencyId))) << 48) | (bytes32(uint256(uint40(maturity))) << 8) | bytes32(uint256(uint8(assetType))) ); } /// @dev Used to flip the sign of assets to decrement the `from` account that is sending assets function invertNotionalAmountsInPlace(PortfolioAsset[] memory assets) internal pure { for (uint256 i; i < assets.length; i++) { assets[i].notional = assets[i].notional.neg(); } } /// @dev Useful method for hiding the logic of updating an account. WARNING: the account /// context returned from this method may not be the same memory location as the account /// context provided if the account is settled. function placeAssetsInAccount( address account, AccountContext memory accountContext, PortfolioAsset[] memory assets ) internal returns (AccountContext memory) { // If an account has assets that require settlement then placing assets inside it // may cause issues. require(!accountContext.mustSettleAssets(), "Account must settle"); if (accountContext.isBitmapEnabled()) { // Adds fCash assets into the account and finalized storage BitmapAssetsHandler.addMultipleifCashAssets(account, accountContext, assets); } else { PortfolioState memory portfolioState = PortfolioHandler.buildPortfolioState( account, accountContext.assetArrayLength, assets.length ); // This will add assets in memory portfolioState.addMultipleAssets(assets); // This will store assets and update the account context in memory accountContext.storeAssetsAndUpdateContext(account, portfolioState, false); } return accountContext; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../markets/CashGroup.sol"; import "../markets/AssetRate.sol"; import "../markets/DateTime.sol"; import "../portfolio/PortfolioHandler.sol"; import "../../math/SafeInt256.sol"; import "../../math/ABDKMath64x64.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library AssetHandler { using SafeMath for uint256; using SafeInt256 for int256; using CashGroup for CashGroupParameters; using AssetRate for AssetRateParameters; function isLiquidityToken(uint256 assetType) internal pure returns (bool) { return assetType >= Constants.MIN_LIQUIDITY_TOKEN_INDEX && assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX; } /// @notice Liquidity tokens settle every 90 days (not at the designated maturity). This method /// calculates the settlement date for any PortfolioAsset. function getSettlementDate(PortfolioAsset memory asset) internal pure returns (uint256) { require(asset.assetType > 0 && asset.assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); // dev: settlement date invalid asset type // 3 month tokens and fCash tokens settle at maturity if (asset.assetType <= Constants.MIN_LIQUIDITY_TOKEN_INDEX) return asset.maturity; uint256 marketLength = DateTime.getTradedMarket(asset.assetType - 1); // Liquidity tokens settle at tRef + 90 days. The formula to get a maturity is: // maturity = tRef + marketLength // Here we calculate: // tRef = (maturity - marketLength) + 90 days return asset.maturity.sub(marketLength).add(Constants.QUARTER); } /// @notice Returns the continuously compounded discount rate given an oracle rate and a time to maturity. /// The formula is: e^(-rate * timeToMaturity). function getDiscountFactor(uint256 timeToMaturity, uint256 oracleRate) internal pure returns (int256) { int128 expValue = ABDKMath64x64.fromUInt(oracleRate.mul(timeToMaturity).div(Constants.IMPLIED_RATE_TIME)); expValue = ABDKMath64x64.div(expValue, Constants.RATE_PRECISION_64x64); expValue = ABDKMath64x64.exp(ABDKMath64x64.neg(expValue)); expValue = ABDKMath64x64.mul(expValue, Constants.RATE_PRECISION_64x64); int256 discountFactor = ABDKMath64x64.toInt(expValue); return discountFactor; } /// @notice Present value of an fCash asset without any risk adjustments. function getPresentfCashValue( int256 notional, uint256 maturity, uint256 blockTime, uint256 oracleRate ) internal pure returns (int256) { if (notional == 0) return 0; // NOTE: this will revert if maturity < blockTime. That is the correct behavior because we cannot // discount matured assets. uint256 timeToMaturity = maturity.sub(blockTime); int256 discountFactor = getDiscountFactor(timeToMaturity, oracleRate); require(discountFactor <= Constants.RATE_PRECISION); // dev: get present value invalid discount factor return notional.mulInRatePrecision(discountFactor); } /// @notice Present value of an fCash asset with risk adjustments. Positive fCash value will be discounted more /// heavily than the oracle rate given and vice versa for negative fCash. function getRiskAdjustedPresentfCashValue( CashGroupParameters memory cashGroup, int256 notional, uint256 maturity, uint256 blockTime, uint256 oracleRate ) internal pure returns (int256) { if (notional == 0) return 0; // NOTE: this will revert if maturity < blockTime. That is the correct behavior because we cannot // discount matured assets. uint256 timeToMaturity = maturity.sub(blockTime); int256 discountFactor; if (notional > 0) { // If fCash is positive then discounting by a higher rate will result in a smaller // discount factor (e ^ -x), meaning a lower positive fCash value. discountFactor = getDiscountFactor( timeToMaturity, oracleRate.add(cashGroup.getfCashHaircut()) ); } else { uint256 debtBuffer = cashGroup.getDebtBuffer(); // If the adjustment exceeds the oracle rate we floor the value of the fCash // at the notional value. We don't want to require the account to hold more than // absolutely required. if (debtBuffer >= oracleRate) return notional; discountFactor = getDiscountFactor(timeToMaturity, oracleRate - debtBuffer); } require(discountFactor <= Constants.RATE_PRECISION); // dev: get risk adjusted pv, invalid discount factor return notional.mulInRatePrecision(discountFactor); } /// @notice Returns the non haircut claims on cash and fCash by the liquidity token. function getCashClaims(PortfolioAsset memory token, MarketParameters memory market) internal pure returns (int256 assetCash, int256 fCash) { require(isLiquidityToken(token.assetType) && token.notional >= 0); // dev: invalid asset, get cash claims assetCash = market.totalAssetCash.mul(token.notional).div(market.totalLiquidity); fCash = market.totalfCash.mul(token.notional).div(market.totalLiquidity); } /// @notice Returns the haircut claims on cash and fCash function getHaircutCashClaims( PortfolioAsset memory token, MarketParameters memory market, CashGroupParameters memory cashGroup ) internal pure returns (int256 assetCash, int256 fCash) { require(isLiquidityToken(token.assetType) && token.notional >= 0); // dev: invalid asset get haircut cash claims require(token.currencyId == cashGroup.currencyId); // dev: haircut cash claims, currency id mismatch // This won't overflow, the liquidity token haircut is stored as an uint8 int256 haircut = int256(cashGroup.getLiquidityHaircut(token.assetType)); assetCash = _calcToken(market.totalAssetCash, token.notional, haircut, market.totalLiquidity); fCash = _calcToken(market.totalfCash, token.notional, haircut, market.totalLiquidity); return (assetCash, fCash); } /// @dev This is here to clean up the stack in getHaircutCashClaims function _calcToken( int256 numerator, int256 tokens, int256 haircut, int256 liquidity ) private pure returns (int256) { return numerator.mul(tokens).mul(haircut).div(Constants.PERCENTAGE_DECIMALS).div(liquidity); } /// @notice Returns the asset cash claim and the present value of the fCash asset (if it exists) function getLiquidityTokenValue( uint256 index, CashGroupParameters memory cashGroup, MarketParameters memory market, PortfolioAsset[] memory assets, uint256 blockTime, bool riskAdjusted ) internal view returns (int256, int256) { PortfolioAsset memory liquidityToken = assets[index]; { (uint256 marketIndex, bool idiosyncratic) = DateTime.getMarketIndex( cashGroup.maxMarketIndex, liquidityToken.maturity, blockTime ); // Liquidity tokens can never be idiosyncratic require(!idiosyncratic); // dev: idiosyncratic liquidity token // This market will always be initialized, if a liquidity token exists that means the // market has some liquidity in it. cashGroup.loadMarket(market, marketIndex, true, blockTime); } int256 assetCashClaim; int256 fCashClaim; if (riskAdjusted) { (assetCashClaim, fCashClaim) = getHaircutCashClaims(liquidityToken, market, cashGroup); } else { (assetCashClaim, fCashClaim) = getCashClaims(liquidityToken, market); } // Find the matching fCash asset and net off the value, assumes that the portfolio is sorted and // in that case we know the previous asset will be the matching fCash asset if (index > 0) { PortfolioAsset memory maybefCash = assets[index - 1]; if ( maybefCash.assetType == Constants.FCASH_ASSET_TYPE && maybefCash.currencyId == liquidityToken.currencyId && maybefCash.maturity == liquidityToken.maturity ) { // Net off the fCashClaim here and we will discount it to present value in the second pass. // WARNING: this modifies the portfolio in memory and therefore we cannot store this portfolio! maybefCash.notional = maybefCash.notional.add(fCashClaim); // This state will prevent the fCash asset from being stored. maybefCash.storageState = AssetStorageState.RevertIfStored; return (assetCashClaim, 0); } } // If not matching fCash asset found then get the pv directly if (riskAdjusted) { int256 pv = getRiskAdjustedPresentfCashValue( cashGroup, fCashClaim, liquidityToken.maturity, blockTime, market.oracleRate ); return (assetCashClaim, pv); } else { int256 pv = getPresentfCashValue(fCashClaim, liquidityToken.maturity, blockTime, market.oracleRate); return (assetCashClaim, pv); } } /// @notice Returns present value of all assets in the cash group as asset cash and the updated /// portfolio index where the function has ended. /// @return the value of the cash group in asset cash function getNetCashGroupValue( PortfolioAsset[] memory assets, CashGroupParameters memory cashGroup, MarketParameters memory market, uint256 blockTime, uint256 portfolioIndex ) internal view returns (int256, uint256) { int256 presentValueAsset; int256 presentValueUnderlying; // First calculate value of liquidity tokens because we need to net off fCash value // before discounting to present value for (uint256 i = portfolioIndex; i < assets.length; i++) { if (!isLiquidityToken(assets[i].assetType)) continue; if (assets[i].currencyId != cashGroup.currencyId) break; (int256 assetCashClaim, int256 pv) = getLiquidityTokenValue( i, cashGroup, market, assets, blockTime, true // risk adjusted ); presentValueAsset = presentValueAsset.add(assetCashClaim); presentValueUnderlying = presentValueUnderlying.add(pv); } uint256 j = portfolioIndex; for (; j < assets.length; j++) { PortfolioAsset memory a = assets[j]; if (a.assetType != Constants.FCASH_ASSET_TYPE) continue; // If we hit a different currency id then we've accounted for all assets in this currency // j will mark the index where we don't have this currency anymore if (a.currencyId != cashGroup.currencyId) break; uint256 oracleRate = cashGroup.calculateOracleRate(a.maturity, blockTime); int256 pv = getRiskAdjustedPresentfCashValue( cashGroup, a.notional, a.maturity, blockTime, oracleRate ); presentValueUnderlying = presentValueUnderlying.add(pv); } presentValueAsset = presentValueAsset.add( cashGroup.assetRate.convertFromUnderlying(presentValueUnderlying) ); return (presentValueAsset, j); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../AccountContextHandler.sol"; import "../markets/CashGroup.sol"; import "../valuation/AssetHandler.sol"; import "../../math/Bitmap.sol"; import "../../math/SafeInt256.sol"; import "../../global/LibStorage.sol"; import "../../global/Constants.sol"; import "../../global/Types.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library BitmapAssetsHandler { using SafeMath for uint256; using SafeInt256 for int256; using Bitmap for bytes32; using CashGroup for CashGroupParameters; using AccountContextHandler for AccountContext; function getAssetsBitmap(address account, uint256 currencyId) internal view returns (bytes32 assetsBitmap) { mapping(address => mapping(uint256 => bytes32)) storage store = LibStorage.getAssetsBitmapStorage(); return store[account][currencyId]; } function setAssetsBitmap( address account, uint256 currencyId, bytes32 assetsBitmap ) internal { require(assetsBitmap.totalBitsSet() <= Constants.MAX_BITMAP_ASSETS, "Over max assets"); mapping(address => mapping(uint256 => bytes32)) storage store = LibStorage.getAssetsBitmapStorage(); store[account][currencyId] = assetsBitmap; } function getifCashNotional( address account, uint256 currencyId, uint256 maturity ) internal view returns (int256 notional) { mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage(); return store[account][currencyId][maturity].notional; } /// @notice Adds multiple assets to a bitmap portfolio function addMultipleifCashAssets( address account, AccountContext memory accountContext, PortfolioAsset[] memory assets ) internal { require(accountContext.isBitmapEnabled()); // dev: bitmap currency not set uint256 currencyId = accountContext.bitmapCurrencyId; for (uint256 i; i < assets.length; i++) { PortfolioAsset memory asset = assets[i]; if (asset.notional == 0) continue; require(asset.currencyId == currencyId); // dev: invalid asset in set ifcash assets require(asset.assetType == Constants.FCASH_ASSET_TYPE); // dev: invalid asset in set ifcash assets int256 finalNotional; finalNotional = addifCashAsset( account, currencyId, asset.maturity, accountContext.nextSettleTime, asset.notional ); if (finalNotional < 0) accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT; } } /// @notice Add an ifCash asset in the bitmap and mapping. Updates the bitmap in memory /// but not in storage. /// @return the updated assets bitmap and the final notional amount function addifCashAsset( address account, uint256 currencyId, uint256 maturity, uint256 nextSettleTime, int256 notional ) internal returns (int256) { bytes32 assetsBitmap = getAssetsBitmap(account, currencyId); mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage(); ifCashStorage storage fCashSlot = store[account][currencyId][maturity]; (uint256 bitNum, bool isExact) = DateTime.getBitNumFromMaturity(nextSettleTime, maturity); require(isExact); // dev: invalid maturity in set ifcash asset if (assetsBitmap.isBitSet(bitNum)) { // Bit is set so we read and update the notional amount int256 finalNotional = notional.add(fCashSlot.notional); require(type(int128).min <= finalNotional && finalNotional <= type(int128).max); // dev: bitmap notional overflow fCashSlot.notional = int128(finalNotional); // If the new notional is zero then turn off the bit if (finalNotional == 0) { assetsBitmap = assetsBitmap.setBit(bitNum, false); } setAssetsBitmap(account, currencyId, assetsBitmap); return finalNotional; } if (notional != 0) { // Bit is not set so we turn it on and update the mapping directly, no read required. require(type(int128).min <= notional && notional <= type(int128).max); // dev: bitmap notional overflow fCashSlot.notional = int128(notional); assetsBitmap = assetsBitmap.setBit(bitNum, true); setAssetsBitmap(account, currencyId, assetsBitmap); } return notional; } /// @notice Returns the present value of an asset function getPresentValue( address account, uint256 currencyId, uint256 maturity, uint256 blockTime, CashGroupParameters memory cashGroup, bool riskAdjusted ) internal view returns (int256) { int256 notional = getifCashNotional(account, currencyId, maturity); // In this case the asset has matured and the total value is just the notional amount if (maturity <= blockTime) { return notional; } else { uint256 oracleRate = cashGroup.calculateOracleRate(maturity, blockTime); if (riskAdjusted) { return AssetHandler.getRiskAdjustedPresentfCashValue( cashGroup, notional, maturity, blockTime, oracleRate ); } else { return AssetHandler.getPresentfCashValue( notional, maturity, blockTime, oracleRate ); } } } function getNetPresentValueFromBitmap( address account, uint256 currencyId, uint256 nextSettleTime, uint256 blockTime, CashGroupParameters memory cashGroup, bool riskAdjusted, bytes32 assetsBitmap ) internal view returns (int256 totalValueUnderlying, bool hasDebt) { uint256 bitNum = assetsBitmap.getNextBitNum(); while (bitNum != 0) { uint256 maturity = DateTime.getMaturityFromBitNum(nextSettleTime, bitNum); int256 pv = getPresentValue( account, currencyId, maturity, blockTime, cashGroup, riskAdjusted ); totalValueUnderlying = totalValueUnderlying.add(pv); if (pv < 0) hasDebt = true; // Turn off the bit and look for the next one assetsBitmap = assetsBitmap.setBit(bitNum, false); bitNum = assetsBitmap.getNextBitNum(); } } /// @notice Get the net present value of all the ifCash assets function getifCashNetPresentValue( address account, uint256 currencyId, uint256 nextSettleTime, uint256 blockTime, CashGroupParameters memory cashGroup, bool riskAdjusted ) internal view returns (int256 totalValueUnderlying, bool hasDebt) { bytes32 assetsBitmap = getAssetsBitmap(account, currencyId); return getNetPresentValueFromBitmap( account, currencyId, nextSettleTime, blockTime, cashGroup, riskAdjusted, assetsBitmap ); } /// @notice Returns the ifCash assets as an array function getifCashArray( address account, uint256 currencyId, uint256 nextSettleTime ) internal view returns (PortfolioAsset[] memory) { bytes32 assetsBitmap = getAssetsBitmap(account, currencyId); uint256 index = assetsBitmap.totalBitsSet(); PortfolioAsset[] memory assets = new PortfolioAsset[](index); index = 0; uint256 bitNum = assetsBitmap.getNextBitNum(); while (bitNum != 0) { uint256 maturity = DateTime.getMaturityFromBitNum(nextSettleTime, bitNum); int256 notional = getifCashNotional(account, currencyId, maturity); PortfolioAsset memory asset = assets[index]; asset.currencyId = currencyId; asset.maturity = maturity; asset.assetType = Constants.FCASH_ASSET_TYPE; asset.notional = notional; index += 1; // Turn off the bit and look for the next one assetsBitmap = assetsBitmap.setBit(bitNum, false); bitNum = assetsBitmap.getNextBitNum(); } return assets; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../global/Types.sol"; import "../global/Constants.sol"; /// @notice Helper methods for bitmaps, they are big-endian and 1-indexed. library Bitmap { /// @notice Set a bit on or off in a bitmap, index is 1-indexed function setBit( bytes32 bitmap, uint256 index, bool setOn ) internal pure returns (bytes32) { require(index >= 1 && index <= 256); // dev: set bit index bounds if (setOn) { return bitmap | (Constants.MSB >> (index - 1)); } else { return bitmap & ~(Constants.MSB >> (index - 1)); } } /// @notice Check if a bit is set function isBitSet(bytes32 bitmap, uint256 index) internal pure returns (bool) { require(index >= 1 && index <= 256); // dev: set bit index bounds return ((bitmap << (index - 1)) & Constants.MSB) == Constants.MSB; } /// @notice Count the total bits set function totalBitsSet(bytes32 bitmap) internal pure returns (uint256) { uint256 x = uint256(bitmap); x = (x & 0x5555555555555555555555555555555555555555555555555555555555555555) + (x >> 1 & 0x5555555555555555555555555555555555555555555555555555555555555555); x = (x & 0x3333333333333333333333333333333333333333333333333333333333333333) + (x >> 2 & 0x3333333333333333333333333333333333333333333333333333333333333333); x = (x & 0x0707070707070707070707070707070707070707070707070707070707070707) + (x >> 4); x = (x & 0x000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F) + (x >> 8 & 0x000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F); x = x + (x >> 16); x = x + (x >> 32); x = x + (x >> 64); return (x & 0xFF) + (x >> 128 & 0xFF); } // Does a binary search over x to get the position of the most significant bit function getMSB(uint256 x) internal pure returns (uint256 msb) { // If x == 0 then there is no MSB and this method will return zero. That would // be the same as the return value when x == 1 (MSB is zero indexed), so instead // we have this require here to ensure that the values don't get mixed up. require(x != 0); // dev: get msb zero value if (x >= 0x100000000000000000000000000000000) { x >>= 128; msb += 128; } if (x >= 0x10000000000000000) { x >>= 64; msb += 64; } if (x >= 0x100000000) { x >>= 32; msb += 32; } if (x >= 0x10000) { x >>= 16; msb += 16; } if (x >= 0x100) { x >>= 8; msb += 8; } if (x >= 0x10) { x >>= 4; msb += 4; } if (x >= 0x4) { x >>= 2; msb += 2; } if (x >= 0x2) msb += 1; // No need to shift xc anymore } /// @dev getMSB returns a zero indexed bit number where zero is the first bit counting /// from the right (little endian). Asset Bitmaps are counted from the left (big endian) /// and one indexed. function getNextBitNum(bytes32 bitmap) internal pure returns (uint256 bitNum) { // Short circuit the search if bitmap is all zeros if (bitmap == 0x00) return 0; return 255 - getMSB(uint256(bitmap)) + 1; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../internal/portfolio/PortfolioHandler.sol"; import "../internal/balances/BalanceHandler.sol"; import "../internal/settlement/SettlePortfolioAssets.sol"; import "../internal/settlement/SettleBitmapAssets.sol"; import "../internal/AccountContextHandler.sol"; /// @notice External library for settling assets library SettleAssetsExternal { using PortfolioHandler for PortfolioState; using AccountContextHandler for AccountContext; event AccountSettled(address indexed account); /// @notice Settles an account, returns the new account context object after settlement. /// @dev The memory location of the account context object is not the same as the one returned. function settleAccount( address account, AccountContext memory accountContext ) external returns (AccountContext memory) { // Defensive check to ensure that this is a valid settlement require(accountContext.mustSettleAssets()); SettleAmount[] memory settleAmounts; PortfolioState memory portfolioState; if (accountContext.isBitmapEnabled()) { (int256 settledCash, uint256 blockTimeUTC0) = SettleBitmapAssets.settleBitmappedCashGroup( account, accountContext.bitmapCurrencyId, accountContext.nextSettleTime, block.timestamp ); require(blockTimeUTC0 < type(uint40).max); // dev: block time utc0 overflow accountContext.nextSettleTime = uint40(blockTimeUTC0); settleAmounts = new SettleAmount[](1); settleAmounts[0] = SettleAmount(accountContext.bitmapCurrencyId, settledCash); } else { portfolioState = PortfolioHandler.buildPortfolioState( account, accountContext.assetArrayLength, 0 ); settleAmounts = SettlePortfolioAssets.settlePortfolio(portfolioState, block.timestamp); accountContext.storeAssetsAndUpdateContext(account, portfolioState, false); } BalanceHandler.finalizeSettleAmounts(account, accountContext, settleAmounts); emit AccountSettled(account); return accountContext; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./AssetHandler.sol"; import "./ExchangeRate.sol"; import "../markets/CashGroup.sol"; import "../AccountContextHandler.sol"; import "../balances/BalanceHandler.sol"; import "../portfolio/PortfolioHandler.sol"; import "../nToken/nTokenHandler.sol"; import "../nToken/nTokenCalculations.sol"; import "../../math/SafeInt256.sol"; library FreeCollateral { using SafeInt256 for int256; using Bitmap for bytes; using ExchangeRate for ETHRate; using AssetRate for AssetRateParameters; using AccountContextHandler for AccountContext; using nTokenHandler for nTokenPortfolio; /// @dev This is only used within the library to clean up the stack struct FreeCollateralFactors { int256 netETHValue; bool updateContext; uint256 portfolioIndex; CashGroupParameters cashGroup; MarketParameters market; PortfolioAsset[] portfolio; AssetRateParameters assetRate; nTokenPortfolio nToken; } /// @notice Checks if an asset is active in the portfolio function _isActiveInPortfolio(bytes2 currencyBytes) private pure returns (bool) { return currencyBytes & Constants.ACTIVE_IN_PORTFOLIO == Constants.ACTIVE_IN_PORTFOLIO; } /// @notice Checks if currency balances are active in the account returns them if true /// @return cash balance, nTokenBalance function _getCurrencyBalances(address account, bytes2 currencyBytes) private view returns (int256, int256) { if (currencyBytes & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES) { uint256 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS); // prettier-ignore ( int256 cashBalance, int256 nTokenBalance, /* lastClaimTime */, /* accountIncentiveDebt */ ) = BalanceHandler.getBalanceStorage(account, currencyId); return (cashBalance, nTokenBalance); } return (0, 0); } /// @notice Calculates the nToken asset value with a haircut set by governance /// @return the value of the account's nTokens after haircut, the nToken parameters function _getNTokenHaircutAssetPV( CashGroupParameters memory cashGroup, nTokenPortfolio memory nToken, int256 tokenBalance, uint256 blockTime ) internal view returns (int256, bytes6) { nToken.loadNTokenPortfolioNoCashGroup(cashGroup.currencyId); nToken.cashGroup = cashGroup; int256 nTokenAssetPV = nTokenCalculations.getNTokenAssetPV(nToken, blockTime); // (tokenBalance * nTokenValue * haircut) / totalSupply int256 nTokenHaircutAssetPV = tokenBalance .mul(nTokenAssetPV) .mul(uint8(nToken.parameters[Constants.PV_HAIRCUT_PERCENTAGE])) .div(Constants.PERCENTAGE_DECIMALS) .div(nToken.totalSupply); // nToken.parameters is returned for use in liquidation return (nTokenHaircutAssetPV, nToken.parameters); } /// @notice Calculates portfolio and/or nToken values while using the supplied cash groups and /// markets. The reason these are grouped together is because they both require storage reads of the same /// values. function _getPortfolioAndNTokenAssetValue( FreeCollateralFactors memory factors, int256 nTokenBalance, uint256 blockTime ) private view returns ( int256 netPortfolioValue, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters ) { // If the next asset matches the currency id then we need to calculate the cash group value if ( factors.portfolioIndex < factors.portfolio.length && factors.portfolio[factors.portfolioIndex].currencyId == factors.cashGroup.currencyId ) { // netPortfolioValue is in asset cash (netPortfolioValue, factors.portfolioIndex) = AssetHandler.getNetCashGroupValue( factors.portfolio, factors.cashGroup, factors.market, blockTime, factors.portfolioIndex ); } else { netPortfolioValue = 0; } if (nTokenBalance > 0) { (nTokenHaircutAssetValue, nTokenParameters) = _getNTokenHaircutAssetPV( factors.cashGroup, factors.nToken, nTokenBalance, blockTime ); } else { nTokenHaircutAssetValue = 0; nTokenParameters = 0; } } /// @notice Returns balance values for the bitmapped currency function _getBitmapBalanceValue( address account, uint256 blockTime, AccountContext memory accountContext, FreeCollateralFactors memory factors ) private view returns ( int256 cashBalance, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters ) { int256 nTokenBalance; // prettier-ignore ( cashBalance, nTokenBalance, /* lastClaimTime */, /* accountIncentiveDebt */ ) = BalanceHandler.getBalanceStorage(account, accountContext.bitmapCurrencyId); if (nTokenBalance > 0) { (nTokenHaircutAssetValue, nTokenParameters) = _getNTokenHaircutAssetPV( factors.cashGroup, factors.nToken, nTokenBalance, blockTime ); } else { nTokenHaircutAssetValue = 0; } } /// @notice Returns portfolio value for the bitmapped currency function _getBitmapPortfolioValue( address account, uint256 blockTime, AccountContext memory accountContext, FreeCollateralFactors memory factors ) private view returns (int256) { (int256 netPortfolioValueUnderlying, bool bitmapHasDebt) = BitmapAssetsHandler.getifCashNetPresentValue( account, accountContext.bitmapCurrencyId, accountContext.nextSettleTime, blockTime, factors.cashGroup, true // risk adjusted ); // Turns off has debt flag if it has changed bool contextHasAssetDebt = accountContext.hasDebt & Constants.HAS_ASSET_DEBT == Constants.HAS_ASSET_DEBT; if (bitmapHasDebt && !contextHasAssetDebt) { // Turn on has debt accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT; factors.updateContext = true; } else if (!bitmapHasDebt && contextHasAssetDebt) { // Turn off has debt accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_ASSET_DEBT; factors.updateContext = true; } // Return asset cash value return factors.cashGroup.assetRate.convertFromUnderlying(netPortfolioValueUnderlying); } function _updateNetETHValue( uint256 currencyId, int256 netLocalAssetValue, FreeCollateralFactors memory factors ) private view returns (ETHRate memory) { ETHRate memory ethRate = ExchangeRate.buildExchangeRate(currencyId); // Converts to underlying first, ETH exchange rates are in underlying factors.netETHValue = factors.netETHValue.add( ethRate.convertToETH(factors.assetRate.convertToUnderlying(netLocalAssetValue)) ); return ethRate; } /// @notice Stateful version of get free collateral, returns the total net ETH value and true or false if the account /// context needs to be updated. function getFreeCollateralStateful( address account, AccountContext memory accountContext, uint256 blockTime ) internal returns (int256, bool) { FreeCollateralFactors memory factors; bool hasCashDebt; if (accountContext.isBitmapEnabled()) { factors.cashGroup = CashGroup.buildCashGroupStateful(accountContext.bitmapCurrencyId); // prettier-ignore ( int256 netCashBalance, int256 nTokenHaircutAssetValue, /* nTokenParameters */ ) = _getBitmapBalanceValue(account, blockTime, accountContext, factors); if (netCashBalance < 0) hasCashDebt = true; int256 portfolioAssetValue = _getBitmapPortfolioValue(account, blockTime, accountContext, factors); int256 netLocalAssetValue = netCashBalance.add(nTokenHaircutAssetValue).add(portfolioAssetValue); factors.assetRate = factors.cashGroup.assetRate; _updateNetETHValue(accountContext.bitmapCurrencyId, netLocalAssetValue, factors); } else { factors.portfolio = PortfolioHandler.getSortedPortfolio( account, accountContext.assetArrayLength ); } bytes18 currencies = accountContext.activeCurrencies; while (currencies != 0) { bytes2 currencyBytes = bytes2(currencies); uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS); // Explicitly ensures that bitmap currency cannot be double counted require(currencyId != accountContext.bitmapCurrencyId); (int256 netLocalAssetValue, int256 nTokenBalance) = _getCurrencyBalances(account, currencyBytes); if (netLocalAssetValue < 0) hasCashDebt = true; if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) { factors.cashGroup = CashGroup.buildCashGroupStateful(currencyId); // prettier-ignore ( int256 netPortfolioAssetValue, int256 nTokenHaircutAssetValue, /* nTokenParameters */ ) = _getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime); netLocalAssetValue = netLocalAssetValue .add(netPortfolioAssetValue) .add(nTokenHaircutAssetValue); factors.assetRate = factors.cashGroup.assetRate; } else { // NOTE: we must set the proper assetRate when we updateNetETHValue factors.assetRate = AssetRate.buildAssetRateStateful(currencyId); } _updateNetETHValue(currencyId, netLocalAssetValue, factors); currencies = currencies << 16; } // Free collateral is the only method that examines all cash balances for an account at once. If there is no cash debt (i.e. // they have been repaid or settled via more debt) then this will turn off the flag. It's possible that this flag is out of // sync temporarily after a cash settlement and before the next free collateral check. The only downside for that is forcing // an account to do an extra free collateral check to turn off this setting. if ( accountContext.hasDebt & Constants.HAS_CASH_DEBT == Constants.HAS_CASH_DEBT && !hasCashDebt ) { accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_CASH_DEBT; factors.updateContext = true; } return (factors.netETHValue, factors.updateContext); } /// @notice View version of getFreeCollateral, does not use the stateful version of build cash group and skips /// all the update context logic. function getFreeCollateralView( address account, AccountContext memory accountContext, uint256 blockTime ) internal view returns (int256, int256[] memory) { FreeCollateralFactors memory factors; uint256 netLocalIndex; int256[] memory netLocalAssetValues = new int256[](10); if (accountContext.isBitmapEnabled()) { factors.cashGroup = CashGroup.buildCashGroupView(accountContext.bitmapCurrencyId); // prettier-ignore ( int256 netCashBalance, int256 nTokenHaircutAssetValue, /* nTokenParameters */ ) = _getBitmapBalanceValue(account, blockTime, accountContext, factors); int256 portfolioAssetValue = _getBitmapPortfolioValue(account, blockTime, accountContext, factors); netLocalAssetValues[netLocalIndex] = netCashBalance .add(nTokenHaircutAssetValue) .add(portfolioAssetValue); factors.assetRate = factors.cashGroup.assetRate; _updateNetETHValue( accountContext.bitmapCurrencyId, netLocalAssetValues[netLocalIndex], factors ); netLocalIndex++; } else { factors.portfolio = PortfolioHandler.getSortedPortfolio( account, accountContext.assetArrayLength ); } bytes18 currencies = accountContext.activeCurrencies; while (currencies != 0) { bytes2 currencyBytes = bytes2(currencies); uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS); // Explicitly ensures that bitmap currency cannot be double counted require(currencyId != accountContext.bitmapCurrencyId); int256 nTokenBalance; (netLocalAssetValues[netLocalIndex], nTokenBalance) = _getCurrencyBalances( account, currencyBytes ); if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) { factors.cashGroup = CashGroup.buildCashGroupView(currencyId); // prettier-ignore ( int256 netPortfolioValue, int256 nTokenHaircutAssetValue, /* nTokenParameters */ ) = _getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime); netLocalAssetValues[netLocalIndex] = netLocalAssetValues[netLocalIndex] .add(netPortfolioValue) .add(nTokenHaircutAssetValue); factors.assetRate = factors.cashGroup.assetRate; } else { factors.assetRate = AssetRate.buildAssetRateView(currencyId); } _updateNetETHValue(currencyId, netLocalAssetValues[netLocalIndex], factors); netLocalIndex++; currencies = currencies << 16; } return (factors.netETHValue, netLocalAssetValues); } /// @notice Calculates the net value of a currency within a portfolio, this is a bit /// convoluted to fit into the stack frame function _calculateLiquidationAssetValue( FreeCollateralFactors memory factors, LiquidationFactors memory liquidationFactors, bytes2 currencyBytes, bool setLiquidationFactors, uint256 blockTime ) private returns (int256) { uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS); (int256 netLocalAssetValue, int256 nTokenBalance) = _getCurrencyBalances(liquidationFactors.account, currencyBytes); if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) { factors.cashGroup = CashGroup.buildCashGroupStateful(currencyId); (int256 netPortfolioValue, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters) = _getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime); netLocalAssetValue = netLocalAssetValue .add(netPortfolioValue) .add(nTokenHaircutAssetValue); factors.assetRate = factors.cashGroup.assetRate; // If collateralCurrencyId is set to zero then this is a local currency liquidation if (setLiquidationFactors) { liquidationFactors.collateralCashGroup = factors.cashGroup; liquidationFactors.nTokenParameters = nTokenParameters; liquidationFactors.nTokenHaircutAssetValue = nTokenHaircutAssetValue; } } else { factors.assetRate = AssetRate.buildAssetRateStateful(currencyId); } return netLocalAssetValue; } /// @notice A version of getFreeCollateral used during liquidation to save off necessary additional information. function getLiquidationFactors( address account, AccountContext memory accountContext, uint256 blockTime, uint256 localCurrencyId, uint256 collateralCurrencyId ) internal returns (LiquidationFactors memory, PortfolioAsset[] memory) { FreeCollateralFactors memory factors; LiquidationFactors memory liquidationFactors; // This is only set to reduce the stack size liquidationFactors.account = account; if (accountContext.isBitmapEnabled()) { factors.cashGroup = CashGroup.buildCashGroupStateful(accountContext.bitmapCurrencyId); (int256 netCashBalance, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters) = _getBitmapBalanceValue(account, blockTime, accountContext, factors); int256 portfolioBalance = _getBitmapPortfolioValue(account, blockTime, accountContext, factors); int256 netLocalAssetValue = netCashBalance.add(nTokenHaircutAssetValue).add(portfolioBalance); factors.assetRate = factors.cashGroup.assetRate; ETHRate memory ethRate = _updateNetETHValue(accountContext.bitmapCurrencyId, netLocalAssetValue, factors); // If the bitmap currency id can only ever be the local currency where debt is held. // During enable bitmap we check that the account has no assets in their portfolio and // no cash debts. if (accountContext.bitmapCurrencyId == localCurrencyId) { liquidationFactors.localAssetAvailable = netLocalAssetValue; liquidationFactors.localETHRate = ethRate; liquidationFactors.localAssetRate = factors.assetRate; // This will be the case during local currency or local fCash liquidation if (collateralCurrencyId == 0) { // If this is local fCash liquidation, the cash group information is required // to calculate fCash haircuts and buffers. liquidationFactors.collateralCashGroup = factors.cashGroup; liquidationFactors.nTokenHaircutAssetValue = nTokenHaircutAssetValue; liquidationFactors.nTokenParameters = nTokenParameters; } } } else { factors.portfolio = PortfolioHandler.getSortedPortfolio( account, accountContext.assetArrayLength ); } bytes18 currencies = accountContext.activeCurrencies; while (currencies != 0) { bytes2 currencyBytes = bytes2(currencies); // This next bit of code here is annoyingly structured to get around stack size issues bool setLiquidationFactors; { uint256 tempId = uint256(uint16(currencyBytes & Constants.UNMASK_FLAGS)); // Explicitly ensures that bitmap currency cannot be double counted require(tempId != accountContext.bitmapCurrencyId); setLiquidationFactors = (tempId == localCurrencyId && collateralCurrencyId == 0) || tempId == collateralCurrencyId; } int256 netLocalAssetValue = _calculateLiquidationAssetValue( factors, liquidationFactors, currencyBytes, setLiquidationFactors, blockTime ); uint256 currencyId = uint256(uint16(currencyBytes & Constants.UNMASK_FLAGS)); ETHRate memory ethRate = _updateNetETHValue(currencyId, netLocalAssetValue, factors); if (currencyId == collateralCurrencyId) { // Ensure that this is set even if the cash group is not loaded, it will not be // loaded if the account only has a cash balance and no nTokens or assets liquidationFactors.collateralCashGroup.assetRate = factors.assetRate; liquidationFactors.collateralAssetAvailable = netLocalAssetValue; liquidationFactors.collateralETHRate = ethRate; } else if (currencyId == localCurrencyId) { // This branch will not be entered if bitmap is enabled liquidationFactors.localAssetAvailable = netLocalAssetValue; liquidationFactors.localETHRate = ethRate; liquidationFactors.localAssetRate = factors.assetRate; // If this is local fCash liquidation, the cash group information is required // to calculate fCash haircuts and buffers and it will have been set in // _calculateLiquidationAssetValue above because the account must have fCash assets, // there is no need to set cash group in this branch. } currencies = currencies << 16; } liquidationFactors.netETHValue = factors.netETHValue; require(liquidationFactors.netETHValue < 0, "Sufficient collateral"); // Refetch the portfolio if it exists, AssetHandler.getNetCashValue updates values in memory to do fCash // netting which will make further calculations incorrect. if (accountContext.assetArrayLength > 0) { factors.portfolio = PortfolioHandler.getSortedPortfolio( account, accountContext.assetArrayLength ); } return (liquidationFactors, factors.portfolio); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../valuation/AssetHandler.sol"; import "../markets/Market.sol"; import "../markets/AssetRate.sol"; import "../portfolio/PortfolioHandler.sol"; import "../../math/SafeInt256.sol"; import "../../global/Constants.sol"; import "../../global/Types.sol"; library SettlePortfolioAssets { using SafeInt256 for int256; using AssetRate for AssetRateParameters; using Market for MarketParameters; using PortfolioHandler for PortfolioState; using AssetHandler for PortfolioAsset; /// @dev Returns a SettleAmount array for the assets that will be settled function _getSettleAmountArray(PortfolioState memory portfolioState, uint256 blockTime) private pure returns (SettleAmount[] memory) { uint256 currenciesSettled; uint256 lastCurrencyId = 0; if (portfolioState.storedAssets.length == 0) return new SettleAmount[](0); // Loop backwards so "lastCurrencyId" will be set to the first currency in the portfolio // NOTE: if this contract is ever upgraded to Solidity 0.8+ then this i-- will underflow and cause // a revert, must wrap in an unchecked. for (uint256 i = portfolioState.storedAssets.length; (i--) > 0;) { PortfolioAsset memory asset = portfolioState.storedAssets[i]; // Assets settle on exactly blockTime if (asset.getSettlementDate() > blockTime) continue; // Assume that this is sorted by cash group and maturity, currencyId = 0 is unused so this // will work for the first asset if (lastCurrencyId != asset.currencyId) { lastCurrencyId = asset.currencyId; currenciesSettled++; } } // Actual currency ids will be set as we loop through the portfolio and settle assets SettleAmount[] memory settleAmounts = new SettleAmount[](currenciesSettled); if (currenciesSettled > 0) settleAmounts[0].currencyId = lastCurrencyId; return settleAmounts; } /// @notice Settles a portfolio array function settlePortfolio(PortfolioState memory portfolioState, uint256 blockTime) internal returns (SettleAmount[] memory) { AssetRateParameters memory settlementRate; SettleAmount[] memory settleAmounts = _getSettleAmountArray(portfolioState, blockTime); MarketParameters memory market; if (settleAmounts.length == 0) return settleAmounts; uint256 settleAmountIndex; for (uint256 i; i < portfolioState.storedAssets.length; i++) { PortfolioAsset memory asset = portfolioState.storedAssets[i]; uint256 settleDate = asset.getSettlementDate(); // Settlement date is on block time exactly if (settleDate > blockTime) continue; // On the first loop the lastCurrencyId is already set. if (settleAmounts[settleAmountIndex].currencyId != asset.currencyId) { // New currency in the portfolio settleAmountIndex += 1; settleAmounts[settleAmountIndex].currencyId = asset.currencyId; } int256 assetCash; if (asset.assetType == Constants.FCASH_ASSET_TYPE) { // Gets or sets the settlement rate, only do this before settling fCash settlementRate = AssetRate.buildSettlementRateStateful( asset.currencyId, asset.maturity, blockTime ); assetCash = settlementRate.convertFromUnderlying(asset.notional); portfolioState.deleteAsset(i); } else if (AssetHandler.isLiquidityToken(asset.assetType)) { Market.loadSettlementMarket(market, asset.currencyId, asset.maturity, settleDate); int256 fCash; (assetCash, fCash) = market.removeLiquidity(asset.notional); // Assets mature exactly on block time if (asset.maturity > blockTime) { // If fCash has not yet matured then add it to the portfolio _settleLiquidityTokenTofCash(portfolioState, i, fCash); } else { // Gets or sets the settlement rate, only do this before settling fCash settlementRate = AssetRate.buildSettlementRateStateful( asset.currencyId, asset.maturity, blockTime ); // If asset has matured then settle fCash to asset cash assetCash = assetCash.add(settlementRate.convertFromUnderlying(fCash)); portfolioState.deleteAsset(i); } } settleAmounts[settleAmountIndex].netCashChange = settleAmounts[settleAmountIndex] .netCashChange .add(assetCash); } return settleAmounts; } /// @notice Settles a liquidity token to idiosyncratic fCash, this occurs when the maturity is still in the future function _settleLiquidityTokenTofCash( PortfolioState memory portfolioState, uint256 index, int256 fCash ) private pure { PortfolioAsset memory liquidityToken = portfolioState.storedAssets[index]; // If the liquidity token's maturity is still in the future then we change the entry to be // an idiosyncratic fCash entry with the net fCash amount. if (index != 0) { // Check to see if the previous index is the matching fCash asset, this will be the case when the // portfolio is sorted PortfolioAsset memory fCashAsset = portfolioState.storedAssets[index - 1]; if ( fCashAsset.currencyId == liquidityToken.currencyId && fCashAsset.maturity == liquidityToken.maturity && fCashAsset.assetType == Constants.FCASH_ASSET_TYPE ) { // This fCash asset has not matured if we are settling to fCash fCashAsset.notional = fCashAsset.notional.add(fCash); fCashAsset.storageState = AssetStorageState.Update; portfolioState.deleteAsset(index); } } // We are going to delete this asset anyway, convert to an fCash position liquidityToken.assetType = Constants.FCASH_ASSET_TYPE; liquidityToken.notional = fCash; liquidityToken.storageState = AssetStorageState.Update; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../markets/AssetRate.sol"; import "../../global/LibStorage.sol"; import "../portfolio/BitmapAssetsHandler.sol"; import "../../math/SafeInt256.sol"; import "../../math/Bitmap.sol"; import "../../global/Constants.sol"; import "../../global/Types.sol"; /** * Settles a bitmap portfolio by checking for all matured fCash assets and turning them into cash * at the prevailing settlement rate. It will also update the asset bitmap to ensure that it continues * to correctly reference all actual maturities. fCash asset notional values are stored in *absolute* * time terms and bitmap bits are *relative* time terms based on the bitNumber and the stored oldSettleTime. * Remapping bits requires converting the old relative bit numbers to new relative bit numbers based on * newSettleTime and the absolute times (maturities) that the previous bitmap references. */ library SettleBitmapAssets { using SafeInt256 for int256; using AssetRate for AssetRateParameters; using Bitmap for bytes32; /// @notice Given a bitmap for a cash group and timestamps, will settle all assets /// that have matured and remap the bitmap to correspond to the current time. function settleBitmappedCashGroup( address account, uint256 currencyId, uint256 oldSettleTime, uint256 blockTime ) internal returns (int256 totalAssetCash, uint256 newSettleTime) { bytes32 bitmap = BitmapAssetsHandler.getAssetsBitmap(account, currencyId); // This newSettleTime will be set to the new `oldSettleTime`. The bits between 1 and // `lastSettleBit` (inclusive) will be shifted out of the bitmap and settled. The reason // that lastSettleBit is inclusive is that it refers to newSettleTime which always less // than the current block time. newSettleTime = DateTime.getTimeUTC0(blockTime); // If newSettleTime == oldSettleTime lastSettleBit will be zero require(newSettleTime >= oldSettleTime); // dev: new settle time before previous // Do not need to worry about validity, if newSettleTime is not on an exact bit we will settle up until // the closest maturity that is less than newSettleTime. (uint256 lastSettleBit, /* isValid */) = DateTime.getBitNumFromMaturity(oldSettleTime, newSettleTime); if (lastSettleBit == 0) return (totalAssetCash, newSettleTime); // Returns the next bit that is set in the bitmap uint256 nextBitNum = bitmap.getNextBitNum(); while (nextBitNum != 0 && nextBitNum <= lastSettleBit) { uint256 maturity = DateTime.getMaturityFromBitNum(oldSettleTime, nextBitNum); totalAssetCash = totalAssetCash.add( _settlefCashAsset(account, currencyId, maturity, blockTime) ); // Turn the bit off now that it is settled bitmap = bitmap.setBit(nextBitNum, false); nextBitNum = bitmap.getNextBitNum(); } bytes32 newBitmap; while (nextBitNum != 0) { uint256 maturity = DateTime.getMaturityFromBitNum(oldSettleTime, nextBitNum); (uint256 newBitNum, bool isValid) = DateTime.getBitNumFromMaturity(newSettleTime, maturity); require(isValid); // dev: invalid new bit num newBitmap = newBitmap.setBit(newBitNum, true); // Turn the bit off now that it is remapped bitmap = bitmap.setBit(nextBitNum, false); nextBitNum = bitmap.getNextBitNum(); } BitmapAssetsHandler.setAssetsBitmap(account, currencyId, newBitmap); } /// @dev Stateful settlement function to settle a bitmapped asset. Deletes the /// asset from storage after calculating it. function _settlefCashAsset( address account, uint256 currencyId, uint256 maturity, uint256 blockTime ) private returns (int256 assetCash) { mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage(); int256 notional = store[account][currencyId][maturity].notional; // Gets the current settlement rate or will store a new settlement rate if it does not // yet exist. AssetRateParameters memory rate = AssetRate.buildSettlementRateStateful(currencyId, maturity, blockTime); assetCash = rate.convertFromUnderlying(notional); delete store[account][currencyId][maturity]; return assetCash; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../balances/TokenHandler.sol"; import "../../math/SafeInt256.sol"; import "../../../interfaces/chainlink/AggregatorV2V3Interface.sol"; library ExchangeRate { using SafeInt256 for int256; /// @notice Converts a balance to ETH from a base currency. Buffers or haircuts are /// always applied in this method. /// @param er exchange rate object from base to ETH /// @return the converted balance denominated in ETH with Constants.INTERNAL_TOKEN_PRECISION function convertToETH(ETHRate memory er, int256 balance) internal pure returns (int256) { int256 multiplier = balance > 0 ? er.haircut : er.buffer; // We are converting internal balances here so we know they have INTERNAL_TOKEN_PRECISION decimals // internalDecimals * rateDecimals * multiplier / (rateDecimals * multiplierDecimals) // Therefore the result is in ethDecimals int256 result = balance.mul(er.rate).mul(multiplier).div(Constants.PERCENTAGE_DECIMALS).div( er.rateDecimals ); return result; } /// @notice Converts the balance denominated in ETH to the equivalent value in a base currency. /// Buffers and haircuts ARE NOT applied in this method. /// @param er exchange rate object from base to ETH /// @param balance amount (denominated in ETH) to convert function convertETHTo(ETHRate memory er, int256 balance) internal pure returns (int256) { // We are converting internal balances here so we know they have INTERNAL_TOKEN_PRECISION decimals // internalDecimals * rateDecimals / rateDecimals int256 result = balance.mul(er.rateDecimals).div(er.rate); return result; } /// @notice Calculates the exchange rate between two currencies via ETH. Returns the rate denominated in /// base exchange rate decimals: (baseRateDecimals * quoteRateDecimals) / quoteRateDecimals /// @param baseER base exchange rate struct /// @param quoteER quote exchange rate struct function exchangeRate(ETHRate memory baseER, ETHRate memory quoteER) internal pure returns (int256) { return baseER.rate.mul(quoteER.rateDecimals).div(quoteER.rate); } /// @notice Returns an ETHRate object used to calculate free collateral function buildExchangeRate(uint256 currencyId) internal view returns (ETHRate memory) { mapping(uint256 => ETHRateStorage) storage store = LibStorage.getExchangeRateStorage(); ETHRateStorage storage ethStorage = store[currencyId]; int256 rateDecimals; int256 rate; if (currencyId == Constants.ETH_CURRENCY_ID) { // ETH rates will just be 1e18, but will still have buffers, haircuts, // and liquidation discounts rateDecimals = Constants.ETH_DECIMALS; rate = Constants.ETH_DECIMALS; } else { // prettier-ignore ( /* roundId */, rate, /* uint256 startedAt */, /* updatedAt */, /* answeredInRound */ ) = ethStorage.rateOracle.latestRoundData(); require(rate > 0, "Invalid rate"); // No overflow, restricted on storage rateDecimals = int256(10**ethStorage.rateDecimalPlaces); if (ethStorage.mustInvert) { rate = rateDecimals.mul(rateDecimals).div(rate); } } return ETHRate({ rateDecimals: rateDecimals, rate: rate, buffer: ethStorage.buffer, haircut: ethStorage.haircut, liquidationDiscount: ethStorage.liquidationDiscount }); } }
Get the number of tokens `spender` is approved to spend on behalf of `account` currencyId Currency id of the nToken account tokenHolder The address of the account holding the funds spender The address of the account spending the funds return The number of tokens approved The specific allowance overrides the blanket whitelist
function nTokenTransferAllowance( uint16 currencyId, address tokenHolder, address spender ) external view override returns (uint256) { uint256 allowance = nTokenAllowance[tokenHolder][spender][currencyId]; if (allowance > 0) { return allowance; return nTokenWhitelist[tokenHolder][spender]; } }
10,315,706
./full_match/97/0x1D1bB1B8e428661F8a5F8549987331F12729150e/sources/project_/contracts/ERC20Farm.sol
Calculates number of blocks to pay reward for. _from: Starting block _to: Ending block return Number of blocks, that should be rewarded/
function _getMultiplier(uint256 _from, uint256 _to) private view returns (uint256) { uint256 finalBlock = getFinalBlockNumber(); if (_to <= finalBlock) { return _to - _from; return 0; return finalBlock - _from; } }
5,028,265
./partial_match/1/0x486Ae5A2df309Cbd7f86b6EaCF81f607e79c6128/sources/contracts/interfaces/IFarmingPod.sol
View functions User functions Owner functions Distributor functions
interface IFarmingPod is IPod { event FarmCreated(address token, address reward); event DistributorChanged(address oldDistributor, address newDistributor); event RewardAdded(uint256 reward, uint256 duration); function totalSupply() external view returns(uint256); function distributor() external view returns(address); function farmInfo() external view returns(FarmAccounting.Info memory); function farmed(address account) external view returns(uint256); function claim() external; function setDistributor(address distributor_) external; function startFarming(uint256 amount, uint256 period) external; function rescueFunds(IERC20 token, uint256 amount) external; }
16,161,544
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./BondDepositoryLib.sol"; import "./Facet.sol"; // import "hardhat/console.sol"; contract BondConfigFacet is Facet { using SafeMath for uint256; using SafeERC20 for IERC20; using BondDepositoryLib for LibBondStorage.Storage; /** * @notice allow anyone to send lost tokens (excluding principle or Necc) to the DAO * @return bool */ function recoverLostToken(address _token) external returns (bool) { require(_token != s.Necc); require(!EnumerableSet.contains(s.principles, _token)); IERC20(_token).safeTransfer( s.DAO, IERC20(_token).balanceOf(address(this)) ); return true; } /* ======== BondDepository ======== */ function initializeBondDepository( address _ndol, address _Necc, address _treasury, address _DAO ) external { onlyGov(); require(_Necc != address(0)); s.Necc = _Necc; require(_treasury != address(0)); s.treasury = _treasury; require(_DAO != address(0)); s.DAO = _DAO; require(_ndol != address(0)); s.ndol = _ndol; } /** * @notice initializes bond parameters */ function initializeBondTerms( uint256 _controlVariable, uint256 _minimumPrice, uint256 _maxPayout, uint256 _fee, uint256 _maxDebt, uint256 _initialDebt, uint256 _vestingTerm, bool _isLiquidityBond, address _priceFeed, address _principle ) external { onlyGov(); EnumerableSet.add(s.principles, _principle); uint256 _principleIndex = s.getIndexAt(_principle); require( // TODO: Remove >= into == s.terms[_principleIndex].controlVariable >= 0, "Bonds must be initialized from 0" ); s.terms[_principleIndex] = LibBondStorage.Terms({ controlVariable: _controlVariable, minimumPrice: _minimumPrice, maxPayout: _maxPayout, fee: _fee, maxDebt: _maxDebt, vestingTerm: _vestingTerm, isLiquidityBond: _isLiquidityBond }); s.totalDebt[_principleIndex] = _initialDebt; s.lastDecay[_principleIndex] = uint256(block.timestamp); if (_priceFeed != address(0)) { s.priceFeeds[_principleIndex] = _priceFeed; } } /* ======== POLICY FUNCTIONS ======== */ /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms( PARAMETER _parameter, uint256 _input, address _principle ) external { onlyGov(); uint256 _principleIndex = s.getIndexAt(_principle); if (_parameter == PARAMETER.VESTING) { // 0 require(_input >= 129600, "Vesting must be longer than 36 hours"); s.terms[_principleIndex].vestingTerm = uint256(_input); } else if (_parameter == PARAMETER.PAYOUT) { // 1 require(_input <= 1000, "Payout cannot be above 1 percent"); s.terms[_principleIndex].maxPayout = _input; } else if (_parameter == PARAMETER.FEE) { // 2 require(_input <= 10000, "DAO fee cannot exceed payout"); s.terms[_principleIndex].fee = _input; } else if (_parameter == PARAMETER.DEBT) { // 3 s.terms[_principleIndex].maxDebt = _input; } else if (_parameter == PARAMETER.MINPRICE) { // 4 s.terms[_principleIndex].minimumPrice = _input; } } function setAdjustment( bool _addition, uint256 _delta, uint256 _timeToTargetInSeconds, address _principle ) public { LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage(); require( (msg.sender == address(this)) || (msg.sender == ds.contractOwner), "BondDepository: Invalid contract owner" ); uint256 _principleIndex = s.getIndexAt(_principle); require( _timeToTargetInSeconds >= s.terms[0].vestingTerm, "Adjustment: Change too fast" ); s.bondDepositoryAdjustment[_principleIndex] = LibBondStorage .BondDepositoryAdjustment({ add: _addition, delta: _delta, timeToTarget: _timeToTargetInSeconds, lastTime: uint256(block.timestamp) }); } /* ======== Distributor ======== */ function initializeDistributor( uint256 _epochLength, uint256 _nextEpochTimestamp, address _principle ) public { onlyGov(); uint256 _principleIndex = s.getIndexAt(_principle); s.epochLength = _epochLength; s.nextEpochTimestamp[_principleIndex] = _nextEpochTimestamp; } /* ====== POLICY FUNCTIONS ====== */ /** @notice adds recipient for distributions @param _recipient address @param _rewardRate uint */ function addRecipient(address _recipient, uint256 _rewardRate) external { onlyGov(); require(_recipient != address(0)); require( _rewardRate <= 1_000_000, "Reward Rate cannot exceed denominator" ); s.info.push( LibBondStorage.Info({recipient: _recipient, rate: _rewardRate}) ); } /** @notice removes recipient for distributions @param _index uint @param _recipient address */ function removeRecipient(uint256 _index, address _recipient) external { onlyGov(); require(_recipient == s.info[_index].recipient, "Invalid recipient"); s.info[_index].recipient = address(0); s.info[_index].rate = 0; } /** @notice set adjustment info for a collector's reward rate @param _index uint @param _add bool @param _rate uint @param _target uint */ function setAdjustment( uint256 _index, bool _add, uint256 _rate, uint256 _target ) external { onlyGov(); require(address(0) != s.info[_index].recipient, "Invalid recipient"); if (!_add) { require( _rate <= s.distributorAdjustments[_index].rate, "Cannot decrease rate" ); } s.distributorAdjustments[_index] = LibBondStorage .DistributorAdjustment({add: _add, rate: _rate, target: _target}); } /* ======== Staking ======== */ function initializeStaking( uint256 _firstEpochNumber, uint32 _firstEpochTime, address _sNecc, address _nNecc ) public { onlyGov(); require(_sNecc != address(0)); require(_nNecc != address(0)); s.sNecc = _sNecc; s.nNecc = _nNecc; s.epoch = LibBondStorage.Epoch({ length: s.epochLength, number: _firstEpochNumber, endTime: _firstEpochTime, distribute: 0 }); } /** @notice prevent new deposits to address (protection from malicious activity) */ function toggleDepositLock(address _maliciousDepositor) external { onlyGov(); s.warmupInfo[_maliciousDepositor].lock = !s .warmupInfo[_maliciousDepositor] .lock; } /** @notice sets the contract address for LP staking @param _contract address */ function setContract(CONTRACTS _contract, address _address) external { onlyGov(); if (_contract == CONTRACTS.LOCKER) { // 2 require( s.locker == address(0), "Locker cannot be set more than once" ); s.locker = _address; } } /** * @notice set warmup period in epoch's numbers for new stakers * @param _warmupPeriod uint */ function setWarmup(uint256 _warmupPeriod) external { onlyGov(); s.warmupPeriod = _warmupPeriod; } function setFarmDistributor(address _farmDistributor) external { onlyGov(); s.farmDistributor = _farmDistributor; } function setDAO(address _DAO) external { onlyGov(); s.DAO = _DAO; } function setTreasury(address _treasury) external { onlyGov(); s.treasury = _treasury; } }
initializes bond parameters/ TODO: Remove >= into ==
function initializeBondTerms( uint256 _controlVariable, uint256 _minimumPrice, uint256 _maxPayout, uint256 _fee, uint256 _maxDebt, uint256 _initialDebt, uint256 _vestingTerm, bool _isLiquidityBond, address _priceFeed, address _principle ) external { onlyGov(); EnumerableSet.add(s.principles, _principle); uint256 _principleIndex = s.getIndexAt(_principle); require( s.terms[_principleIndex].controlVariable >= 0, "Bonds must be initialized from 0" ); s.terms[_principleIndex] = LibBondStorage.Terms({ controlVariable: _controlVariable, minimumPrice: _minimumPrice, maxPayout: _maxPayout, fee: _fee, maxDebt: _maxDebt, vestingTerm: _vestingTerm, isLiquidityBond: _isLiquidityBond }); s.totalDebt[_principleIndex] = _initialDebt; s.lastDecay[_principleIndex] = uint256(block.timestamp); if (_priceFeed != address(0)) { s.priceFeeds[_principleIndex] = _priceFeed; } }
15,796,130
//SPDX-License-Identifier: ISC pragma solidity 0.7.6; pragma experimental ABIEncoderV2; // Libraries import "./synthetix/SafeDecimalMath.sol"; import "./synthetix/SignedSafeDecimalMath.sol"; // Inherited import "@openzeppelin/contracts/access/Ownable.sol"; // Interfaces import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interfaces/IBlackScholes.sol"; import "./interfaces/ILyraGlobals.sol"; import "./interfaces/IOptionMarket.sol"; import "./interfaces/IOptionMarketPricer.sol"; import "./interfaces/IOptionGreekCache.sol"; /** * @title OptionGreekCache * @author Lyra * @dev Aggregates the netDelta and netStdVega of the OptionMarket by iterating over current listings. * Needs to be called by an external override actor as it's not feasible to do all the computation during the trade flow and * because delta/vega change over time and with movements in asset price and volatility. */ contract OptionGreekCache is IOptionGreekCache, Ownable { using SafeMath for uint; using SafeDecimalMath for uint; using SignedSafeMath for int; using SignedSafeDecimalMath for int; ILyraGlobals internal globals; IOptionMarket internal optionMarket; IOptionMarketPricer internal optionPricer; IBlackScholes internal blackScholes; // Limit due to gas constraints when updating uint public constant override MAX_LISTINGS_PER_BOARD = 10; // For calculating if the cache is stale based on spot price // These values can be quite wide as per listing updates occur whenever a trade does. uint public override staleUpdateDuration = 2 days; uint public override priceScalingPeriod = 7 days; uint public override maxAcceptablePercent = (1e18 / 100) * 20; // 20% uint public override minAcceptablePercent = (1e18 / 100) * 10; // 10% bool internal initialized; uint[] public override liveBoards; // Should be a clone of OptionMarket.liveBoards mapping(uint => OptionListingCache) public override listingCaches; mapping(uint => OptionBoardCache) public override boardCaches; GlobalCache public override globalCache; constructor() Ownable() {} /** * @dev Initialize the contract. * * @param _globals LyraGlobals address * @param _optionMarket OptionMarket address * @param _optionPricer OptionMarketPricer address */ function init( ILyraGlobals _globals, IOptionMarket _optionMarket, IOptionMarketPricer _optionPricer, IBlackScholes _blackScholes ) external { require(!initialized, "Contract already initialized"); globals = _globals; optionMarket = _optionMarket; optionPricer = _optionPricer; blackScholes = _blackScholes; initialized = true; } function setStaleCacheParameters( uint _staleUpdateDuration, uint _priceScalingPeriod, uint _maxAcceptablePercent, uint _minAcceptablePercent ) external override onlyOwner { require(_staleUpdateDuration >= 2 hours, "staleUpdateDuration too low"); require(_maxAcceptablePercent >= _minAcceptablePercent, "maxAcceptablePercent must be >= min"); require(_minAcceptablePercent >= (1e18 / 100) * 1, "minAcceptablePercent too low"); // Note: this value can be zero even though it is in the divisor as timeToExpiry must be < priceScalingPeriod for it // to be used. priceScalingPeriod = _priceScalingPeriod; minAcceptablePercent = _minAcceptablePercent; maxAcceptablePercent = _maxAcceptablePercent; staleUpdateDuration = _staleUpdateDuration; emit StaleCacheParametersUpdated( priceScalingPeriod, minAcceptablePercent, maxAcceptablePercent, staleUpdateDuration ); } //// // Add/Remove boards //// /** * @notice Adds a new OptionBoardCache. * @dev Called by the OptionMarket when an OptionBoard is added. * * @param boardId The id of the OptionBoard. */ function addBoard(uint boardId) external override onlyOptionMarket { // Load in board from OptionMarket, adding net positions to global count (, uint expiry, uint iv, ) = optionMarket.optionBoards(boardId); uint[] memory listings = optionMarket.getBoardListings(boardId); require(listings.length <= MAX_LISTINGS_PER_BOARD, "too many listings for board"); OptionBoardCache storage boardCache = boardCaches[boardId]; boardCache.id = boardId; boardCache.expiry = expiry; boardCache.iv = iv; liveBoards.push(boardId); for (uint i = 0; i < listings.length; i++) { _addNewListingToListingCache(boardCache, listings[i]); } _updateBoardLastUpdatedAt(boardCache); } /** * @notice Removes an OptionBoardCache. * @dev Called by the OptionMarket when an OptionBoard is liquidated. * * @param boardId The id of the OptionBoard. */ function removeBoard(uint boardId) external override onlyOptionMarket { // Remove board from cache, removing net positions from global count OptionBoardCache memory boardCache = boardCaches[boardId]; globalCache.netDelta = globalCache.netDelta.sub(boardCache.netDelta); globalCache.netStdVega = globalCache.netStdVega.sub(boardCache.netStdVega); // Clean up, cache isn't necessary for settle logic for (uint i = 0; i < boardCache.listings.length; i++) { delete listingCaches[boardCache.listings[i]]; } for (uint i = 0; i < liveBoards.length; i++) { if (liveBoards[i] == boardId) { liveBoards[i] = liveBoards[liveBoards.length - 1]; liveBoards.pop(); break; } } delete boardCaches[boardId]; emit GlobalCacheUpdated(globalCache.netDelta, globalCache.netStdVega); } /** * @dev modifies an OptionBoard's baseIv * * @param boardId The id of the OptionBoard. * @param newIv The baseIv of the OptionBoard. */ function setBoardIv(uint boardId, uint newIv) external override onlyOptionMarket { // Remove board from cache, removing net positions from global count OptionBoardCache storage boardCache = boardCaches[boardId]; boardCache.iv = newIv; } /** * @dev modifies an OptionListing's skew * * @param listingId The id of the OptionListing. * @param newSkew The skew of the OptionListing. */ function setListingSkew(uint listingId, uint newSkew) external override onlyOptionMarket { // Remove board from cache, removing net positions from global count OptionListingCache storage listingCache = listingCaches[listingId]; listingCache.skew = newSkew; } /** * @notice Add a new listing to the listingCaches and the listingId to the boardCache * * @param boardId The id of the Board * @param listingId The id of the OptionListing. */ function addListingToBoard(uint boardId, uint listingId) external override onlyOptionMarket { OptionBoardCache storage boardCache = boardCaches[boardId]; require(boardCache.listings.length + 1 <= MAX_LISTINGS_PER_BOARD, "too many listings for board"); _addNewListingToListingCache(boardCache, listingId); } /** * @notice Add a new listing to the listingCaches * * @param boardCache The OptionBoardCache object the listing is being added to * @param listingId The id of the OptionListing. */ function _addNewListingToListingCache(OptionBoardCache storage boardCache, uint listingId) internal { IOptionMarket.OptionListing memory listing = getOptionMarketListing(listingId); // This is only called when a new board or a new listing is added, so exposure values will be 0 OptionListingCache storage listingCache = listingCaches[listing.id]; listingCache.id = listing.id; listingCache.strike = listing.strike; listingCache.boardId = listing.boardId; listingCache.skew = listing.skew; boardCache.listings.push(listingId); } /** * @notice Retrieves an OptionListing from the OptionMarket. * * @param listingId The id of the OptionListing. */ function getOptionMarketListing(uint listingId) internal view returns (IOptionMarket.OptionListing memory) { (uint id, uint strike, uint skew, uint longCall, uint shortCall, uint longPut, uint shortPut, uint boardId) = optionMarket.optionListings(listingId); return IOptionMarket.OptionListing(id, strike, skew, longCall, shortCall, longPut, shortPut, boardId); } //// // Updating greeks/caches //// /** * @notice Updates all stale boards. */ function updateAllStaleBoards() external override returns (int) { // Check all boards to see if they are stale ILyraGlobals.GreekCacheGlobals memory greekCacheGlobals = globals.getGreekCacheGlobals(address(optionMarket)); _updateAllStaleBoards(greekCacheGlobals); return globalCache.netDelta; } /** * @dev Updates all stale boards. * * @param greekCacheGlobals The GreekCacheGlobals. */ function _updateAllStaleBoards(ILyraGlobals.GreekCacheGlobals memory greekCacheGlobals) internal { for (uint i = 0; i < liveBoards.length; i++) { uint boardId = liveBoards[i]; if (_isBoardCacheStale(boardId, greekCacheGlobals.spotPrice)) { // This updates all listings in the board, even though it is not strictly necessary _updateBoardCachedGreeks(greekCacheGlobals, boardId); } } } /** * @notice Updates the cached greeks for an OptionBoardCache. * * @param boardCacheId The id of the OptionBoardCache. */ function updateBoardCachedGreeks(uint boardCacheId) external override { _updateBoardCachedGreeks(globals.getGreekCacheGlobals(address(optionMarket)), boardCacheId); } /** * @dev Updates the cached greeks for an OptionBoardCache. * * @param greekCacheGlobals The GreekCacheGlobals. * @param boardCacheId The id of the OptionBoardCache. */ function _updateBoardCachedGreeks(ILyraGlobals.GreekCacheGlobals memory greekCacheGlobals, uint boardCacheId) internal { OptionBoardCache storage boardCache = boardCaches[boardCacheId]; // In the case the board doesnt exist, listings.length is 0, so nothing happens for (uint i = 0; i < boardCache.listings.length; i++) { OptionListingCache storage listingCache = listingCaches[boardCache.listings[i]]; _updateListingCachedGreeks( greekCacheGlobals, listingCache, boardCache, true, listingCache.callExposure, listingCache.putExposure ); } boardCache.minUpdatedAt = block.timestamp; boardCache.minUpdatedAtPrice = greekCacheGlobals.spotPrice; boardCache.maxUpdatedAtPrice = greekCacheGlobals.spotPrice; _updateGlobalLastUpdatedAt(); } /** * @notice Updates the OptionListingCache to reflect the new exposure. * * @param greekCacheGlobals The GreekCacheGlobals. * @param listingCacheId The id of the OptionListingCache. * @param newCallExposure The new call exposure of the OptionListing. * @param newPutExposure The new put exposure of the OptionListing. * @param iv The new iv of the OptionBoardCache. * @param skew The new skew of the OptionListingCache. */ function updateListingCacheAndGetPrice( ILyraGlobals.GreekCacheGlobals memory greekCacheGlobals, uint listingCacheId, int newCallExposure, int newPutExposure, uint iv, uint skew ) external override onlyOptionMarketPricer returns (IOptionMarketPricer.Pricing memory) { require(!_isGlobalCacheStale(greekCacheGlobals.spotPrice), "Global cache is stale"); OptionListingCache storage listingCache = listingCaches[listingCacheId]; OptionBoardCache storage boardCache = boardCaches[listingCache.boardId]; int callExposureDiff = newCallExposure.sub(listingCache.callExposure); int putExposureDiff = newPutExposure.sub(listingCache.putExposure); require(callExposureDiff == 0 || putExposureDiff == 0, "both call and put exposure updated"); boardCache.iv = iv; listingCache.skew = skew; // The AMM's net std vega is opposite to the global sum of user's std vega int preTradeAmmNetStdVega = -globalCache.netStdVega; IOptionMarketPricer.Pricing memory pricing = _updateListingCachedGreeks( greekCacheGlobals, listingCache, boardCache, callExposureDiff != 0, newCallExposure, newPutExposure ); pricing.preTradeAmmNetStdVega = preTradeAmmNetStdVega; _updateBoardLastUpdatedAt(boardCache); return pricing; } /** * @dev Updates an OptionListingCache. * * @param greekCacheGlobals The GreekCacheGlobals. * @param listingCache The OptionListingCache. * @param boardCache The OptionBoardCache. * @param returnCallPrice If true, return the call price, otherwise return the put price. */ function _updateListingCachedGreeks( ILyraGlobals.GreekCacheGlobals memory greekCacheGlobals, OptionListingCache storage listingCache, OptionBoardCache storage boardCache, bool returnCallPrice, int newCallExposure, int newPutExposure ) internal returns (IOptionMarketPricer.Pricing memory pricing) { IBlackScholes.PricesDeltaStdVega memory pricesDeltaStdVega = blackScholes.pricesDeltaStdVega( timeToMaturitySeconds(boardCache.expiry), boardCache.iv.multiplyDecimal(listingCache.skew), greekCacheGlobals.spotPrice, listingCache.strike, greekCacheGlobals.rateAndCarry ); // (newCallExposure * newCallDelta - oldCallExposure * oldCallDelta) // + (newPutExposure * newPutDelta - oldPutExposure * oldPutDelta) int netDeltaDiff = ( (newCallExposure.multiplyDecimal(pricesDeltaStdVega.callDelta)) // newCall .sub(listingCache.callExposure.multiplyDecimal(listingCache.callDelta)) .add( (newPutExposure.multiplyDecimal(pricesDeltaStdVega.putDelta)).sub( listingCache.putExposure.multiplyDecimal(listingCache.putDelta) ) ) ); int netStdVegaDiff = newCallExposure.add(newPutExposure).multiplyDecimal(int(pricesDeltaStdVega.stdVega)).sub( listingCache.callExposure.add(listingCache.putExposure).multiplyDecimal(int(listingCache.stdVega)) ); if (listingCache.callExposure != newCallExposure || listingCache.putExposure != newPutExposure) { emit ListingExposureUpdated(listingCache.id, newCallExposure, newPutExposure); } listingCache.callExposure = newCallExposure; listingCache.putExposure = newPutExposure; listingCache.callDelta = pricesDeltaStdVega.callDelta; listingCache.putDelta = pricesDeltaStdVega.putDelta; listingCache.stdVega = pricesDeltaStdVega.stdVega; listingCache.updatedAt = block.timestamp; listingCache.updatedAtPrice = greekCacheGlobals.spotPrice; boardCache.netDelta = boardCache.netDelta.add(netDeltaDiff); boardCache.netStdVega = boardCache.netStdVega.add(netStdVegaDiff); globalCache.netDelta = globalCache.netDelta.add(netDeltaDiff); globalCache.netStdVega = globalCache.netStdVega.add(netStdVegaDiff); pricing.optionPrice = returnCallPrice ? pricesDeltaStdVega.callPrice : pricesDeltaStdVega.putPrice; // AMM's net positions are the inverse of the user's net position pricing.postTradeAmmNetStdVega = -globalCache.netStdVega; pricing.callDelta = pricesDeltaStdVega.callDelta; emit ListingGreeksUpdated( listingCache.id, pricesDeltaStdVega.callDelta, pricesDeltaStdVega.putDelta, pricesDeltaStdVega.stdVega, greekCacheGlobals.spotPrice, boardCache.iv, listingCache.skew ); emit GlobalCacheUpdated(globalCache.netDelta, globalCache.netStdVega); return pricing; } /** * @notice Checks if the GlobalCache is stale. */ function isGlobalCacheStale() external view override returns (bool) { // Check all boards to see if they are stale uint currentPrice = getCurrentPrice(); return _isGlobalCacheStale(currentPrice); } /** * @dev Checks if the GlobalCache is stale. * * @param spotPrice The price of the baseAsset. */ function _isGlobalCacheStale(uint spotPrice) internal view returns (bool) { // Check all boards to see if they are stale return (isUpdatedAtTimeStale(globalCache.minUpdatedAt) || !isPriceMoveAcceptable( globalCache.minUpdatedAtPrice, spotPrice, timeToMaturitySeconds(globalCache.minExpiryTimestamp) ) || !isPriceMoveAcceptable( globalCache.maxUpdatedAtPrice, spotPrice, timeToMaturitySeconds(globalCache.minExpiryTimestamp) )); } /** * @notice Checks if the OptionBoardCache is stale. * * @param boardCacheId The OptionBoardCache id. */ function isBoardCacheStale(uint boardCacheId) external view override returns (bool) { uint spotPrice = getCurrentPrice(); return _isBoardCacheStale(boardCacheId, spotPrice); } /** * @dev Checks if the OptionBoardCache is stale. * * @param boardCacheId The OptionBoardCache id. * @param spotPrice The price of the baseAsset. */ function _isBoardCacheStale(uint boardCacheId, uint spotPrice) internal view returns (bool) { // We do not have to check every individual listing, as the OptionBoardCache // should always keep the minimum values. OptionBoardCache memory boardCache = boardCaches[boardCacheId]; require(boardCache.id != 0, "Board does not exist"); return isUpdatedAtTimeStale(boardCache.minUpdatedAt) || !isPriceMoveAcceptable(boardCache.minUpdatedAtPrice, spotPrice, timeToMaturitySeconds(boardCache.expiry)) || !isPriceMoveAcceptable(boardCache.maxUpdatedAtPrice, spotPrice, timeToMaturitySeconds(boardCache.expiry)); } /** * @dev Checks if `updatedAt` is stale. * * @param updatedAt The time of the last update. */ function isUpdatedAtTimeStale(uint updatedAt) internal view returns (bool) { // This can be more complex than just checking the item wasn't updated in the last two hours return getSecondsTo(updatedAt, block.timestamp) > staleUpdateDuration; } /** * @dev Check if the price move of an asset is acceptable given the time to expiry. * * @param pastPrice The previous price. * @param currentPrice The current price. * @param timeToExpirySec The time to expiry in seconds. */ function isPriceMoveAcceptable( uint pastPrice, uint currentPrice, uint timeToExpirySec ) internal view returns (bool) { uint acceptablePriceMovementPercent = maxAcceptablePercent; if (timeToExpirySec < priceScalingPeriod) { acceptablePriceMovementPercent = ((maxAcceptablePercent.sub(minAcceptablePercent)).mul(timeToExpirySec)) .div(priceScalingPeriod) .add(minAcceptablePercent); } uint acceptablePriceMovement = pastPrice.multiplyDecimal(acceptablePriceMovementPercent); if (currentPrice > pastPrice) { return currentPrice.sub(pastPrice) < acceptablePriceMovement; } else { return pastPrice.sub(currentPrice) < acceptablePriceMovement; } } /** * @dev Updates `lastUpdatedAt` for an OptionBoardCache. * * @param boardCache The OptionBoardCache. */ function _updateBoardLastUpdatedAt(OptionBoardCache storage boardCache) internal { OptionListingCache memory listingCache = listingCaches[boardCache.listings[0]]; uint minUpdate = listingCache.updatedAt; uint minPrice = listingCache.updatedAtPrice; uint maxPrice = listingCache.updatedAtPrice; for (uint i = 1; i < boardCache.listings.length; i++) { listingCache = listingCaches[boardCache.listings[i]]; if (listingCache.updatedAt < minUpdate) { minUpdate = listingCache.updatedAt; } if (listingCache.updatedAtPrice < minPrice) { minPrice = listingCache.updatedAtPrice; } else if (listingCache.updatedAtPrice > maxPrice) { maxPrice = listingCache.updatedAtPrice; } } boardCache.minUpdatedAt = minUpdate; boardCache.minUpdatedAtPrice = minPrice; boardCache.maxUpdatedAtPrice = maxPrice; _updateGlobalLastUpdatedAt(); } /** * @dev Updates global `lastUpdatedAt`. */ function _updateGlobalLastUpdatedAt() internal { OptionBoardCache memory boardCache = boardCaches[liveBoards[0]]; uint minUpdate = boardCache.minUpdatedAt; uint minPrice = boardCache.minUpdatedAtPrice; uint minExpiry = boardCache.expiry; uint maxPrice = boardCache.maxUpdatedAtPrice; for (uint i = 1; i < liveBoards.length; i++) { boardCache = boardCaches[liveBoards[i]]; if (boardCache.minUpdatedAt < minUpdate) { minUpdate = boardCache.minUpdatedAt; } if (boardCache.minUpdatedAtPrice < minPrice) { minPrice = boardCache.minUpdatedAtPrice; } if (boardCache.maxUpdatedAtPrice > maxPrice) { maxPrice = boardCache.maxUpdatedAtPrice; } if (boardCache.expiry < minExpiry) { minExpiry = boardCache.expiry; } } globalCache.minUpdatedAt = minUpdate; globalCache.minUpdatedAtPrice = minPrice; globalCache.maxUpdatedAtPrice = maxPrice; globalCache.minExpiryTimestamp = minExpiry; } /** * @dev Returns time to maturity for a given expiry. */ function timeToMaturitySeconds(uint expiry) internal view returns (uint) { return getSecondsTo(block.timestamp, expiry); } /** * @dev Returns the difference in seconds between two dates. */ function getSecondsTo(uint fromTime, uint toTime) internal pure returns (uint) { if (toTime > fromTime) { return toTime - fromTime; } return 0; } /** * @dev Get the price of the baseAsset for the OptionMarket. */ function getCurrentPrice() internal view returns (uint) { return globals.getSpotPriceForMarket(address(optionMarket)); } /** * @dev Get the current cached global netDelta value. */ function getGlobalNetDelta() external view override returns (int) { return globalCache.netDelta; } modifier onlyOptionMarket virtual { require(msg.sender == address(optionMarket), "Only optionMarket permitted"); _; } modifier onlyOptionMarketPricer virtual { require(msg.sender == address(optionPricer), "Only optionPricer permitted"); _; } /** * @dev Emitted when stale cache parameters are updated. */ event StaleCacheParametersUpdated( uint priceScalingPeriod, uint minAcceptablePercent, uint maxAcceptablePercent, uint staleUpdateDuration ); /** * @dev Emitted when the cache of an OptionListing is updated. */ event ListingGreeksUpdated( uint indexed listingId, int callDelta, int putDelta, uint vega, uint price, uint baseIv, uint skew ); /** * @dev Emitted when the exposure of an OptionListing is updated. */ event ListingExposureUpdated(uint indexed listingId, int newCallExposure, int newPutExposure); /** * @dev Emitted when the GlobalCache is updated. */ event GlobalCacheUpdated(int netDelta, int netStdVega); }
Get the current cached global netDelta value./
function getGlobalNetDelta() external view override returns (int) { return globalCache.netDelta; }
913,003
./full_match/5/0x6022eFfDd18125A83cccd0B9D59017a3e392580D/sources/contracts/TheGardens.sol
getBeeMintingData: Function to get the bee NFT minting data for a minter. This function is public and can be called by anyone. return honeySaleMinted uint8 - The number of bee NFTs minted by the minter during the Honeylist sale. return pollenSaleMinted uint8 - The number of bee NFTs minted by the minter during the Pollen sale. This function gets the minting data for a minter, which is used to determine the number of bee NFTs that can be minted per wallet during the sale. The minting data consists of two values: the number of bee NFTs minted during the Honeylist sale and the number of bee NFTs minted during the Pollen sale./ Get the minter's minting data from the mapping Extract the number of bee NFTs minted during the Honeylist sale and the Pollen sale
function getBeeMintingData() public view returns (uint8 honeySaleMinted, uint8 pollenSaleMinted) { uint8 _mintingData = mintingData[msg.sender]; honeySaleMinted = uint8(_mintingData & 0x0F); pollenSaleMinted = uint8((_mintingData & 0xF0) >> 4); }
7,039,098
pragma solidity ^0.4.15; /** * @title Ownership interface * * Perminent ownership * * #created 01/10/2017 * #author Frank Bonnet */ contract IOwnership { /** * Returns true if `_account` is the current owner * * @param _account The address to test against */ function isOwner(address _account) constant returns (bool); /** * Gets the current owner * * @return address The current owner */ function getOwner() constant returns (address); } /** * @title Ownership * * Perminent ownership * * #created 01/10/2017 * #author Frank Bonnet */ contract Ownership is IOwnership { // Owner address internal owner; /** * The publisher is the inital owner */ function Ownership() { owner = msg.sender; } /** * Access is restricted to the current owner */ modifier only_owner() { require(msg.sender == owner); _; } /** * Returns true if `_account` is the current owner * * @param _account The address to test against */ function isOwner(address _account) public constant returns (bool) { return _account == owner; } /** * Gets the current owner * * @return address The current owner */ function getOwner() public constant returns (address) { return owner; } } /** * @title Transferable ownership interface * * Enhances ownership by allowing the current owner to * transfer ownership to a new owner * * #created 01/10/2017 * #author Frank Bonnet */ contract ITransferableOwnership { /** * Transfer ownership to `_newOwner` * * @param _newOwner The address of the account that will become the new owner */ function transferOwnership(address _newOwner); } /** * @title Transferable ownership * * Enhances ownership by allowing the current owner to * transfer ownership to a new owner * * #created 01/10/2017 * #author Frank Bonnet */ contract TransferableOwnership is ITransferableOwnership, Ownership { /** * Transfer ownership to `_newOwner` * * @param _newOwner The address of the account that will become the new owner */ function transferOwnership(address _newOwner) public only_owner { owner = _newOwner; } } /** * @title Multi-owned interface * * Interface that allows multiple owners * * #created 09/10/2017 * #author Frank Bonnet */ contract IMultiOwned { /** * Returns true if `_account` is an owner * * @param _account The address to test against */ function isOwner(address _account) constant returns (bool); /** * Returns the amount of owners * * @return The amount of owners */ function getOwnerCount() constant returns (uint); /** * Gets the owner at `_index` * * @param _index The index of the owner * @return The address of the owner found at `_index` */ function getOwnerAt(uint _index) constant returns (address); /** * Adds `_account` as a new owner * * @param _account The account to add as an owner */ function addOwner(address _account); /** * Removes `_account` as an owner * * @param _account The account to remove as an owner */ function removeOwner(address _account); } /** * @title Token retrieve interface * * Allows tokens to be retrieved from a contract * * #created 29/09/2017 * #author Frank Bonnet */ contract ITokenRetriever { /** * Extracts tokens from the contract * * @param _tokenContract The address of ERC20 compatible token */ function retrieveTokens(address _tokenContract); } /** * @title Token retrieve * * Allows tokens to be retrieved from a contract * * #created 18/10/2017 * #author Frank Bonnet */ contract TokenRetriever is ITokenRetriever { /** * Extracts tokens from the contract * * @param _tokenContract The address of ERC20 compatible token */ function retrieveTokens(address _tokenContract) public { IToken tokenInstance = IToken(_tokenContract); uint tokenBalance = tokenInstance.balanceOf(this); if (tokenBalance > 0) { tokenInstance.transfer(msg.sender, tokenBalance); } } } /** * @title Token observer interface * * Allows a token smart-contract to notify observers * when tokens are received * * #created 09/10/2017 * #author Frank Bonnet */ contract ITokenObserver { /** * Called by the observed token smart-contract in order * to notify the token observer when tokens are received * * @param _from The address that the tokens where send from * @param _value The amount of tokens that was received */ function notifyTokensReceived(address _from, uint _value); } /** * @title Abstract token observer * * Allows observers to be notified by an observed token smart-contract * when tokens are received * * #created 09/10/2017 * #author Frank Bonnet */ contract TokenObserver is ITokenObserver { /** * Called by the observed token smart-contract in order * to notify the token observer when tokens are received * * @param _from The address that the tokens where send from * @param _value The amount of tokens that was received */ function notifyTokensReceived(address _from, uint _value) public { onTokensReceived(msg.sender, _from, _value); } /** * Event handler * * Called by `_token` when a token amount is received * * @param _token The token contract that received the transaction * @param _from The account or contract that send the transaction * @param _value The value of tokens that where received */ function onTokensReceived(address _token, address _from, uint _value) internal; } /** * @title ERC20 compatible token interface * * - Implements ERC 20 Token standard * - Implements short address attack fix * * #created 29/09/2017 * #author Frank Bonnet */ contract IToken { /** * Get the total supply of tokens * * @return The total supply */ function totalSupply() constant returns (uint); /** * Get balance of `_owner` * * @param _owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address _owner) constant returns (uint); /** * 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, uint _value) returns (bool); /** * 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, uint _value) returns (bool); /** * `msg.sender` approves `_spender` to spend `_value` tokens * * @param _spender The address of the account able to transfer the tokens * @param _value The amount of tokens to be approved for transfer * @return Whether the approval was successful or not */ function approve(address _spender, uint _value) returns (bool); /** * Get the amount of remaining tokens that `_spender` is allowed to spend from `_owner` * * @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 (uint); } /** * @title Dcorp Proxy * * Serves as a placeholder for the Dcorp funds, allowing the community the ability to vote on the acceptance of the VC platform, * and the transfer of token ownership. This mechanism is in place to allow the unlocking of the original DRP token, and to allow token * holders to convert to DRPU or DRPS. * This proxy is deployed upon receiving the Ether that is currently held by the DRP Crowdsale contract. * * #created 16/10/2017 * #author Frank Bonnet */ contract DcorpProxy is TokenObserver, TransferableOwnership, TokenRetriever { enum Stages { Deploying, Deployed, Executed } struct Balance { uint drps; uint drpu; uint index; } struct Vote { uint datetime; bool support; uint index; } struct Proposal { uint createdTimestamp; uint supportingWeight; uint rejectingWeight; mapping(address => Vote) votes; address[] voteIndex; uint index; } // State Stages private stage; // Settings uint private constant VOTING_DURATION = 7 days; uint private constant MIN_QUORUM = 5; // 5% // Alocated balances mapping (address => Balance) private allocated; address[] private allocatedIndex; // Proposals mapping(address => Proposal) private proposals; address[] private proposalIndex; // Tokens IToken private drpsToken; IToken private drpuToken; // Crowdsale address private drpCrowdsale; uint public drpCrowdsaleRecordedBalance; /** * Require that the proxy is in `_stage` */ modifier only_at_stage(Stages _stage) { require(stage == _stage); _; } /** * Require `_token` to be one of the drp tokens * * @param _token The address to test against */ modifier only_accepted_token(address _token) { require(_token == address(drpsToken) || _token == address(drpuToken)); _; } /** * Require that `_token` is not one of the drp tokens * * @param _token The address to test against */ modifier not_accepted_token(address _token) { require(_token != address(drpsToken) && _token != address(drpuToken)); _; } /** * Require that sender has more than zero tokens */ modifier only_token_holder() { require(allocated[msg.sender].drps > 0 || allocated[msg.sender].drpu > 0); _; } /** * Require `_proposedAddress` to have been proposed already * * @param _proposedAddress Address that needs to be proposed */ modifier only_proposed(address _proposedAddress) { require(isProposed(_proposedAddress)); _; } /** * Require that the voting period for the proposal has * not yet ended * * @param _proposedAddress Address that was proposed */ modifier only_during_voting_period(address _proposedAddress) { require(now <= proposals[_proposedAddress].createdTimestamp + VOTING_DURATION); _; } /** * Require that the voting period for the proposal has ended * * @param _proposedAddress Address that was proposed */ modifier only_after_voting_period(address _proposedAddress) { require(now > proposals[_proposedAddress].createdTimestamp + VOTING_DURATION); _; } /** * Require that the proposal is supported * * @param _proposedAddress Address that was proposed */ modifier only_when_supported(address _proposedAddress) { require(isSupported(_proposedAddress, false)); _; } /** * Construct the proxy * * @param _drpsToken The new security token * @param _drpuToken The new utility token * @param _drpCrowdsale Proxy accepts and requires ether from the crowdsale */ function DcorpProxy(address _drpsToken, address _drpuToken, address _drpCrowdsale) { drpsToken = IToken(_drpsToken); drpuToken = IToken(_drpuToken); drpCrowdsale = _drpCrowdsale; drpCrowdsaleRecordedBalance = _drpCrowdsale.balance; stage = Stages.Deploying; } /** * Returns whether the proxy is being deployed * * @return Whether the proxy is in the deploying stage */ function isDeploying() public constant returns (bool) { return stage == Stages.Deploying; } /** * Returns whether the proxy is deployed. The proxy is deployed * when it receives Ether from the drp crowdsale contract * * @return Whether the proxy is deployed */ function isDeployed() public constant returns (bool) { return stage == Stages.Deployed; } /** * Returns whether a proposal, and with it the proxy itself, is * already executed or not * * @return Whether the proxy is executed */ function isExecuted() public constant returns (bool) { return stage == Stages.Executed; } /** * Accept eth from the crowdsale while deploying */ function () public payable only_at_stage(Stages.Deploying) { require(msg.sender == drpCrowdsale); } /** * Deploy the proxy */ function deploy() only_owner only_at_stage(Stages.Deploying) { require(this.balance >= drpCrowdsaleRecordedBalance); stage = Stages.Deployed; } /** * Returns the combined total supply of all drp tokens * * @return The combined total drp supply */ function getTotalSupply() public constant returns (uint) { uint sum = 0; sum += drpsToken.totalSupply(); sum += drpuToken.totalSupply(); return sum; } /** * Returns true if `_owner` has a balance allocated * * @param _owner The account that the balance is allocated for * @return True if there is a balance that belongs to `_owner` */ function hasBalance(address _owner) public constant returns (bool) { return allocatedIndex.length > 0 && _owner == allocatedIndex[allocated[_owner].index]; } /** * Get the allocated drps token balance of `_owner` * * @param _token The address to test against * @param _owner The address from which the allocated token balance will be retrieved * @return The allocated drps token balance */ function balanceOf(address _token, address _owner) public constant returns (uint) { uint balance = 0; if (address(drpsToken) == _token) { balance = allocated[_owner].drps; } else if (address(drpuToken) == _token) { balance = allocated[_owner].drpu; } return balance; } /** * Returns true if `_proposedAddress` is already proposed * * @param _proposedAddress Address that was proposed * @return Whether `_proposedAddress` is already proposed */ function isProposed(address _proposedAddress) public constant returns (bool) { return proposalIndex.length > 0 && _proposedAddress == proposalIndex[proposals[_proposedAddress].index]; } /** * Returns the how many proposals where made * * @return The amount of proposals */ function getProposalCount() public constant returns (uint) { return proposalIndex.length; } /** * Propose the transfer token ownership and all funds to `_proposedAddress` * * @param _proposedAddress The proposed DCORP address */ function propose(address _proposedAddress) public only_owner only_at_stage(Stages.Deployed) { require(!isProposed(_proposedAddress)); // Add proposal Proposal storage p = proposals[_proposedAddress]; p.createdTimestamp = now; p.index = proposalIndex.push(_proposedAddress) - 1; } /** * Gets the voting duration, the amount of time voting * is allowed * * @return Voting duration */ function getVotingDuration() public constant returns (uint) { return VOTING_DURATION; } /** * Gets the number of votes towards a proposal * * @param _proposedAddress The proposed DCORP address * @return uint Vote count */ function getVoteCount(address _proposedAddress) public constant returns (uint) { return proposals[_proposedAddress].voteIndex.length; } /** * Returns true if `_account` has voted on the proposal * * @param _proposedAddress The proposed DCORP address * @param _account The key (address) that maps to the vote * @return bool Whether `_account` has voted on the proposal */ function hasVoted(address _proposedAddress, address _account) public constant returns (bool) { bool voted = false; if (getVoteCount(_proposedAddress) > 0) { Proposal storage p = proposals[_proposedAddress]; voted = p.voteIndex[p.votes[_account].index] == _account; } return voted; } /** * Returns true if `_account` supported the proposal and returns * false if `_account` is opposed to the proposal * * Does not check if `_account` had voted, use hasVoted() * * @param _proposedAddress The proposed DCORP address * @param _account The key (address) that maps to the vote * @return bool Supported */ function getVote(address _proposedAddress, address _account) public constant returns (bool) { return proposals[_proposedAddress].votes[_account].support; } /** * Allows a token holder to vote on a proposal * * @param _proposedAddress The proposed DCORP address * @param _support True if supported */ function vote(address _proposedAddress, bool _support) public only_at_stage(Stages.Deployed) only_proposed(_proposedAddress) only_during_voting_period(_proposedAddress) only_token_holder { Proposal storage p = proposals[_proposedAddress]; Balance storage b = allocated[msg.sender]; // Register vote if (!hasVoted(_proposedAddress, msg.sender)) { p.votes[msg.sender] = Vote( now, _support, p.voteIndex.push(msg.sender) - 1); // Register weight if (_support) { p.supportingWeight += b.drps + b.drpu; } else { p.rejectingWeight += b.drps + b.drpu; } } else { Vote storage v = p.votes[msg.sender]; if (v.support != _support) { // Register changed weight if (_support) { p.supportingWeight += b.drps + b.drpu; p.rejectingWeight -= b.drps + b.drpu; } else { p.rejectingWeight += b.drps + b.drpu; p.supportingWeight -= b.drps + b.drpu; } v.support = _support; v.datetime = now; } } } /** * Returns the current voting results for a proposal * * @param _proposedAddress The proposed DCORP address * @return supported, rejected */ function getVotingResult(address _proposedAddress) public constant returns (uint, uint) { Proposal storage p = proposals[_proposedAddress]; return (p.supportingWeight, p.rejectingWeight); } /** * Returns true if the proposal is supported * * @param _proposedAddress The proposed DCORP address * @param _strict If set to true the function requires that the voting period is ended * @return bool Supported */ function isSupported(address _proposedAddress, bool _strict) public constant returns (bool) { Proposal storage p = proposals[_proposedAddress]; bool supported = false; if (!_strict || now > p.createdTimestamp + VOTING_DURATION) { var (support, reject) = getVotingResult(_proposedAddress); supported = support > reject; if (supported) { supported = support + reject >= getTotalSupply() * MIN_QUORUM / 100; } } return supported; } /** * Executes the proposal * * Should only be called after the voting period and * when the proposal is supported * * @param _acceptedAddress The accepted DCORP address * @return bool Success */ function execute(address _acceptedAddress) public only_owner only_at_stage(Stages.Deployed) only_proposed(_acceptedAddress) only_after_voting_period(_acceptedAddress) only_when_supported(_acceptedAddress) { // Mark as executed stage = Stages.Executed; // Add accepted address as token owner IMultiOwned(drpsToken).addOwner(_acceptedAddress); IMultiOwned(drpuToken).addOwner(_acceptedAddress); // Remove self token as owner IMultiOwned(drpsToken).removeOwner(this); IMultiOwned(drpuToken).removeOwner(this); // Transfer Eth (safe because we don't know how much gas is used counting votes) uint balanceBefore = _acceptedAddress.balance; uint balanceToSend = this.balance; _acceptedAddress.transfer(balanceToSend); // Assert balances assert(balanceBefore + balanceToSend == _acceptedAddress.balance); assert(this.balance == 0); } /** * Event handler that initializes the token conversion * * Called by `_token` when a token amount is received on * the address of this token changer * * @param _token The token contract that received the transaction * @param _from The account or contract that send the transaction * @param _value The value of tokens that where received */ function onTokensReceived(address _token, address _from, uint _value) internal only_at_stage(Stages.Deployed) only_accepted_token(_token) { require(_token == msg.sender); // Allocate tokens if (!hasBalance(_from)) { allocated[_from] = Balance( 0, 0, allocatedIndex.push(_from) - 1); } Balance storage b = allocated[_from]; if (_token == address(drpsToken)) { b.drps += _value; } else { b.drpu += _value; } // Increase weight _adjustWeight(_from, _value, true); } /** * Withdraw DRPS tokens from the proxy and reduce the * owners weight accordingly * * @param _value The amount of DRPS tokens to withdraw */ function withdrawDRPS(uint _value) public { Balance storage b = allocated[msg.sender]; // Require sufficient balance require(b.drps >= _value); require(b.drps - _value <= b.drps); // Update balance b.drps -= _value; // Reduce weight _adjustWeight(msg.sender, _value, false); // Call external if (!drpsToken.transfer(msg.sender, _value)) { revert(); } } /** * Withdraw DRPU tokens from the proxy and reduce the * owners weight accordingly * * @param _value The amount of DRPU tokens to withdraw */ function withdrawDRPU(uint _value) public { Balance storage b = allocated[msg.sender]; // Require sufficient balance require(b.drpu >= _value); require(b.drpu - _value <= b.drpu); // Update balance b.drpu -= _value; // Reduce weight _adjustWeight(msg.sender, _value, false); // Call external if (!drpuToken.transfer(msg.sender, _value)) { revert(); } } /** * Failsafe mechanism * * Allows the owner to retrieve tokens (other than DRPS and DRPU tokens) from the contract that * might have been send there by accident * * @param _tokenContract The address of ERC20 compatible token */ function retrieveTokens(address _tokenContract) public only_owner not_accepted_token(_tokenContract) { super.retrieveTokens(_tokenContract); } /** * Adjust voting weight in ongoing proposals on which `_owner` * has already voted * * @param _owner The owner of the weight * @param _value The amount of weight that is adjusted * @param _increase Indicated whether the weight is increased or decreased */ function _adjustWeight(address _owner, uint _value, bool _increase) private { for (uint i = proposalIndex.length; i > 0; i--) { Proposal storage p = proposals[proposalIndex[i - 1]]; if (now > p.createdTimestamp + VOTING_DURATION) { break; // Last active proposal } if (hasVoted(proposalIndex[i - 1], _owner)) { if (p.votes[_owner].support) { if (_increase) { p.supportingWeight += _value; } else { p.supportingWeight -= _value; } } else { if (_increase) { p.rejectingWeight += _value; } else { p.rejectingWeight -= _value; } } } } } }
Returns whether a proposal, and with it the proxy itself, is already executed or not return Whether the proxy is executed/
function isExecuted() public constant returns (bool) { return stage == Stages.Executed; }
12,807,824
pragma solidity 0.4.23; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(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; } } contract ERC20 { function totalSupply()public view returns (uint total_Supply); function balanceOf(address who)public view returns (uint256); function allowance(address owner, address spender)public view returns (uint); function transferFrom(address from, address to, uint value)public returns (bool ok); function approve(address spender, uint value)public returns (bool ok); function transfer(address to, uint value)public returns (bool ok); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract Bitron is ERC20 { using SafeMath for uint256; // Name of the token string public constant name = "Bitron coin"; // Symbol of token string public constant symbol = "BTO"; uint8 public constant decimals = 18; uint public _totalsupply = 50000000 * 10 ** 18; // 50 Million total supply // muliplies dues to decimal precision address public owner; // Owner of this contract uint256 public _price_tokn; uint256 no_of_tokens; uint256 bonus_token; uint256 total_token; bool stopped = false; address ethFundMain = 0x1e6d1Fc2d934D2E4e2aE5e4882409C3fECD769dF; uint256 public postico_startdate; uint256 postico_enddate; uint256 maxCap_POSTICO; uint public priceFactor; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; uint bon; uint public bonus; enum Stages { NOTSTARTED, POSTICO, PAUSED, ENDED } Stages public stage; modifier atStage(Stages _stage) { require (stage == _stage); _; } modifier onlyOwner(){ require (msg.sender == owner); _; } constructor(uint256 EtherPriceFactor) public { require(EtherPriceFactor != 0); owner = msg.sender; balances[owner] = 30000000 * 10 **18; // 30 million to owner stage = Stages.NOTSTARTED; priceFactor = EtherPriceFactor; emit Transfer(0, owner, balances[owner]); } function setpricefactor(uint256 newPricefactor) external onlyOwner { priceFactor = newPricefactor; } function () public payable { require(stage != Stages.ENDED); require(!stopped && msg.sender != owner); no_of_tokens = ((msg.value).mul(priceFactor.mul(100))).div(_price_tokn); transferTokens(msg.sender,no_of_tokens); } function start_POSTICO() public onlyOwner atStage(Stages.NOTSTARTED) { stage = Stages.POSTICO; stopped = false; maxCap_POSTICO = 20000000 * 10 **18; // 20 million balances[address(this)] = maxCap_POSTICO; postico_startdate = now; postico_enddate = now + 90 days; //3 months _price_tokn = 5; // Price in Cents emit Transfer(0, address(this), maxCap_POSTICO); } // called by the owner, pause ICO function PauseICO() external onlyOwner { stopped = true; } // called by the owner , resumes ICO function ResumeICO() external onlyOwner { stopped = false; } function end_ICO() external onlyOwner { stage = Stages.ENDED; uint256 x = balances[address(this)]; balances[owner] = (balances[owner]).add(balances[address(this)]); balances[address(this)] = 0; emit Transfer(address(this), owner , x); } // what is the total supply of the ech tokens function totalSupply() public view returns (uint256 total_Supply) { total_Supply = _totalsupply; } // What is the balance of a particular account? function balanceOf(address _owner)public view returns (uint256 balance) { return balances[_owner]; } // Send _value amount of tokens from address _from to address _to // The transferFrom method is used for a withdraw workflow, allowing contracts to send // tokens on your behalf, for example to "deposit" to a contract address and/or to charge // fees in sub-currencies; the command should fail unless the _from account has // deliberately authorized the sender of the message via some mechanism; we propose // these standardized APIs for approval: function transferFrom( address _from, address _to, uint256 _amount )public returns (bool success) { require( _to != 0x0); require(balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount >= 0); balances[_from] = (balances[_from]).sub(_amount); allowed[_from][msg.sender] = (allowed[_from][msg.sender]).sub(_amount); balances[_to] = (balances[_to]).add(_amount); emit Transfer(_from, _to, _amount); return true; } // Allow _spender to withdraw from your account, multiple times, up to the _value amount. // If this function is called again it overwrites the current allowance with _value. function approve(address _spender, uint256 _amount)public returns (bool success) { require( _spender != 0x0); allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } function allowance(address _owner, address _spender)public view returns (uint256 remaining) { require( _owner != 0x0 && _spender !=0x0); return allowed[_owner][_spender]; } // Transfer the balance from owner's account to another account function transfer(address _to, uint256 _amount)public returns (bool success) { require( _to != 0x0); require(balances[msg.sender] >= _amount && _amount >= 0); balances[msg.sender] = (balances[msg.sender]).sub(_amount); balances[_to] = (balances[_to]).add(_amount); emit Transfer(msg.sender, _to, _amount); return true; } // Transfer the balance from owner's account to another account function transferTokens(address _to, uint256 _amount) private returns(bool success) { require( _to != 0x0); require(balances[address(this)] >= _amount && _amount > 0); balances[address(this)] = (balances[address(this)]).sub(_amount); balances[_to] = (balances[_to]).add(_amount); emit Transfer(address(this), _to, _amount); return true; } //In case the ownership needs to be transferred function transferOwnership(address newOwner) external onlyOwner { require( newOwner != 0x0); balances[newOwner] = (balances[newOwner]).add(balances[owner]); balances[owner] = 0; owner = newOwner; emit Transfer(msg.sender, newOwner, balances[newOwner]); } function drain() external onlyOwner { address myAddress = this; ethFundMain.transfer(myAddress.balance); } }
In case the ownership needs to be transferred
function transferOwnership(address newOwner) external onlyOwner { require( newOwner != 0x0); balances[newOwner] = (balances[newOwner]).add(balances[owner]); balances[owner] = 0; owner = newOwner; emit Transfer(msg.sender, newOwner, balances[newOwner]); }
6,036,400
./full_match/1/0x76bdA39E2b3f35c3fd6a6EC57c87B2657b500A0B/sources/contracts/token.sol
Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by decrementing then incrementing.
function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; _balances[to] += amount; } emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); }
9,667,763
// File: @openzeppelin/contracts/utils/Context.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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 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: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.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, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { 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"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { 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, reverting 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) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * 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); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @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); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); 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].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 virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); 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 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); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _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 virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(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); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(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 Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @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 to 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 { } } // File: @openzeppelin/contracts/token/ERC20/ERC20Capped.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Extension of {ERC20} that adds a cap to the supply of tokens. */ abstract contract ERC20Capped is ERC20 { using SafeMath for uint256; uint256 private _cap; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ constructor (uint256 cap_) internal { 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-_beforeTokenTransfer}. * * Requirements: * * - minted tokens must not cause the total supply to go over the cap. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) { // When minting tokens require(totalSupply().add(amount) <= cap(), "ERC20Capped: cap exceeded"); } } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), 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 { 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 virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/introspection/IERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, 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/token/ERC721/IERC721Metadata.sol pragma solidity >=0.6.2 <0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @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/token/ERC721/IERC721Enumerable.sol pragma solidity >=0.6.2 <0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @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/introspection/ERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity >=0.6.2 <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; // 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: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity >=0.6.0 <0.8.0; /** * @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: @openzeppelin/contracts/utils/EnumerableMap.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry 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. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element 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(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` 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); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // 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; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @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 _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @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 _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.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 { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_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 _tokenOwners.contains(tokenId); } /** * @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 = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `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); _holderTokens[to].add(tokenId); _tokenOwners.set(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 = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(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(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @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()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @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` cannot be the zero address. * - `to` cannot be the zero address. * * 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 { } } // File: contracts/LeasedEmblem.sol pragma solidity 0.7.6; contract LeasedEmblem is ERC721, Ownable { using SafeMath for uint256; address internal leaseExchange; struct Metadata { uint256 amount; address leasor; uint256 duration; uint256 tradeExpiry; uint256 leaseExpiry; bool isMining; } mapping(uint256 => Metadata) public metadata; mapping(address => uint256[]) internal leasedTokens; mapping(uint256 => uint256) internal leasedTokensIndex; mapping (uint256 => address) internal tokenLeasor; mapping (address => uint256) internal leasedTokensCount; uint256 highestId = 1; uint256 sixMonths = 15768000; constructor (string memory _name, string memory _symbol) public ERC721(_name, _symbol) { } function getNewId() public view returns(uint256) { return highestId; } function leasorOf(uint256 _tokenId) public view returns (address) { address owner = tokenLeasor[_tokenId]; require(owner != address(0)); return owner; } function balanceOfLeasor(address _leasor) public view returns (uint256) { require(_leasor != address(0)); return leasedTokensCount[_leasor]; } function tokenOfLeasorByIndex(address _leasor,uint256 _index) public view returns (uint256){ require(_index < balanceOfLeasor(_leasor)); return leasedTokens[_leasor][_index]; } function addTokenToLeasor(address _to, uint256 _tokenId) internal { require(tokenLeasor[_tokenId] == address(0)); tokenLeasor[_tokenId] = _to; leasedTokensCount[_to] = leasedTokensCount[_to].add(1); uint256 length = leasedTokens[_to].length; leasedTokens[_to].push(_tokenId); leasedTokensIndex[_tokenId] = length; } function removeTokenFromLeasor(address _from, uint256 _tokenId) internal { require(leasorOf(_tokenId) == _from); leasedTokensCount[_from] = leasedTokensCount[_from].sub(1); tokenLeasor[_tokenId] = address(0); uint256 tokenIndex = leasedTokensIndex[_tokenId]; uint256 lastTokenIndex = leasedTokens[_from].length.sub(1); uint256 lastToken = leasedTokens[_from][lastTokenIndex]; leasedTokens[_from][tokenIndex] = lastToken; leasedTokens[_from][lastTokenIndex] = 0; leasedTokens[_from].pop(); delete leasedTokensIndex[_tokenId]; leasedTokensIndex[lastToken] = tokenIndex; } function setLeaseExchange(address _leaseExchange) public onlyOwner { leaseExchange = _leaseExchange; } function totalAmount() external view returns (uint256) { uint256 amount = 0; for(uint256 i = 0; i < totalSupply(); i++){ amount += metadata[tokenByIndex(i)].amount; } return amount; } function setMetadata(uint256 _tokenId, uint256 amount, address leasor, uint256 duration,uint256 tradeExpiry, uint256 leaseExpiry) internal { require(_exists(_tokenId)); metadata[_tokenId]= Metadata(amount,leasor,duration,tradeExpiry,leaseExpiry,false); } function getMetadata(uint256 _tokenId) public view returns (uint256, address, uint256, uint256,uint256, bool) { require(_exists(_tokenId)); return ( metadata[_tokenId].amount, metadata[_tokenId].leasor, metadata[_tokenId].duration, metadata[_tokenId].tradeExpiry, metadata[_tokenId].leaseExpiry, metadata[_tokenId].isMining ); } function getAmountForUser(address owner) external view returns (uint256) { uint256 amount = 0; uint256 numTokens = balanceOf(owner); for(uint256 i = 0; i < numTokens; i++){ amount += metadata[tokenOfOwnerByIndex(owner,i)].amount; } return amount; } function getAmountForUserMining(address owner) external view returns (uint256) { uint256 amount = 0; uint256 numTokens = balanceOf(owner); for(uint256 i = 0; i < numTokens; i++){ if(metadata[tokenOfOwnerByIndex(owner,i)].isMining) { amount += metadata[tokenOfOwnerByIndex(owner,i)].amount; } } return amount; } function getAmount(uint256 _tokenId) public view returns (uint256) { require(_exists(_tokenId)); return metadata[_tokenId].amount; } function getTradeExpiry(uint256 _tokenId) public view returns (uint256) { require(_exists(_tokenId)); return metadata[_tokenId].tradeExpiry; } function getDuration(uint256 _tokenId) public view returns (uint256) { require(_exists(_tokenId)); return metadata[_tokenId].duration; } function getIsMining(uint256 _tokenId) public view returns (bool) { require(_exists(_tokenId)); return metadata[_tokenId].isMining; } function startMining(address _owner, uint256 _tokenId) public returns (bool) { require(msg.sender == leaseExchange); require(_exists(_tokenId)); require(ownerOf(_tokenId) == _owner); require(block.timestamp < metadata[_tokenId].tradeExpiry); require(metadata[_tokenId].isMining == false); Metadata storage m = metadata[_tokenId]; m.isMining = true; m.leaseExpiry = block.timestamp + m.duration; return true; } function canRetrieveEMB(address _leasor, uint256 _tokenId) public view returns (bool) { require(_exists(_tokenId)); require(metadata[_tokenId].leasor == _leasor); if(metadata[_tokenId].isMining == false) { return(block.timestamp > metadata[_tokenId].leaseExpiry); } else { return(block.timestamp > metadata[_tokenId].tradeExpiry); } } function endLease(address _leasee, uint256 _tokenId) public { require(msg.sender == leaseExchange); require(_exists(_tokenId)); require(ownerOf(_tokenId) == _leasee); require(block.timestamp > metadata[_tokenId].leaseExpiry); removeTokenFromLeasor(metadata[_tokenId].leasor, _tokenId); _burn(_tokenId); } function splitLEMB(uint256 _tokenId, uint256 amount) public { require(_exists(_tokenId)); require(ownerOf(_tokenId) == msg.sender); require(metadata[_tokenId].isMining == false); require(block.timestamp < metadata[_tokenId].tradeExpiry); require(amount < getAmount(_tokenId)); uint256 _newTokenId = getNewId(); Metadata storage m = metadata[_tokenId]; m.amount = m.amount - amount; _mint(msg.sender, _newTokenId); addTokenToLeasor(m.leasor, _newTokenId); setMetadata(_newTokenId, amount, m.leasor, m.duration,m.tradeExpiry, 0); highestId = highestId + 1; } function mintUniqueTokenTo(address _to, uint256 amount, address leasor, uint256 duration) public { require(msg.sender == leaseExchange); uint256 _tokenId = getNewId(); _mint(_to, _tokenId); addTokenToLeasor(leasor, _tokenId); uint256 tradeExpiry = block.timestamp + sixMonths; setMetadata(_tokenId, amount, leasor, duration,tradeExpiry, 0); highestId = highestId + 1; } function _burn(uint256 _tokenId) override internal { super._burn(_tokenId); delete metadata[_tokenId]; } modifier canTransfer(uint256 _tokenId) { require(_isApprovedOrOwner(msg.sender, _tokenId)); require(metadata[_tokenId].isMining == false); _; } } // File: contracts/Emblem.sol pragma solidity 0.7.6; contract Emblem is ERC20, ERC20Capped, Ownable { using SafeMath for uint256; bool internal useVanityFees; address internal leaseExchange; address internal vanityPurchaseReceiver; uint256 internal vanityPurchaseCost = 1 * (10 ** 8); //1 EMB bytes12[] internal allVanities; LeasedEmblem internal LEMB; mapping (bytes12 => address) public vanityAddresses; mapping (address => bytes12[]) public ownedVanities; mapping (address => mapping(bytes12 => uint256)) public ownedVanitiesIndex; mapping (bytes12 => uint256) internal allVanitiesIndex; mapping (address => mapping (bytes12 => address)) internal allowedVanities; mapping (bytes12 => uint256) internal vanityFees; event TransferVanity(address indexed from, address indexed to, bytes12 vanity); event ApprovedVanity(address indexed from, address indexed to, bytes12 vanity); event VanityPurchaseCost(uint256 cost); event VanityPurchased(address indexed from, bytes12 vanity); constructor(string memory _name, string memory _ticker, uint8 _decimal, uint256 _supply, address _wallet) public ERC20(_name, _ticker) ERC20Capped(_supply) { _mint(_wallet,_supply); _setupDecimals(_decimal); } function setLeaseExchange(address _leaseExchange) public onlyOwner { require(_leaseExchange != address(0), "Lease Exchange address cannot be set to 0"); leaseExchange = _leaseExchange; } function setVanityPurchaseCost(uint256 cost) public onlyOwner { require(cost > 0, "Vanity Purchase Cost must be > 0"); vanityPurchaseCost = cost; emit VanityPurchaseCost(cost); } function getVanityPurchaseCost() public view returns (uint256) { return vanityPurchaseCost; } function enableFees(bool enabled) public onlyOwner { useVanityFees = enabled; } function setVanityPurchaseReceiver(address _address) public onlyOwner { require(_address != address(0), "Vanity Purchase Receiver address cannot be set to 0"); vanityPurchaseReceiver = _address; } function setLEMB(address _lemb) public onlyOwner { require(_lemb != address(0), "Leased Emblem address cannot be set to 0"); LEMB = LeasedEmblem(_lemb); } function setVanityFee(bytes12 vanity, uint256 fee) public onlyOwner { vanityFees[vanity] = fee; } function getFee(bytes12 vanity) public view returns(uint256) { return vanityFees[vanity]; } function enabledVanityFee() public view returns(bool) { return useVanityFees; } function vanityAllowance(address _owner, bytes12 _vanity, address _spender) public view returns (bool) { return allowedVanities[_owner][_vanity] == _spender; } function getVanityOwner(bytes12 _vanity) public view returns (address) { return vanityAddresses[_vanity]; } function getAllVanities() public view returns (bytes12[] memory){ return allVanities; } function getMyVanities() public view returns (bytes12[] memory){ return ownedVanities[msg.sender]; } function approveVanity(address _spender, bytes12 _vanity) public returns (bool) { require(_spender != address(0), 'spender of vanity cannot be address zero'); require(vanityAddresses[_vanity] == msg.sender, 'transaction initiator must own the vanity'); allowedVanities[msg.sender][_vanity] = _spender; emit ApprovedVanity(msg.sender, _spender, _vanity); return true; } function clearVanityApproval(bytes12 _vanity) public returns (bool){ require(vanityAddresses[_vanity] == msg.sender,'transaction initiator must own the vanity'); delete allowedVanities[msg.sender][_vanity]; return true; } function transferVanity(bytes12 van, address newOwner) public returns (bool) { require(newOwner != address(0),'new vanity owner cannot be of address zero'); require(vanityAddresses[van] == msg.sender,'transaction initiator must own the vanity'); vanityAddresses[van] = newOwner; ownedVanities[newOwner].push(van); ownedVanitiesIndex[newOwner][van] = ownedVanities[newOwner].length.sub(1); uint256 vanityIndex = ownedVanitiesIndex[msg.sender][van]; uint256 lastVanityIndex = ownedVanities[msg.sender].length.sub(1); bytes12 lastVanity = ownedVanities[msg.sender][lastVanityIndex]; ownedVanities[msg.sender][vanityIndex] = lastVanity; ownedVanities[msg.sender].pop(); delete ownedVanitiesIndex[msg.sender][van]; ownedVanitiesIndex[msg.sender][lastVanity] = vanityIndex; emit TransferVanity(msg.sender, newOwner,van); return true; } function transferVanityFrom( address _from, address _to, bytes12 _vanity ) public returns (bool) { require(_to != address(0),'new vanity owner cannot be of address zero'); require(_from == vanityAddresses[_vanity],'the vanity being transferred must be owned by address _from'); require(msg.sender == allowedVanities[_from][_vanity],'transaction initiator must be approved to transfer vanity'); vanityAddresses[_vanity] = _to; ownedVanities[_to].push(_vanity); ownedVanitiesIndex[_to][_vanity] = ownedVanities[_to].length.sub(1); uint256 vanityIndex = ownedVanitiesIndex[_from][_vanity]; uint256 lastVanityIndex = ownedVanities[_from].length.sub(1); bytes12 lastVanity = ownedVanities[_from][lastVanityIndex]; ownedVanities[_from][vanityIndex] = lastVanity; ownedVanities[_from].pop(); delete ownedVanitiesIndex[_from][_vanity]; ownedVanitiesIndex[_from][lastVanity] = vanityIndex; emit TransferVanity(_from, _to,_vanity); return true; } function purchaseVanity(bytes12 van) public returns (bool) { require(vanityPurchaseReceiver != address(0),'vanity purchase receiver must be set'); require(vanityAddresses[van] == address(0),'vanity must not be purchased so far'); for(uint8 i = 0; i < 12; i++){ //Vanities must be lower case require((uint8(van[i]) >= 48 && uint8(van[i]) <= 57) || (uint8(van[i]) >= 65 && uint8(van[i]) <= 90)); } if(vanityPurchaseCost > 0) this.transferFrom(msg.sender,vanityPurchaseReceiver, vanityPurchaseCost); vanityAddresses[van] = msg.sender; ownedVanities[msg.sender].push(van); ownedVanitiesIndex[msg.sender][van] = ownedVanities[msg.sender].length.sub(1); allVanities.push(van); allVanitiesIndex[van] = allVanities.length.sub(1); emit VanityPurchased(msg.sender, van); return true; } //ensure the amount being transferred does not dip into EMB owned through leases. function canTransfer(address _account,uint256 _value) internal view returns (bool) { if(address(LEMB)!= address(0)){ require((_value.add(LEMB.getAmountForUserMining(_account)) <= balanceOf(_account)),'value being sent cannot dip into EMB acquired through leasing'); } return true; } function transfer(address _to, uint256 _value) public override returns (bool){ require(canTransfer(msg.sender,_value),'value must be transferrable by transaction initiator'); super.transfer(_to,_value); return true; } function multiTransfer(bytes27[] calldata _addressesAndAmounts) external returns (bool){ for (uint i = 0; i < _addressesAndAmounts.length; i++) { address to = address(uint216(_addressesAndAmounts[i] >> 56)); uint216 amount = uint216((_addressesAndAmounts[i] << 160) >> 160); transfer(to, amount); } return true; } function releaseEMB(address _from, address _to, uint256 _value) external returns (bool){ require(address(0) != leaseExchange, 'Lease Exchange must be activated'); require(msg.sender == leaseExchange, 'only the lease exchange can call this function'); transferFrom(_from,_to,_value); return true; } function transferFrom(address _from, address _to, uint256 _value) public override returns (bool){ if(msg.sender != leaseExchange) require(canTransfer(_from,_value),'value must be transfered from address _from'); super.transferFrom(_from,_to,_value); return true; } function decreaseAllowance(address _spender,uint256 _subtractedValue) public override returns (bool) { if(_spender == leaseExchange) { if(address(LEMB)!= address(0)){ require(allowance(msg.sender,_spender).sub(_subtractedValue) >= LEMB.getAmountForUserMining(msg.sender),'if spender is the lease exchange, the allowance must be greater than the amount the user is mining with LEMB'); } } super.decreaseAllowance(_spender,_subtractedValue); return true; } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20, ERC20Capped) { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) { // When minting tokens require(totalSupply().add(amount) <= cap(), "ERC20Capped: cap exceeded"); } } function approve(address _spender, uint256 _value) public override returns (bool) { if(_spender == leaseExchange){ if(address(LEMB)!= address(0)){ require(_value >= LEMB.getAmountForUserMining(msg.sender)); } } _approve(msg.sender, _spender, _value); return true; } }
ensure the amount being transferred does not dip into EMB owned through leases.
function canTransfer(address _account,uint256 _value) internal view returns (bool) { if(address(LEMB)!= address(0)){ require((_value.add(LEMB.getAmountForUserMining(_account)) <= balanceOf(_account)),'value being sent cannot dip into EMB acquired through leasing'); } return true; }
14,888,020
./partial_match/1/0x10eDf1Bec8072FCAA80F3Ce60120e2Ea934b05B7/sources/NyanV2.sol
Override ERC20 transfer function with transfer fee and LP algo. _recipient Recepient of the transfer. _amount Amount of tokens being transferred./ Check if the recipient is an address that has staked or holds LP require(ERC20(nyanV2LP).balanceOf(_recipient) == 0, "Recipient holds Nyan-2 liquidity."); Check if the recipient is an address that has staked or holds LP
function transfer(address _recipient, uint256 _amount) delegatedOnly public override returns(bool) { uint256 transferFee = _amount.div(100); if (hasExited[msg.sender]) { require(!isExitPeriod); } if((msg.sender == uniswapRouterV2) || (msg.sender == nyanV2LP)) { require(ERC20(nyanV2LP).balanceOf(_recipient) == 0, "Recipient holds Nyan-2 liquidity."); transferFee = 0; require(lastLPCount <= ERC20(nyanV2LP).totalSupply()); } if((_recipient == uniswapRouterV2) || (_recipient == nyanV2LP)) { require(ERC20(nyanV2LP).balanceOf(_recipient) == 0, "Recipient holds Nyan-2 liquidity."); transferFee = 0; } lastLPCount = ERC20(nyanV2LP).totalSupply(); emit transferFeeSubtracted(msg.sender, transferFee); return super.transfer(_recipient, _amount); }
4,259,260
// SPDX-License-Identifier: MIT /** * @authors: [*@epiqueras, @shotaronowhere] * @reviewers: [] * @auditors: [] * @bounties: [] * @deployments: [ ] */ pragma solidity ^0.4.24; /** * @title DualSortitionSumTreeFactory * @author Shotaro - <shawtarohgn@gmail.com> * @dev A factory of dual trees that keep track of staked values for sortition. */ library DualSortitionSumTreeFactory { /* Structs */ struct SortitionSumTree { uint K; // The maximum number of childs per node. // We use this to keep track of vacant positions in the tree after removing a leaf. This is for keeping the tree as balanced as possible without spending gas on moving nodes around. uint[] stack; uint[] nodes; // Two-way mapping of IDs to node indexes. Note that node index 0 is reserved for the root node, and means the ID does not have a node. mapping(bytes32 => uint) IDsToNodeIndexes; mapping(uint => bytes32) nodeIndexesToIDs; } /* Storage */ struct DualSortitionSumTrees { mapping(bytes32 => SortitionSumTree) sortitionSumDrawTrees; mapping(bytes32 => SortitionSumTree) sortitionSumSetTrees; uint threshold; uint lastThresholdUpdate; } /* Public */ /** * @dev Create a sortition sum tree at the specified key. * @param _key The key of the new tree. * @param _K_draw The number of children each node in the draw tree should have. * @param _K_set The number of children each node in the draw tree should have. */ function createTree(DualSortitionSumTrees storage self, bytes32 _key, uint _K_draw,uint _K_set) public { SortitionSumTree storage treeDraw = self.sortitionSumDrawTrees[_key]; SortitionSumTree storage treeSet = self.sortitionSumSetTrees[_key]; self.threshold = uint(-1); self.lastThresholdUpdate = 0; require(treeDraw.K == 0, "Tree already exists."); require(treeSet.K == 0, "Tree already exists."); require(_K_draw > 1, "K must be greater than one."); require(_K_set > 1, "K must be greater than one."); treeDraw.K = _K_draw; treeDraw.stack.length = 0; treeDraw.nodes.length = 0; treeDraw.nodes.push(0); treeSet.K = _K_set; treeSet.stack.length = 0; treeSet.nodes.length = 0; treeSet.nodes.push(0); } /** * @dev Set a value of a tree. * @param _key The key of the tree. * @param _value The new value. * @param _ID The ID of the value. * `O(log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function set(DualSortitionSumTrees storage self, bytes32 _key, uint _value, bytes32 _ID) public { SortitionSumTree storage treeSet = self.sortitionSumSetTrees[_key]; SortitionSumTree storage treeDraw = self.sortitionSumDrawTrees[_key]; if (self.lastThresholdUpdate > 2*(treeSet.nodes[0]+treeDraw.nodes[0]) || 2*self.lastThresholdUpdate < treeSet.nodes[0]+treeDraw.nodes[0]){ uint startIndex = 0; for (uint i = 0; i < treeSet.nodes.length; i++) { if ((treeSet.K * i) + 1 >= treeSet.nodes.length) { startIndex = i; if (i == 0) startIndex = 1; break; } } for (i = 0; i < treeDraw.nodes.length; i++) { if ((treeDraw.K * i) + 1 >= treeDraw.nodes.length) { if (i == 0){ startIndex = startIndex +1; } else{ startIndex = startIndex + i; } break; } } uint numTreeElements = treeDraw.nodes.length + treeSet.nodes.length - startIndex; self.threshold = (treeSet.nodes[0]+treeDraw.nodes[0])/numTreeElements; if(self.threshold == 0){ self.threshold = uint(-1); } self.lastThresholdUpdate = treeSet.nodes[0]+treeDraw.nodes[0]; } uint treeIndex = treeSet.IDsToNodeIndexes[_ID]; bool plusOrMinus; uint plusOrMinusValue; if (treeIndex != 0){//set tree if (_value == 0) { // Zero value. // Remove. // Remember value and set to 0. remove(treeSet, treeIndex, _value, _ID); } else if (_value != treeSet.nodes[treeIndex]) { // New, non zero value. // Set. if (_value > self.threshold){// SortionSumSetTree -> SortitionSumDrawTree // Remove from SortionSumSetTree // Remember value and set to 0. remove(treeSet, treeIndex, _value, _ID); insert(treeDraw, _value, _ID); } else { plusOrMinus = treeSet.nodes[treeIndex] <= _value; plusOrMinusValue = plusOrMinus ? _value - treeSet.nodes[treeIndex] : treeSet.nodes[treeIndex] - _value; treeSet.nodes[treeIndex] = _value; updateParents(treeSet, treeIndex, plusOrMinus, plusOrMinusValue); } } } else { // draw tree or DNE treeIndex = treeDraw.IDsToNodeIndexes[_ID]; if (treeIndex != 0){// draw tree if (_value == 0) { // Zero value. // Remove. // Remember value and set to 0. remove(treeDraw, treeIndex, _value, _ID); } else if (_value != treeDraw.nodes[treeIndex]) { // New, non zero value. // Set. if (_value < self.threshold){// SortionSumDrawTree -> SortitionSumSetTree // Remove from SortionSumSetTree remove(treeDraw, treeIndex, _value, _ID); insert(treeSet, _value, _ID); } else{ plusOrMinus = treeDraw.nodes[treeIndex] <= _value; plusOrMinusValue = plusOrMinus ? _value - treeDraw.nodes[treeIndex] : treeDraw.nodes[treeIndex] - _value; treeDraw.nodes[treeIndex] = _value; updateParents(treeDraw, treeIndex, plusOrMinus, plusOrMinusValue); } } } else{ // new _ID if (_value != 0) { // Non zero value. if (_value < self.threshold){ insert(treeSet, _value, _ID); } else { insert(treeDraw, _value, _ID); } } } } } function insert(SortitionSumTree storage tree, uint _value, bytes32 _ID) private { uint treeIndex; if (tree.stack.length == 0) { // No vacant spots. // Get the index and append the value. treeIndex = tree.nodes.length; tree.nodes.push(_value); // Potentially append a new node and make the parent a sum node. if (treeIndex != 1 && (treeIndex - 1) % tree.K == 0) { // Is first child. uint parentIndex = treeIndex / tree.K; bytes32 parentID = tree.nodeIndexesToIDs[parentIndex]; uint newIndex = treeIndex + 1; tree.nodes.push(tree.nodes[parentIndex]); delete tree.nodeIndexesToIDs[parentIndex]; tree.IDsToNodeIndexes[parentID] = newIndex; tree.nodeIndexesToIDs[newIndex] = parentID; } } else { // Some vacant spot. // Pop the stack and append the value. treeIndex = tree.stack[tree.stack.length - 1]; tree.stack.length--; tree.nodes[treeIndex] = _value; } // Add label. tree.IDsToNodeIndexes[_ID] = treeIndex; tree.nodeIndexesToIDs[treeIndex] = _ID; updateParents(tree, treeIndex, true, _value); } function remove(SortitionSumTree storage tree, uint _treeIndex, uint _value, bytes32 _ID) private { tree.nodes[_treeIndex] = 0; // Push to stack. tree.stack.push(_treeIndex); // Clear label. delete tree.IDsToNodeIndexes[_ID]; delete tree.nodeIndexesToIDs[_treeIndex]; updateParents(tree, _treeIndex, false, _value); } /* Public Views */ /** * @dev Query the leaves of a tree. Note that if `startIndex == 0`, the tree is empty and the root node will be returned. * @param _key The key of the tree to get the leaves from. * @param _cursor The pagination cursor. * @param _count The number of items to return. * @return startIndex The index at which leaves start. * @return values The values of the returned leaves. * @return hasMore Whether there are more for pagination. * `O(n)` where * `n` is the maximum number of nodes ever appended. */ function queryLeafs( DualSortitionSumTrees storage self, bytes32 _key, uint _cursor, uint _count, bool isSumTree ) public view returns(uint startIndex, uint[] values, bool hasMore) { SortitionSumTree storage tree = isSumTree ? self.sortitionSumSetTrees[_key] : self.sortitionSumDrawTrees[_key]; // Find the start index. for (uint i = 0; i < tree.nodes.length; i++) { if ((tree.K * i) + 1 >= tree.nodes.length) { startIndex = i; break; } } // Get the values. uint loopStartIndex = startIndex + _cursor; values = new uint[](loopStartIndex + _count > tree.nodes.length ? tree.nodes.length - loopStartIndex : _count); uint valuesIndex = 0; for (uint j = loopStartIndex; j < tree.nodes.length; j++) { if (valuesIndex < _count) { values[valuesIndex] = tree.nodes[j]; valuesIndex++; } else { hasMore = true; break; } } } /** * @dev Draw an ID from a tree using a number. Note that this function reverts if the sum of all values in the tree is 0. * @param _key The key of the tree. * @param _drawnNumber The drawn number. * @return ID The drawn ID. * `O(k * log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function draw(DualSortitionSumTrees storage self, bytes32 _key, uint _drawnNumber) public view returns(bytes32 ID) { SortitionSumTree storage tree = self.sortitionSumDrawTrees[_key]; SortitionSumTree storage treeSet = self.sortitionSumSetTrees[_key]; uint treeIndex = 0; uint currentDrawnNumber = _drawnNumber % (tree.nodes[0]+treeSet.nodes[0]); if(currentDrawnNumber > tree.nodes[0]){ currentDrawnNumber -= tree.nodes[0]; tree = treeSet; } while ((tree.K * treeIndex) + 1 < tree.nodes.length) // While it still has children. for (uint i = 1; i <= tree.K; i++) { // Loop over children. uint nodeIndex = (tree.K * treeIndex) + i; uint nodeValue = tree.nodes[nodeIndex]; if (currentDrawnNumber >= nodeValue) currentDrawnNumber -= nodeValue; // Go to the next child. else { // Pick this child. treeIndex = nodeIndex; break; } } ID = tree.nodeIndexesToIDs[treeIndex]; } /** @dev Gets a specified ID's associated value. * @param _key The key of the tree. * @param _ID The ID of the value. * @return value The associated value. */ function stakeOf(DualSortitionSumTrees storage self, bytes32 _key, bytes32 _ID) public view returns(uint value) { // check set first SortitionSumTree storage tree = self.sortitionSumSetTrees[_key]; uint treeIndex = tree.IDsToNodeIndexes[_ID]; if (treeIndex == 0) { // check draw second tree = self.sortitionSumDrawTrees[_key]; treeIndex = tree.IDsToNodeIndexes[_ID]; if (treeIndex == 0) value = 0; else value = tree.nodes[treeIndex]; } else { value = tree.nodes[treeIndex]; } } /* Private */ /** * @dev Update all the parents of a node. * @param _treeIndex The index of the node to start from. * @param _plusOrMinus Wether to add (true) or substract (false). * @param _value The value to add or substract. * `O(log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function updateParents(SortitionSumTree storage tree, uint _treeIndex, bool _plusOrMinus, uint _value) private { uint parentIndex = _treeIndex; while (parentIndex != 0) { parentIndex = (parentIndex - 1) / tree.K; tree.nodes[parentIndex] = _plusOrMinus ? tree.nodes[parentIndex] + _value : tree.nodes[parentIndex] - _value; } } }
Update all the parents of a node. _treeIndex The index of the node to start from. _plusOrMinus Wether to add (true) or substract (false). _value The value to add or substract. `O(log_k(n))` where `k` is the maximum number of childs per node in the tree, and `n` is the maximum number of nodes ever appended./
function updateParents(SortitionSumTree storage tree, uint _treeIndex, bool _plusOrMinus, uint _value) private { uint parentIndex = _treeIndex; while (parentIndex != 0) { parentIndex = (parentIndex - 1) / tree.K; tree.nodes[parentIndex] = _plusOrMinus ? tree.nodes[parentIndex] + _value : tree.nodes[parentIndex] - _value; } }
6,369,326
./full_match/1/0x967280A833bd1924C58c61C2d0dFe2D772c37178/sources/contracts/BewSwapImplement.sol
charge fee and transfer balance to to address
function swapExactTokensForETH( IUniRouter router, uint amountIn, uint amountOutMin, address[] calldata path, address payable to, uint deadline ) external nonReentrant { IERC20Upgradeable fromToken = IERC20Upgradeable(path[0]); fromToken.safeTransferFrom(msg.sender, address(this), amountIn); fromToken.safeIncreaseAllowance(address(router), amountIn); router.swapExactTokensForETHSupportingFeeOnTransferTokens(amountIn, amountOutMin, path, address(this), deadline); uint256 ethBalance = address(this).balance; require(ethBalance >= amountOutMin, "BewSwap: get less eth than expected"); uint256 feeAmount = (ethBalance * _feePct) / feePctScale; uint256 remainAmount = ethBalance - feeAmount; _safeTransferETH(to, remainAmount); if (feeAmount != 0) { _safeTransferETH(_feeAccount, feeAmount); emit FeeReceived(address(0), feeAmount); } }
3,083,691
pragma solidity 0.4.25; contract TokenConfig { string public constant NAME = "MANGO"; string public constant SYMBOL = "MANG"; uint8 public constant DECIMALS = 5; uint public constant DECIMALSFACTOR = 10 ** uint(DECIMALS); uint public constant TOTALSUPPLY = 10000000000 * DECIMALSFACTOR; } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on 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-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "can't mul"); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "can't sub with zero."); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "can't sub"); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "add overflow"); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "can't mod with zero"); return a % b; } } library SafeERC20 { using SafeMath for uint256; function safeTransfer(IERC20 token, address to, uint256 value) internal { require(token.transfer(to, value), "safeTransfer"); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { require(token.transferFrom(from, to, value), "safeTransferFrom"); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require((value == 0) || (token.allowance(msg.sender, spender) == 0), "safeApprove"); require(token.approve(spender, value), "safeApprove"); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); require(token.approve(spender, newAllowance), "safeIncreaseAllowance"); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); require(token.approve(spender, newAllowance), "safeDecreaseAllowance"); } } /** * @title Helps contracts guard against reentrancy attacks. * @author Remco Bloemen <remco@2π.com>, Eenae <alexey@mixbytes.io> * @dev If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor () internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @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() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "nonReentrant."); } } /** * @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 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, "only for owner."); _; } /** * @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 { require(newOwner != address(0), "address is zero."); owner = newOwner; emit OwnershipTransferred(owner, newOwner); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Paused(address account); event Unpaused(address account); bool private _paused; constructor() internal { _paused = false; } /** * @return true if the contract is paused, false otherwise. */ function paused() public view returns(bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "paused."); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Not paused."); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { _paused = false; emit Unpaused(msg.sender); } } /** * @title Crowdsale white list address */ contract Whitelist is Ownable { event WhitelistAdded(address addr); event WhitelistRemoved(address addr); mapping (address => bool) private _whitelist; /** * @dev add addresses to the whitelist * @param addrs addresses */ function addWhiteListAddr(address[] addrs) public { uint256 len = addrs.length; for (uint256 i = 0; i < len; i++) { _addAddressToWhitelist(addrs[i]); } } /** * @dev remove an address from the whitelist * @param addr address */ function removeWhiteListAddr(address addr) public { _removeAddressToWhitelist(addr); } /** * @dev getter to determine if address is in whitelist */ function isWhiteListAddr(address addr) public view returns (bool) { require(addr != address(0), "address is zero"); return _whitelist[addr]; } modifier onlyAuthorised(address beneficiary) { require(isWhiteListAddr(beneficiary),"Not authorised"); _; } /** * @dev add an address to the whitelist * @param addr address */ function _addAddressToWhitelist(address addr) internal onlyOwner { require(addr != address(0), "address is zero"); _whitelist[addr] = true; emit WhitelistAdded(addr); } /** * @dev remove an address from the whitelist * @param addr address */ function _removeAddressToWhitelist(address addr) internal onlyOwner { require(addr != address(0), "address is zero"); _whitelist[addr] = false; emit WhitelistRemoved(addr); } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overridden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropriate to concatenate * behavior. */ contract Crowdsale is TokenConfig, Pausable, ReentrancyGuard, Whitelist { using SafeMath for uint256; using SafeERC20 for IERC20; // The token being sold IERC20 private _token; // Address where funds are collected address private _wallet; // Address where funds are collected address private _tokenholder; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 private _rate; // Amount of contribution wei raised uint256 private _weiRaised; // Amount of token sold uint256 private _tokenSoldAmount; // Minimum contribution amount of fund uint256 private _minWeiAmount; // balances of user should be sent mapping (address => uint256) private _tokenBalances; // balances of user fund mapping (address => uint256) private _weiBalances; // ICO period timestamp uint256 private _openingTime; uint256 private _closingTime; // Amount of token hardcap uint256 private _hardcap; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokensPurchased( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); event TokensDelivered(address indexed beneficiary, uint256 amount); event RateChanged(uint256 rate); event MinWeiChanged(uint256 minWei); event PeriodChanged(uint256 open, uint256 close); event HardcapChanged(uint256 hardcap); constructor( uint256 rate, uint256 minWeiAmount, address wallet, address tokenholder, IERC20 token, uint256 hardcap, uint256 openingTime, uint256 closingTime ) public { require(rate > 0, "Rate is lower than zero."); require(wallet != address(0), "Wallet address is zero"); require(tokenholder != address(0), "Tokenholder address is zero"); require(token != address(0), "Token address is zero"); _rate = rate; _minWeiAmount = minWeiAmount; _wallet = wallet; _tokenholder = tokenholder; _token = token; _hardcap = hardcap; _openingTime = openingTime; _closingTime = closingTime; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** * Note that other contracts will transfer fund with a base gas stipend * of 2300, which is not enough to call buyTokens. Consider calling * buyTokens directly when purchasing tokens from a contract. */ function () external payable { buyTokens(msg.sender); } /** * @return the token being sold. */ function token() public view returns(IERC20) { return _token; } /** * @return token hardcap. */ function hardcap() public view returns(uint256) { return _hardcap; } /** * @return the address where funds are collected. */ function wallet() public view returns(address) { return _wallet; } /** * @return the number of token units a buyer gets per wei. */ function rate() public view returns(uint256) { return _rate; } /** * @return the amount of wei raised. */ function weiRaised() public view returns (uint256) { return _weiRaised; } /** * @return ICO opening time. */ function openingTime() public view returns (uint256) { return _openingTime; } /** * @return ICO closing time. */ function closingTime() public view returns (uint256) { return _closingTime; } /** * @return the amount of token raised. */ function tokenSoldAmount() public view returns (uint256) { return _tokenSoldAmount; } /** * @return the number of minimum amount buyer can fund. */ function minWeiAmount() public view returns(uint256) { return _minWeiAmount; } /** * @return is ICO period */ function isOpen() public view returns (bool) { // solium-disable-next-line security/no-block-members return now >= _openingTime && now <= _closingTime; } /** * @dev Gets the token balance of the specified address for deliver * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function tokenBalanceOf(address owner) public view returns (uint256) { return _tokenBalances[owner]; } /** * @dev Gets the ETH balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function weiBalanceOf(address owner) public view returns (uint256) { return _weiBalances[owner]; } function setRate(uint256 value) public onlyOwner { _rate = value; emit RateChanged(value); } function setMinWeiAmount(uint256 value) public onlyOwner { _minWeiAmount = value; emit MinWeiChanged(value); } function setPeriodTimestamp(uint256 open, uint256 close) public onlyOwner { _openingTime = open; _closingTime = close; emit PeriodChanged(open, close); } function setHardcap(uint256 value) public onlyOwner { _hardcap = value; emit HardcapChanged(value); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * This function has a non-reentrancy guard, so it shouldn't be called by * another `nonReentrant` function. * @param beneficiary Recipient of the token purchase */ function buyTokens(address beneficiary) public nonReentrant whenNotPaused payable { uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount); // Calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); require(_hardcap > _tokenSoldAmount.add(tokens), "Over hardcap"); // Update state _weiRaised = _weiRaised.add(weiAmount); _tokenSoldAmount = _tokenSoldAmount.add(tokens); _weiBalances[beneficiary] = _weiBalances[beneficiary].add(weiAmount); _tokenBalances[beneficiary] = _tokenBalances[beneficiary].add(tokens); emit TokensPurchased( msg.sender, beneficiary, weiAmount, tokens ); _forwardFunds(); } /** * @dev method that deliver token to user */ function deliverTokens(address[] users) public whenNotPaused onlyOwner { uint256 len = users.length; for (uint256 i = 0; i < len; i++) { address user = users[i]; uint256 tokenAmount = _tokenBalances[user]; _deliverTokens(user, tokenAmount); _tokenBalances[user] = 0; emit TokensDelivered(user, tokenAmount); } } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations. * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _preValidatePurchase( address beneficiary, uint256 weiAmount ) internal view onlyAuthorised(beneficiary) { require(weiAmount != 0, "Zero ETH"); require(weiAmount >= _minWeiAmount, "Must be equal or higher than minimum"); require(beneficiary != address(0), "Beneficiary address is zero"); require(isOpen(), "Sales is close"); } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param beneficiary Address performing the token purchase * @param tokenAmount Number of tokens to be emitted */ function _deliverTokens( address beneficiary, uint256 tokenAmount ) internal { _token.safeTransferFrom(_tokenholder, beneficiary, tokenAmount); } /** * @dev Override to extend the way in which ether is converted to tokens. * @param weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) { uint ethDecimals = 18; require(DECIMALS <= ethDecimals, ""); uint256 covertedTokens = weiAmount; if (DECIMALS != ethDecimals) { covertedTokens = weiAmount.div((10 ** uint256(ethDecimals - DECIMALS))); } return covertedTokens.mul(_rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { _wallet.transfer(msg.value); } }
return the number of minimum amount buyer can fund./
function minWeiAmount() public view returns(uint256) { return _minWeiAmount; }
6,439,331
// SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma experimental ABIEncoderV2; import "../GitRepository.sol"; import "../facets/GitRepositoryManagement.sol"; library LibGitFactory { struct Repository { bool isActive; string name; GitRepository location; } struct ActiveRepo { bool isActive; uint256 index; } struct Repositories { // mapps from a bytes32 to a repository contract // The bytes32 key is the hash over the owner's address and // the repository name mapping(bytes32 => Repository) repositoryList; // all address that own a repository with that name are in that array // if a user types in a repository name, we are able to show all the // users owning a repository with that name mapping(string => address[]) reposUserList; // mapping of user address to array of repository names // with this, we are able to type in a users address and list all his repositories mapping(address => string[]) usersRepoList; // array with repository names // possible use: array = [testRepo, testCcde, awesomeCode] // if a user types in test, we are able to show all repository names // starting with test string[] repositoryNames; // mapping from repository name to bool // if a repositry is created and that name has not been used yet, // the value is set to true and the name is added to repositoryNames // If a repository is created and the bollean is true, we don't // have to add it to the repositoryNames array mapping(string => ActiveRepo) activeRepository; } /** * This function is used to create a new repository. By providing a name, a new * GitRepository smart contract is deployed. * * @param self (Repositories) - The struct which contains all repository related inforation * @param key (bytes32) - Hash of user address and repository name * @param repoName (string) - The name of the new repository * @param newGitRepo (GitRepository) - Address of the newly deployed GitRepostory * @param owner (address) - Address of the owner of the new GitRepository */ function addRepository( Repositories storage self, bytes32 key, string memory repoName, GitRepository newGitRepo, address owner ) internal { self.repositoryList[key] = Repository({ isActive: true, name: repoName, location: newGitRepo }); // add the repositie's owner to the array self.reposUserList[repoName].push(owner); // and the repository name to the owner's array self.usersRepoList[owner].push(repoName); if (!self.activeRepository[repoName].isActive) { self.activeRepository[repoName].isActive = true; self.activeRepository[repoName].index = self.repositoryNames.length; self.repositoryNames.push(repoName); } } /** * Used to remove a repository from the internal 'database'. It takes the owner of the repository, the repository name, * the userIndex (describes at what position the owner's address is written in the reposUserList array) and the * repoIndex (describes at what position the repositories name is written in the usersRepoList array). It removes * the values from the arrays and reorganizes them. * * This function should be called only by GitRepository contracts. * * @param self (Repositories) - The struct which contains all repository related inforation * @param owner (address) - Owner of the repository to be removed * @param repoName (string) - The name of the repository to be removed * @param userIndex (uint256) - The position the of the repositories owner in the reposUserList * @param repoName (uint256) - The position of the repositories name in the usersRepoList */ function removeRepository( Repositories storage self, address owner, string memory repoName, uint256 userIndex, uint256 repoIndex ) internal { bytes32 key = getUserRepoNameHash(owner, repoName); // check if the key has already an active repository require(self.repositoryList[key].isActive, "Repository doesn't exist"); GitRepositoryManagement repoToDelete = GitRepositoryManagement(address(self.repositoryList[key].location)); uint _userIndex; uint _repoIndex; (, , , _userIndex, _repoIndex) = repoToDelete.getRepositoryInfo(); require(userIndex == _userIndex, "User Index value is not correct"); require(repoIndex == _repoIndex, "Repo Index value is not correct"); uint256 reposUserListLenght = self.reposUserList[repoName].length; if ((userIndex + 1) == reposUserListLenght) { // if the owner's address is at the end of the array, we just pop the value self.reposUserList[repoName].pop(); } else { // otherwise we remove it and move the last entry to that location. delete self.reposUserList[repoName][userIndex]; // address of the owner of the moving contract address lastEntry = self.reposUserList[repoName][reposUserListLenght - 1]; self.reposUserList[repoName].pop(); self.reposUserList[repoName][userIndex] = lastEntry; // We also have to update the underlying repository value get the key for the moved repository bytes32 key2 = getUserRepoNameHash(lastEntry, repoName); // we require here the GitRepositoryManagement contract with the address of the GitRepository in order // to call the updateUserIndex function throught GitRepositry's fallback function GitRepositoryManagement movedGitRepo = GitRepositoryManagement(address(self.repositoryList[key2].location)); // and update the user index movedGitRepo.updateUserIndex(userIndex); } uint256 usersRepoListLength = self.usersRepoList[owner].length; if ((repoIndex + 1) == usersRepoListLength) { self.usersRepoList[owner].pop(); } else { // otherwise we remove it and move the last entry to that location. delete self.usersRepoList[owner][repoIndex]; string memory lastEntry = self.usersRepoList[owner][usersRepoListLength - 1]; self.usersRepoList[owner].pop(); self.usersRepoList[owner][repoIndex] = lastEntry; // We also have to update the underlying repository value get the key for the moved repository bytes32 key2 = getUserRepoNameHash(owner, lastEntry); // we require here the GitRepositoryManagement contract with the address of the GitRepository in order // to call the updateRepoIndex function throught GitRepositry's fallback function GitRepositoryManagement movedGitRepo = GitRepositoryManagement(address(self.repositoryList[key2].location)); // and update the user index movedGitRepo.updateRepoIndex(repoIndex); } // in case there are no more users having a repositry with this name, we set the name to false if (self.reposUserList[repoName].length == 0) { self.activeRepository[repoName].isActive = false; uint256 index = self.activeRepository[repoName].index; if (index != self.repositoryNames.length - 1) { delete self.repositoryNames[index]; string memory name = self.repositoryNames[self.repositoryNames.length - 1]; self.repositoryNames[index] = name; self.activeRepository[name].index = index; } self.repositoryNames.pop(); } // we still need to deactive the repo and update the entries for the moved repo self.repositoryList[key].isActive = false; } /** * Returns the keccak256 hash generated over a user's address and a repository name. * * @param _owner (address) - The address of a repository owner * @param _repoName (string) - The name of a repository * * @return (bytes32) - The keccak256(_owner, _repoName) hash */ function getUserRepoNameHash(address _owner, string memory _repoName) pure internal returns (bytes32) { return keccak256(abi.encode(_owner, _repoName)); } function getRepository(Repositories storage self, bytes32 location) view internal returns (Repository memory) { return self.repositoryList[location]; } /** * Returns all user addresses owning a repository by the given name. * * @param _repoName (string) - Repository name * * @return (address[]) - An array containing all owner addresses having a repository with the given name */ function getRepositoriesUserList(Repositories storage self, string memory _repoName) view internal returns (address[] memory) { return self.reposUserList[_repoName]; } }
Returns the keccak256 hash generated over a user's address and a repository name. _owner (address) - The address of a repository owner _repoName (string) - The name of a repository return (bytes32) - The keccak256(_owner, _repoName) hash/
function getUserRepoNameHash(address _owner, string memory _repoName) pure internal returns (bytes32) { return keccak256(abi.encode(_owner, _repoName)); }
12,763,610
pragma solidity >=0.4.22 <0.5.0; /** * Allow contracts to be managable to upgrade contracts as well as doing other admin actions, etc. * * Overall speaking, manager should have the capability to: * 1, halt the contracts for a while, to be ready for any unexpected emergency * 2, restart the halted contracts to return to normal * 3, change the addresses of all children contracts (for upgradation) * 4, change the manager address itself for transferring the responsibility to the next one */ contract managed { ///////////////////////////////////// // running and functions // ///////////////////////////////////// /** * Stoppable. * only manager can halt/start the contract */ bool public running = true; modifier isRunning { require(running); _; } // "stop" conflicts with the assembly. use "pause". // Warning: Variable is shadowed in inline assembly by an instruction of the same name // use only one function instead of two (pause/unpause, start/stop) to reduce the code size. function setRunning(bool _running) onlyManager public { running = _running; } ///////////////////////////////////// // manager and functions // ///////////////////////////////////// address public manager; // who have the permission to maintain the system event ManagerChanged(address indexed _from, address indexed _to); /** * setup the manager to the deployer while deployed * could be possible to be overriden */ constructor() public { manager = msg.sender; // this should be the factory address } /** * The modifier for decorating functions. */ modifier onlyManager { //require(msg.sender == manager, MANAGED_REQUIRE_ONLY_MANAGER); require(msg.sender == manager, "only manager"); _; } /** * only manager can change manager * * this isRunning is not meaningful but only for test case to verify it works. */ function changeManager(address _newManager) isRunning public onlyManager { // code optimization to reduce code size emit ManagerChanged(manager, _newManager); manager = _newManager; } }
"stop" conflicts with the assembly. use "pause". Warning: Variable is shadowed in inline assembly by an instruction of the same name use only one function instead of two (pause/unpause, start/stop) to reduce the code size.
function setRunning(bool _running) onlyManager public { running = _running; } event ManagerChanged(address indexed _from, address indexed _to);
12,602,721
// SPDX-License-Identifier: MIT pragma solidity ^0.8.3; pragma experimental ABIEncoderV2; //Openzeppelin import "./openzeppelin-solidity/contracts/SafeMath.sol"; import "./openzeppelin-solidity/contracts/Ownable.sol"; import "./openzeppelin-solidity/contracts/ERC20/SafeERC20.sol"; import "./openzeppelin-solidity/contracts/ERC1155/IERC1155.sol"; import "./openzeppelin-solidity/contracts/ERC1155/ERC1155Holder.sol"; //Inheritance import './interfaces/IMarketplace.sol'; contract Marketplace is IMarketplace, ERC1155Holder, Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Max fee of 10%. uint256 public MAX_TRANSACTION_FEE = 1000; // Denominated by 10000. uint256 public transactionFee = 200; IERC1155 public immutable priceManager; IERC20 public immutable TGEN; address public immutable xTGEN; // Starts at index 1; increases without bounds. uint256 public numberOfMarketplaceListings; // Starts at index 1; increases without bounds. mapping (uint256 => MarketplaceListing) public marketplaceListings; // NFT ID => listing index. // Returns 0 if the NFT is listed for sale. mapping (uint256 => uint256) public listingIndexes; // User address => NFT ID => listing index. // Returns 0 if user is not selling the NFT ID. mapping (address => mapping (uint256 => uint256)) public userToID; constructor(address _priceManager, address _TGEN, address _xTGEN) Ownable() { require(_priceManager != address(0), "Marketplace: invalid address for PriceManager."); require(_TGEN != address(0), "Marketplace: invalid address for TGEN."); require(_xTGEN != address(0), "Marketplace: invalid address for xTGEN."); priceManager = IERC1155(_priceManager); TGEN = IERC20(_TGEN); xTGEN = _xTGEN; } /* ========== VIEWS ========== */ /** * @dev Given an NFT ID, returns its listing index. * @notice Returns 0 if the NFT with the given ID is not listed. * @param _ID ID of the ExecutionPrice NFT. * @return uint256 Listing index of the ExecutionPrice NFT. */ function getListingIndex(uint256 _ID) external view override returns (uint256) { return listingIndexes[_ID]; } /** * @dev Given the index of a marketplace listing, returns the listing's data * @param _index Index of the marketplace listing * @return (address, bool, uint256, uint256) Address of the seller, whether the listing exists, NFT ID, and the price (in TGEN). */ function getMarketplaceListing(uint256 _index) external view override indexInRange(_index) returns (address, bool, uint256, uint256) { MarketplaceListing memory listing = marketplaceListings[_index]; return (listing.seller, listing.exists, listing.ID, listing.price); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @dev Purchases the ExecutionPrice NFT at the given listing index. * @param _index Index of the marketplace listing. */ function purchase(uint256 _index) external override indexInRange(_index) { require(marketplaceListings[_index].exists, "Marketplace: listing does not exist."); require(msg.sender != marketplaceListings[_index].seller, "Marketplace: Cannot buy your own position."); uint256 price = marketplaceListings[_index].price; TGEN.safeTransferFrom(msg.sender, address(this), price); // Transfer TGEN to seller. TGEN.safeTransfer(marketplaceListings[_index].seller, price.mul(10000 - transactionFee).div(10000)); // Transfer TGEN to xTGEN contract. TGEN.safeTransfer(xTGEN, price.mul(transactionFee).div(10000)); // Transfer NFT to buyer. priceManager.setApprovalForAll(msg.sender, true); priceManager.safeTransferFrom(address(this), msg.sender, marketplaceListings[_index].ID, 1, ""); // Update state variables. _removeListing(marketplaceListings[_index].seller, _index); emit Purchased(msg.sender, _index, marketplaceListings[_index].ID, marketplaceListings[_index].price); } /** * @dev Creates a new marketplace listing with the given price and NFT ID. * @param _ID ID of the ExecutionPrice NFT. * @param _price TGEN price of the NFT. */ function createListing(uint256 _ID, uint256 _price) external override { require(userToID[msg.sender][_ID] == 0, "Marketplace: Already have a marketplace listing for this NFT."); require(_price > 0, "Marketplace: Price must be greater than 0"); require(priceManager.balanceOf(msg.sender, _ID) == 1, "Marketplace: don't own NFT."); numberOfMarketplaceListings = numberOfMarketplaceListings.add(1); listingIndexes[_ID] = numberOfMarketplaceListings; userToID[msg.sender][_ID] = numberOfMarketplaceListings; marketplaceListings[numberOfMarketplaceListings] = MarketplaceListing(msg.sender, true, _ID, _price); // Transfer NFT to marketplace. priceManager.safeTransferFrom(msg.sender, address(this), _ID, 1, ""); emit CreatedListing(msg.sender, numberOfMarketplaceListings, _ID, _price); } /** * @dev Removes the marketplace listing at the given index. * @param _index Index of the marketplace listing. */ function removeListing(uint256 _index) external override indexInRange(_index) onlySeller(_index) { _removeListing(msg.sender, _index); // Transfer NFT to seller. priceManager.setApprovalForAll(msg.sender, true); priceManager.safeTransferFrom(address(this), msg.sender, marketplaceListings[_index].ID, 1, ""); emit RemovedListing(msg.sender, _index); } /** * @dev Updates the price of the given marketplace listing. * @param _index Index of the marketplace listing. * @param _newPrice TGEN price of the NFT. */ function updatePrice(uint256 _index, uint256 _newPrice) external override indexInRange(_index) onlySeller(_index) { require(_newPrice > 0, "Marketplace: New price must be greater than 0"); marketplaceListings[_index].price = _newPrice; emit UpdatedPrice(msg.sender, _index, _newPrice); } /* ========== RESTRICTED FUNCTIONS ========== */ /** * @dev Updates the transaction fee. * @notice This function is meant to be called by the contract deployer. * @param _newFee The new transaction fee. */ function setTransactionFee(uint256 _newFee) external onlyOwner { require(_newFee >= 0, "Marketplace: new fee must be positive."); require(_newFee <= MAX_TRANSACTION_FEE, "Marketplace: new fee is too high."); transactionFee = _newFee; emit UpdatedTransactionFee(_newFee); } /* ========== INTERNAL FUNCTIONS ========== */ /** * @dev Sets the marketplace listing's 'exists' variable to false. * @param _user Address of the seller. * @param _index Index of the marketplace listing. */ function _removeListing(address _user, uint256 _index) internal { marketplaceListings[_index].exists = false; userToID[_user][marketplaceListings[_index].ID] = 0; } /* ========== MODIFIERS ========== */ modifier indexInRange(uint256 index) { require(index > 0 && index <= numberOfMarketplaceListings, "Marketplace: Index out of range"); _; } modifier onlySeller(uint256 index) { require(msg.sender == marketplaceListings[index].seller, "Marketplace: Only the seller can call this function"); _; } /* ========== EVENTS ========== */ event UpdatedTransactionFee(uint256 newFee); }
Updates the transaction fee. This function is meant to be called by the contract deployer. _newFee The new transaction fee./
function setTransactionFee(uint256 _newFee) external onlyOwner { require(_newFee >= 0, "Marketplace: new fee must be positive."); require(_newFee <= MAX_TRANSACTION_FEE, "Marketplace: new fee is too high."); transactionFee = _newFee; emit UpdatedTransactionFee(_newFee); }
6,486,521
// SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/math/FixedPoint.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/InputHelpers.sol"; import "@balancer-labs/v2-pool-utils/contracts/BaseMinimalSwapInfoPool.sol"; import "./WeightedMath.sol"; import "./WeightedPoolUserDataHelpers.sol"; /** * @dev Base class for WeightedPools containing swap, join and exit logic, but leaving storage and management of * the weights to subclasses. Derived contracts can choose to make weights immutable, mutable, or even dynamic * based on local or external logic. */ abstract contract BaseWeightedPool is BaseMinimalSwapInfoPool, WeightedMath { using FixedPoint for uint256; using WeightedPoolUserDataHelpers for bytes; uint256 private _lastInvariant; // For backwards compatibility, make sure new join and exit kinds are added at the end of the enum. enum JoinKind { INIT, EXACT_TOKENS_IN_FOR_BPT_OUT, TOKEN_IN_FOR_EXACT_BPT_OUT, ALL_TOKENS_IN_FOR_EXACT_BPT_OUT } enum ExitKind { EXACT_BPT_IN_FOR_ONE_TOKEN_OUT, EXACT_BPT_IN_FOR_TOKENS_OUT, BPT_IN_FOR_EXACT_TOKENS_OUT, MANAGEMENT_FEE_TOKENS_OUT // for InvestmentPool } constructor( IVault vault, string memory name, string memory symbol, IERC20[] memory tokens, address[] memory assetManagers, uint256 swapFeePercentage, uint256 pauseWindowDuration, uint256 bufferPeriodDuration, address owner ) BasePool( vault, // Given BaseMinimalSwapInfoPool supports both of these specializations, and this Pool never registers or // deregisters any tokens after construction, picking Two Token when the Pool only has two tokens is free // gas savings. tokens.length == 2 ? IVault.PoolSpecialization.TWO_TOKEN : IVault.PoolSpecialization.MINIMAL_SWAP_INFO, name, symbol, tokens, assetManagers, swapFeePercentage, pauseWindowDuration, bufferPeriodDuration, owner ) { // solhint-disable-previous-line no-empty-blocks } // Virtual functions /** * @dev Returns the normalized weight of `token`. Weights are fixed point numbers that sum to FixedPoint.ONE. */ function _getNormalizedWeight(IERC20 token) internal view virtual returns (uint256); /** * @dev Returns all normalized weights, in the same order as the Pool's tokens. */ function _getNormalizedWeights() internal view virtual returns (uint256[] memory); /** * @dev Returns all normalized weights, in the same order as the Pool's tokens, along with the index of the token * with the highest weight. */ function _getNormalizedWeightsAndMaxWeightIndex() internal view virtual returns (uint256[] memory, uint256); function getLastInvariant() public view virtual returns (uint256) { return _lastInvariant; } /** * @dev Returns the current value of the invariant. */ function getInvariant() public view returns (uint256) { (, uint256[] memory balances, ) = getVault().getPoolTokens(getPoolId()); // Since the Pool hooks always work with upscaled balances, we manually // upscale here for consistency _upscaleArray(balances, _scalingFactors()); (uint256[] memory normalizedWeights, ) = _getNormalizedWeightsAndMaxWeightIndex(); return WeightedMath._calculateInvariant(normalizedWeights, balances); } function getNormalizedWeights() external view returns (uint256[] memory) { return _getNormalizedWeights(); } // Base Pool handlers // Swap function _onSwapGivenIn( SwapRequest memory swapRequest, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut ) internal view virtual override whenNotPaused returns (uint256) { // Swaps are disabled while the contract is paused. return WeightedMath._calcOutGivenIn( currentBalanceTokenIn, _getNormalizedWeight(swapRequest.tokenIn), currentBalanceTokenOut, _getNormalizedWeight(swapRequest.tokenOut), swapRequest.amount ); } function _onSwapGivenOut( SwapRequest memory swapRequest, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut ) internal view virtual override whenNotPaused returns (uint256) { // Swaps are disabled while the contract is paused. return WeightedMath._calcInGivenOut( currentBalanceTokenIn, _getNormalizedWeight(swapRequest.tokenIn), currentBalanceTokenOut, _getNormalizedWeight(swapRequest.tokenOut), swapRequest.amount ); } // Initialize function _onInitializePool( bytes32, address, address, uint256[] memory scalingFactors, bytes memory userData ) internal virtual override whenNotPaused returns (uint256, uint256[] memory) { // It would be strange for the Pool to be paused before it is initialized, but for consistency we prevent // initialization in this case. JoinKind kind = userData.joinKind(); _require(kind == JoinKind.INIT, Errors.UNINITIALIZED); uint256[] memory amountsIn = userData.initialAmountsIn(); InputHelpers.ensureInputLengthMatch(_getTotalTokens(), amountsIn.length); _upscaleArray(amountsIn, scalingFactors); (uint256[] memory normalizedWeights, ) = _getNormalizedWeightsAndMaxWeightIndex(); uint256 invariantAfterJoin = WeightedMath._calculateInvariant(normalizedWeights, amountsIn); // Set the initial BPT to the value of the invariant times the number of tokens. This makes BPT supply more // consistent in Pools with similar compositions but different number of tokens. uint256 bptAmountOut = Math.mul(invariantAfterJoin, _getTotalTokens()); _lastInvariant = invariantAfterJoin; return (bptAmountOut, amountsIn); } // Join function _onJoinPool( bytes32, address, address, uint256[] memory balances, uint256, uint256 protocolSwapFeePercentage, uint256[] memory scalingFactors, bytes memory userData ) internal virtual override whenNotPaused returns ( uint256, uint256[] memory, uint256[] memory ) { // All joins are disabled while the contract is paused. (uint256[] memory normalizedWeights, uint256 maxWeightTokenIndex) = _getNormalizedWeightsAndMaxWeightIndex(); // Due protocol swap fee amounts are computed by measuring the growth of the invariant between the previous join // or exit event and now - the invariant's growth is due exclusively to swap fees. This avoids spending gas // computing them on each individual swap uint256 invariantBeforeJoin = WeightedMath._calculateInvariant(normalizedWeights, balances); uint256[] memory dueProtocolFeeAmounts = _getDueProtocolFeeAmounts( balances, normalizedWeights, maxWeightTokenIndex, _lastInvariant, invariantBeforeJoin, protocolSwapFeePercentage ); // Update current balances by subtracting the protocol fee amounts _mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub); (uint256 bptAmountOut, uint256[] memory amountsIn) = _doJoin( balances, normalizedWeights, scalingFactors, userData ); // Update the invariant with the balances the Pool will have after the join, in order to compute the // protocol swap fee amounts due in future joins and exits. _lastInvariant = _invariantAfterJoin(balances, amountsIn, normalizedWeights); return (bptAmountOut, amountsIn, dueProtocolFeeAmounts); } function _doJoin( uint256[] memory balances, uint256[] memory normalizedWeights, uint256[] memory scalingFactors, bytes memory userData ) internal returns (uint256, uint256[] memory) { JoinKind kind = userData.joinKind(); if (kind == JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT) { return _joinExactTokensInForBPTOut(balances, normalizedWeights, scalingFactors, userData); } else if (kind == JoinKind.TOKEN_IN_FOR_EXACT_BPT_OUT) { return _joinTokenInForExactBPTOut(balances, normalizedWeights, userData); } else if (kind == JoinKind.ALL_TOKENS_IN_FOR_EXACT_BPT_OUT) { return _joinAllTokensInForExactBPTOut(balances, userData); } else { _revert(Errors.UNHANDLED_JOIN_KIND); } } function _joinExactTokensInForBPTOut( uint256[] memory balances, uint256[] memory normalizedWeights, uint256[] memory scalingFactors, bytes memory userData ) private returns (uint256, uint256[] memory) { (uint256[] memory amountsIn, uint256 minBPTAmountOut) = userData.exactTokensInForBptOut(); InputHelpers.ensureInputLengthMatch(_getTotalTokens(), amountsIn.length); _upscaleArray(amountsIn, scalingFactors); (uint256 bptAmountOut, uint256[] memory swapFees) = WeightedMath._calcBptOutGivenExactTokensIn( balances, normalizedWeights, amountsIn, totalSupply(), getSwapFeePercentage() ); // Note that swapFees is already upscaled _processSwapFeeAmounts(swapFees); _require(bptAmountOut >= minBPTAmountOut, Errors.BPT_OUT_MIN_AMOUNT); return (bptAmountOut, amountsIn); } function _joinTokenInForExactBPTOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private returns (uint256, uint256[] memory) { (uint256 bptAmountOut, uint256 tokenIndex) = userData.tokenInForExactBptOut(); // Note that there is no maximum amountIn parameter: this is handled by `IVault.joinPool`. _require(tokenIndex < _getTotalTokens(), Errors.OUT_OF_BOUNDS); (uint256 amountIn, uint256 swapFee) = WeightedMath._calcTokenInGivenExactBptOut( balances[tokenIndex], normalizedWeights[tokenIndex], bptAmountOut, totalSupply(), getSwapFeePercentage() ); // Note that swapFee is already upscaled _processSwapFeeAmount(tokenIndex, swapFee); // We join in a single token, so we initialize amountsIn with zeros uint256[] memory amountsIn = new uint256[](_getTotalTokens()); // And then assign the result to the selected token amountsIn[tokenIndex] = amountIn; return (bptAmountOut, amountsIn); } function _joinAllTokensInForExactBPTOut(uint256[] memory balances, bytes memory userData) private view returns (uint256, uint256[] memory) { uint256 bptAmountOut = userData.allTokensInForExactBptOut(); // Note that there is no maximum amountsIn parameter: this is handled by `IVault.joinPool`. uint256[] memory amountsIn = WeightedMath._calcAllTokensInGivenExactBptOut( balances, bptAmountOut, totalSupply() ); return (bptAmountOut, amountsIn); } // Exit function _onExitPool( bytes32, address, address, uint256[] memory balances, uint256, uint256 protocolSwapFeePercentage, uint256[] memory scalingFactors, bytes memory userData ) internal virtual override returns ( uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts ) { (uint256[] memory normalizedWeights, uint256 maxWeightTokenIndex) = _getNormalizedWeightsAndMaxWeightIndex(); // Exits are not completely disabled while the contract is paused: proportional exits (exact BPT in for tokens // out) remain functional. if (_isNotPaused()) { // Due protocol swap fee amounts are computed by measuring the growth of the invariant between the previous // join or exit event and now - the invariant's growth is due exclusively to swap fees. This avoids // spending gas calculating the fees on each individual swap. uint256 invariantBeforeExit = WeightedMath._calculateInvariant(normalizedWeights, balances); dueProtocolFeeAmounts = _getDueProtocolFeeAmounts( balances, normalizedWeights, maxWeightTokenIndex, _lastInvariant, invariantBeforeExit, protocolSwapFeePercentage ); // Update current balances by subtracting the protocol fee amounts _mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub); } else { // If the contract is paused, swap protocol fee amounts are not charged to avoid extra calculations and // reduce the potential for errors. dueProtocolFeeAmounts = new uint256[](_getTotalTokens()); } (bptAmountIn, amountsOut) = _doExit(balances, normalizedWeights, scalingFactors, userData); // Update the invariant with the balances the Pool will have after the exit, in order to compute the // protocol swap fees due in future joins and exits. _lastInvariant = _invariantAfterExit(balances, amountsOut, normalizedWeights); return (bptAmountIn, amountsOut, dueProtocolFeeAmounts); } function _doExit( uint256[] memory balances, uint256[] memory normalizedWeights, uint256[] memory scalingFactors, bytes memory userData ) internal returns (uint256, uint256[] memory) { ExitKind kind = userData.exitKind(); if (kind == ExitKind.EXACT_BPT_IN_FOR_ONE_TOKEN_OUT) { return _exitExactBPTInForTokenOut(balances, normalizedWeights, userData); } else if (kind == ExitKind.EXACT_BPT_IN_FOR_TOKENS_OUT) { return _exitExactBPTInForTokensOut(balances, userData); } else if (kind == ExitKind.BPT_IN_FOR_EXACT_TOKENS_OUT) { return _exitBPTInForExactTokensOut(balances, normalizedWeights, scalingFactors, userData); } else { _revert(Errors.UNHANDLED_EXIT_KIND); } } function _exitExactBPTInForTokenOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private whenNotPaused returns (uint256, uint256[] memory) { // This exit function is disabled if the contract is paused. (uint256 bptAmountIn, uint256 tokenIndex) = userData.exactBptInForTokenOut(); // Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`. _require(tokenIndex < _getTotalTokens(), Errors.OUT_OF_BOUNDS); (uint256 amountOut, uint256 swapFee) = WeightedMath._calcTokenOutGivenExactBptIn( balances[tokenIndex], normalizedWeights[tokenIndex], bptAmountIn, totalSupply(), getSwapFeePercentage() ); // This is an exceptional situation in which the fee is charged on a token out instead of a token in. // Note that swapFee is already upscaled. _processSwapFeeAmount(tokenIndex, swapFee); // We exit in a single token, so we initialize amountsOut with zeros uint256[] memory amountsOut = new uint256[](_getTotalTokens()); // And then assign the result to the selected token amountsOut[tokenIndex] = amountOut; return (bptAmountIn, amountsOut); } function _exitExactBPTInForTokensOut(uint256[] memory balances, bytes memory userData) private view returns (uint256, uint256[] memory) { // This exit function is the only one that is not disabled if the contract is paused: it remains unrestricted // in an attempt to provide users with a mechanism to retrieve their tokens in case of an emergency. // This particular exit function is the only one that remains available because it is the simplest one, and // therefore the one with the lowest likelihood of errors. uint256 bptAmountIn = userData.exactBptInForTokensOut(); // Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`. uint256[] memory amountsOut = WeightedMath._calcTokensOutGivenExactBptIn(balances, bptAmountIn, totalSupply()); return (bptAmountIn, amountsOut); } function _exitBPTInForExactTokensOut( uint256[] memory balances, uint256[] memory normalizedWeights, uint256[] memory scalingFactors, bytes memory userData ) private whenNotPaused returns (uint256, uint256[] memory) { // This exit function is disabled if the contract is paused. (uint256[] memory amountsOut, uint256 maxBPTAmountIn) = userData.bptInForExactTokensOut(); InputHelpers.ensureInputLengthMatch(amountsOut.length, _getTotalTokens()); _upscaleArray(amountsOut, scalingFactors); (uint256 bptAmountIn, uint256[] memory swapFees) = WeightedMath._calcBptInGivenExactTokensOut( balances, normalizedWeights, amountsOut, totalSupply(), getSwapFeePercentage() ); _require(bptAmountIn <= maxBPTAmountIn, Errors.BPT_IN_MAX_AMOUNT); // This is an exceptional situation in which the fee is charged on a token out instead of a token in. // Note that swapFee is already upscaled. _processSwapFeeAmounts(swapFees); return (bptAmountIn, amountsOut); } // Helpers function _getDueProtocolFeeAmounts( uint256[] memory balances, uint256[] memory normalizedWeights, uint256 maxWeightTokenIndex, uint256 previousInvariant, uint256 currentInvariant, uint256 protocolSwapFeePercentage ) private view returns (uint256[] memory) { // Initialize with zeros uint256[] memory dueProtocolFeeAmounts = new uint256[](_getTotalTokens()); // Early return if the protocol swap fee percentage is zero, saving gas. if (protocolSwapFeePercentage == 0) { return dueProtocolFeeAmounts; } // The protocol swap fees are always paid using the token with the largest weight in the Pool. As this is the // token that is expected to have the largest balance, using it to pay fees should not unbalance the Pool. dueProtocolFeeAmounts[maxWeightTokenIndex] = WeightedMath._calcDueTokenProtocolSwapFeeAmount( balances[maxWeightTokenIndex], normalizedWeights[maxWeightTokenIndex], previousInvariant, currentInvariant, protocolSwapFeePercentage ); return dueProtocolFeeAmounts; } /** * @dev Returns the value of the invariant given `balances`, assuming they are increased by `amountsIn`. All * amounts are expected to be upscaled. */ function _invariantAfterJoin( uint256[] memory balances, uint256[] memory amountsIn, uint256[] memory normalizedWeights ) private view returns (uint256) { _mutateAmounts(balances, amountsIn, FixedPoint.add); return WeightedMath._calculateInvariant(normalizedWeights, balances); } function _invariantAfterExit( uint256[] memory balances, uint256[] memory amountsOut, uint256[] memory normalizedWeights ) private view returns (uint256) { _mutateAmounts(balances, amountsOut, FixedPoint.sub); return WeightedMath._calculateInvariant(normalizedWeights, balances); } /** * @dev Mutates `amounts` by applying `mutation` with each entry in `arguments`. * * Equivalent to `amounts = amounts.map(mutation)`. */ function _mutateAmounts( uint256[] memory toMutate, uint256[] memory arguments, function(uint256, uint256) pure returns (uint256) mutation ) private view { for (uint256 i = 0; i < _getTotalTokens(); ++i) { toMutate[i] = mutation(toMutate[i], arguments[i]); } } /** * @dev This function returns the appreciation of one BPT relative to the * underlying tokens. This starts at 1 when the pool is created and grows over time */ function getRate() public view returns (uint256) { // The initial BPT supply is equal to the invariant times the number of tokens. return Math.mul(getInvariant(), _getTotalTokens()).divDown(totalSupply()); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "./LogExpMath.sol"; import "../helpers/BalancerErrors.sol"; /* solhint-disable private-vars-leading-underscore */ library FixedPoint { uint256 internal constant ONE = 1e18; // 18 decimal places uint256 internal constant MAX_POW_RELATIVE_ERROR = 10000; // 10^(-14) // Minimum base for the power function when the exponent is 'free' (larger than ONE). uint256 internal constant MIN_POW_BASE_FREE_EXPONENT = 0.7e18; function add(uint256 a, uint256 b) internal pure returns (uint256) { // Fixed Point addition is the same as regular checked addition uint256 c = a + b; _require(c >= a, Errors.ADD_OVERFLOW); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { // Fixed Point addition is the same as regular checked addition _require(b <= a, Errors.SUB_OVERFLOW); uint256 c = a - b; return c; } function mulDown(uint256 a, uint256 b) internal pure returns (uint256) { uint256 product = a * b; _require(a == 0 || product / a == b, Errors.MUL_OVERFLOW); return product / ONE; } function mulUp(uint256 a, uint256 b) internal pure returns (uint256) { uint256 product = a * b; _require(a == 0 || product / a == b, Errors.MUL_OVERFLOW); if (product == 0) { return 0; } else { // The traditional divUp formula is: // divUp(x, y) := (x + y - 1) / y // To avoid intermediate overflow in the addition, we distribute the division and get: // divUp(x, y) := (x - 1) / y + 1 // Note that this requires x != 0, which we already tested for. return ((product - 1) / ONE) + 1; } } function divDown(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); if (a == 0) { return 0; } else { uint256 aInflated = a * ONE; _require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow return aInflated / b; } } function divUp(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); if (a == 0) { return 0; } else { uint256 aInflated = a * ONE; _require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow // The traditional divUp formula is: // divUp(x, y) := (x + y - 1) / y // To avoid intermediate overflow in the addition, we distribute the division and get: // divUp(x, y) := (x - 1) / y + 1 // Note that this requires x != 0, which we already tested for. return ((aInflated - 1) / b) + 1; } } /** * @dev Returns x^y, assuming both are fixed point numbers, rounding down. The result is guaranteed to not be above * the true value (that is, the error function expected - actual is always positive). */ function powDown(uint256 x, uint256 y) internal pure returns (uint256) { uint256 raw = LogExpMath.pow(x, y); uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1); if (raw < maxError) { return 0; } else { return sub(raw, maxError); } } /** * @dev Returns x^y, assuming both are fixed point numbers, rounding up. The result is guaranteed to not be below * the true value (that is, the error function expected - actual is always negative). */ function powUp(uint256 x, uint256 y) internal pure returns (uint256) { uint256 raw = LogExpMath.pow(x, y); uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1); return add(raw, maxError); } /** * @dev Returns the complement of a value (1 - x), capped to 0 if x is larger than 1. * * Useful when computing the complement for values with some level of relative error, as it strips this error and * prevents intermediate negative values. */ function complement(uint256 x) internal pure returns (uint256) { return (x < ONE) ? (ONE - x) : 0; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../openzeppelin/IERC20.sol"; import "./BalancerErrors.sol"; library InputHelpers { function ensureInputLengthMatch(uint256 a, uint256 b) internal pure { _require(a == b, Errors.INPUT_LENGTH_MISMATCH); } function ensureInputLengthMatch( uint256 a, uint256 b, uint256 c ) internal pure { _require(a == b && b == c, Errors.INPUT_LENGTH_MISMATCH); } function ensureArrayIsSorted(IERC20[] memory array) internal pure { address[] memory addressArray; // solhint-disable-next-line no-inline-assembly assembly { addressArray := array } ensureArrayIsSorted(addressArray); } function ensureArrayIsSorted(address[] memory array) internal pure { if (array.length < 2) { return; } address previous = array[0]; for (uint256 i = 1; i < array.length; ++i) { address current = array[i]; _require(previous < current, Errors.UNSORTED_ARRAY); previous = current; } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./BasePool.sol"; import "@balancer-labs/v2-vault/contracts/interfaces/IMinimalSwapInfoPool.sol"; /** * @dev Extension of `BasePool`, adding a handler for `IMinimalSwapInfoPool.onSwap`. * * Derived contracts must call `BasePool`'s constructor, and implement `_onSwapGivenIn` and `_onSwapGivenOut` along with * `BasePool`'s virtual functions. Inheriting from this contract lets derived contracts choose the Two Token or Minimal * Swap Info specialization settings. */ abstract contract BaseMinimalSwapInfoPool is IMinimalSwapInfoPool, BasePool { // Swap Hooks function onSwap( SwapRequest memory request, uint256 balanceTokenIn, uint256 balanceTokenOut ) public virtual override onlyVault(request.poolId) returns (uint256) { uint256 scalingFactorTokenIn = _scalingFactor(request.tokenIn); uint256 scalingFactorTokenOut = _scalingFactor(request.tokenOut); if (request.kind == IVault.SwapKind.GIVEN_IN) { // Fees are subtracted before scaling, to reduce the complexity of the rounding direction analysis. uint256 amountInMinusSwapFees = _subtractSwapFeeAmount(request.amount); // Process the (upscaled!) swap fee. uint256 swapFee = request.amount - amountInMinusSwapFees; _processSwapFeeAmount(request.tokenIn, _upscale(swapFee, scalingFactorTokenIn)); request.amount = amountInMinusSwapFees; // All token amounts are upscaled. balanceTokenIn = _upscale(balanceTokenIn, scalingFactorTokenIn); balanceTokenOut = _upscale(balanceTokenOut, scalingFactorTokenOut); request.amount = _upscale(request.amount, scalingFactorTokenIn); uint256 amountOut = _onSwapGivenIn(request, balanceTokenIn, balanceTokenOut); // amountOut tokens are exiting the Pool, so we round down. return _downscaleDown(amountOut, scalingFactorTokenOut); } else { // All token amounts are upscaled. balanceTokenIn = _upscale(balanceTokenIn, scalingFactorTokenIn); balanceTokenOut = _upscale(balanceTokenOut, scalingFactorTokenOut); request.amount = _upscale(request.amount, scalingFactorTokenOut); uint256 amountIn = _onSwapGivenOut(request, balanceTokenIn, balanceTokenOut); // amountIn tokens are entering the Pool, so we round up. amountIn = _downscaleUp(amountIn, scalingFactorTokenIn); // Fees are added after scaling happens, to reduce the complexity of the rounding direction analysis. uint256 amountInPlusSwapFees = _addSwapFeeAmount(amountIn); // Process the (upscaled!) swap fee. uint256 swapFee = amountInPlusSwapFees - amountIn; _processSwapFeeAmount(request.tokenIn, _upscale(swapFee, scalingFactorTokenIn)); return amountInPlusSwapFees; } } /* * @dev Called when a swap with the Pool occurs, where the amount of tokens entering the Pool is known. * * Returns the amount of tokens that will be taken from the Pool in return. * * All amounts inside `swapRequest`, `balanceTokenIn` and `balanceTokenOut` are upscaled. The swap fee has already * been deducted from `swapRequest.amount`. * * The return value is also considered upscaled, and will be downscaled (rounding down) before returning it to the * Vault. */ function _onSwapGivenIn( SwapRequest memory swapRequest, uint256 balanceTokenIn, uint256 balanceTokenOut ) internal virtual returns (uint256); /* * @dev Called when a swap with the Pool occurs, where the amount of tokens exiting the Pool is known. * * Returns the amount of tokens that will be granted to the Pool in return. * * All amounts inside `swapRequest`, `balanceTokenIn` and `balanceTokenOut` are upscaled. * * The return value is also considered upscaled, and will be downscaled (rounding up) before applying the swap fee * and returning it to the Vault. */ function _onSwapGivenOut( SwapRequest memory swapRequest, uint256 balanceTokenIn, uint256 balanceTokenOut ) internal virtual returns (uint256); /** * @dev Called whenever a swap fee is charged. Implementations should call their parents via super, to ensure all * implementations in the inheritance tree are called. * * Callers must call one of the three `_processSwapFeeAmount` functions when swap fees are computed, * and upscale `amount`. */ function _processSwapFeeAmount( uint256, /*index*/ uint256 /*amount*/ ) internal virtual {} function _processSwapFeeAmount(IERC20 token, uint256 amount) internal { _processSwapFeeAmount(_tokenAddressToIndex(token), amount); } function _processSwapFeeAmounts(uint256[] memory amounts) internal { InputHelpers.ensureInputLengthMatch(amounts.length, _getTotalTokens()); for (uint256 i = 0; i < _getTotalTokens(); ++i) { _processSwapFeeAmount(i, amounts[i]); } } /** * @dev Returns the index of `token` in the Pool's token array (i.e. the one `vault.getPoolTokens()` would return). * * A trivial (and incorrect!) implementation is already provided for Pools that don't override * `_processSwapFeeAmount` and skip the entire feature. However, Pools that do override `_processSwapFeeAmount` * *must* override this function with a meaningful implementation. */ function _tokenAddressToIndex( IERC20 /*token*/ ) internal view virtual returns (uint256) { return 0; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/math/FixedPoint.sol"; import "@balancer-labs/v2-solidity-utils/contracts/math/Math.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/InputHelpers.sol"; /* solhint-disable private-vars-leading-underscore */ contract WeightedMath { using FixedPoint for uint256; // A minimum normalized weight imposes a maximum weight ratio. We need this due to limitations in the // implementation of the power function, as these ratios are often exponents. uint256 internal constant _MIN_WEIGHT = 0.01e18; // Having a minimum normalized weight imposes a limit on the maximum number of tokens; // i.e., the largest possible pool is one where all tokens have exactly the minimum weight. uint256 internal constant _MAX_WEIGHTED_TOKENS = 100; // Pool limits that arise from limitations in the fixed point power function (and the imposed 1:100 maximum weight // ratio). // Swap limits: amounts swapped may not be larger than this percentage of total balance. uint256 internal constant _MAX_IN_RATIO = 0.3e18; uint256 internal constant _MAX_OUT_RATIO = 0.3e18; // Invariant growth limit: non-proportional joins cannot cause the invariant to increase by more than this ratio. uint256 internal constant _MAX_INVARIANT_RATIO = 3e18; // Invariant shrink limit: non-proportional exits cannot cause the invariant to decrease by less than this ratio. uint256 internal constant _MIN_INVARIANT_RATIO = 0.7e18; // Invariant is used to collect protocol swap fees by comparing its value between two times. // So we can round always to the same direction. It is also used to initiate the BPT amount // and, because there is a minimum BPT, we round down the invariant. function _calculateInvariant(uint256[] memory normalizedWeights, uint256[] memory balances) internal pure returns (uint256 invariant) { /********************************************************************************************** // invariant _____ // // wi = weight index i | | wi // // bi = balance index i | | bi ^ = i // // i = invariant // **********************************************************************************************/ invariant = FixedPoint.ONE; for (uint256 i = 0; i < normalizedWeights.length; i++) { invariant = invariant.mulDown(balances[i].powDown(normalizedWeights[i])); } _require(invariant > 0, Errors.ZERO_INVARIANT); } // Computes how many tokens can be taken out of a pool if `amountIn` are sent, given the // current balances and weights. function _calcOutGivenIn( uint256 balanceIn, uint256 weightIn, uint256 balanceOut, uint256 weightOut, uint256 amountIn ) internal pure returns (uint256) { /********************************************************************************************** // outGivenIn // // aO = amountOut // // bO = balanceOut // // bI = balanceIn / / bI \ (wI / wO) \ // // aI = amountIn aO = bO * | 1 - | -------------------------- | ^ | // // wI = weightIn \ \ ( bI + aI ) / / // // wO = weightOut // **********************************************************************************************/ // Amount out, so we round down overall. // The multiplication rounds down, and the subtrahend (power) rounds up (so the base rounds up too). // Because bI / (bI + aI) <= 1, the exponent rounds down. // Cannot exceed maximum in ratio _require(amountIn <= balanceIn.mulDown(_MAX_IN_RATIO), Errors.MAX_IN_RATIO); uint256 denominator = balanceIn.add(amountIn); uint256 base = balanceIn.divUp(denominator); uint256 exponent = weightIn.divDown(weightOut); uint256 power = base.powUp(exponent); return balanceOut.mulDown(power.complement()); } // Computes how many tokens must be sent to a pool in order to take `amountOut`, given the // current balances and weights. function _calcInGivenOut( uint256 balanceIn, uint256 weightIn, uint256 balanceOut, uint256 weightOut, uint256 amountOut ) internal pure returns (uint256) { /********************************************************************************************** // inGivenOut // // aO = amountOut // // bO = balanceOut // // bI = balanceIn / / bO \ (wO / wI) \ // // aI = amountIn aI = bI * | | -------------------------- | ^ - 1 | // // wI = weightIn \ \ ( bO - aO ) / / // // wO = weightOut // **********************************************************************************************/ // Amount in, so we round up overall. // The multiplication rounds up, and the power rounds up (so the base rounds up too). // Because b0 / (b0 - a0) >= 1, the exponent rounds up. // Cannot exceed maximum out ratio _require(amountOut <= balanceOut.mulDown(_MAX_OUT_RATIO), Errors.MAX_OUT_RATIO); uint256 base = balanceOut.divUp(balanceOut.sub(amountOut)); uint256 exponent = weightOut.divUp(weightIn); uint256 power = base.powUp(exponent); // Because the base is larger than one (and the power rounds up), the power should always be larger than one, so // the following subtraction should never revert. uint256 ratio = power.sub(FixedPoint.ONE); return balanceIn.mulUp(ratio); } function _calcBptOutGivenExactTokensIn( uint256[] memory balances, uint256[] memory normalizedWeights, uint256[] memory amountsIn, uint256 bptTotalSupply, uint256 swapFeePercentage ) internal pure returns (uint256, uint256[] memory) { // BPT out, so we round down overall. uint256[] memory balanceRatiosWithFee = new uint256[](amountsIn.length); uint256 invariantRatioWithFees = 0; for (uint256 i = 0; i < balances.length; i++) { balanceRatiosWithFee[i] = balances[i].add(amountsIn[i]).divDown(balances[i]); invariantRatioWithFees = invariantRatioWithFees.add(balanceRatiosWithFee[i].mulDown(normalizedWeights[i])); } (uint256 invariantRatio, uint256[] memory swapFees) = _computeJoinExactTokensInInvariantRatio( balances, normalizedWeights, amountsIn, balanceRatiosWithFee, invariantRatioWithFees, swapFeePercentage ); uint256 bptOut = (invariantRatio > FixedPoint.ONE) ? bptTotalSupply.mulDown(invariantRatio.sub(FixedPoint.ONE)) : 0; return (bptOut, swapFees); } /** * @dev Intermediate function to avoid stack-too-deep errors. */ function _computeJoinExactTokensInInvariantRatio( uint256[] memory balances, uint256[] memory normalizedWeights, uint256[] memory amountsIn, uint256[] memory balanceRatiosWithFee, uint256 invariantRatioWithFees, uint256 swapFeePercentage ) private pure returns (uint256 invariantRatio, uint256[] memory swapFees) { // Swap fees are charged on all tokens that are being added in a larger proportion than the overall invariant // increase. swapFees = new uint256[](amountsIn.length); invariantRatio = FixedPoint.ONE; for (uint256 i = 0; i < balances.length; i++) { uint256 amountInWithoutFee; if (balanceRatiosWithFee[i] > invariantRatioWithFees) { uint256 nonTaxableAmount = balances[i].mulDown(invariantRatioWithFees.sub(FixedPoint.ONE)); uint256 taxableAmount = amountsIn[i].sub(nonTaxableAmount); uint256 swapFee = taxableAmount.mulUp(swapFeePercentage); amountInWithoutFee = nonTaxableAmount.add(taxableAmount.sub(swapFee)); swapFees[i] = swapFee; } else { amountInWithoutFee = amountsIn[i]; } uint256 balanceRatio = balances[i].add(amountInWithoutFee).divDown(balances[i]); invariantRatio = invariantRatio.mulDown(balanceRatio.powDown(normalizedWeights[i])); } } function _calcTokenInGivenExactBptOut( uint256 balance, uint256 normalizedWeight, uint256 bptAmountOut, uint256 bptTotalSupply, uint256 swapFeePercentage ) internal pure returns (uint256 amountIn, uint256 swapFee) { /****************************************************************************************** // tokenInForExactBPTOut // // a = amountIn // // b = balance / / totalBPT + bptOut \ (1 / w) \ // // bptOut = bptAmountOut a = b * | | -------------------------- | ^ - 1 | // // bpt = totalBPT \ \ totalBPT / / // // w = weight // ******************************************************************************************/ // Token in, so we round up overall. // Calculate the factor by which the invariant will increase after minting BPTAmountOut uint256 invariantRatio = bptTotalSupply.add(bptAmountOut).divUp(bptTotalSupply); _require(invariantRatio <= _MAX_INVARIANT_RATIO, Errors.MAX_OUT_BPT_FOR_TOKEN_IN); // Calculate by how much the token balance has to increase to match the invariantRatio uint256 balanceRatio = invariantRatio.powUp(FixedPoint.ONE.divUp(normalizedWeight)); uint256 amountInWithoutFee = balance.mulUp(balanceRatio.sub(FixedPoint.ONE)); // We can now compute how much extra balance is being deposited and used in virtual swaps, and charge swap fees // accordingly. uint256 taxablePercentage = normalizedWeight.complement(); uint256 taxableAmount = amountInWithoutFee.mulUp(taxablePercentage); uint256 nonTaxableAmount = amountInWithoutFee.sub(taxableAmount); uint256 taxableAmountPlusFees = taxableAmount.divUp(FixedPoint.ONE.sub(swapFeePercentage)); swapFee = taxableAmountPlusFees - taxableAmount; amountIn = nonTaxableAmount.add(taxableAmountPlusFees); } function _calcAllTokensInGivenExactBptOut( uint256[] memory balances, uint256 bptAmountOut, uint256 totalBPT ) internal pure returns (uint256[] memory) { /************************************************************************************ // tokensInForExactBptOut // // (per token) // // aI = amountIn / bptOut \ // // b = balance aI = b * | ------------ | // // bptOut = bptAmountOut \ totalBPT / // // bpt = totalBPT // ************************************************************************************/ // Tokens in, so we round up overall. uint256 bptRatio = bptAmountOut.divUp(totalBPT); uint256[] memory amountsIn = new uint256[](balances.length); for (uint256 i = 0; i < balances.length; i++) { amountsIn[i] = balances[i].mulUp(bptRatio); } return amountsIn; } function _calcBptInGivenExactTokensOut( uint256[] memory balances, uint256[] memory normalizedWeights, uint256[] memory amountsOut, uint256 bptTotalSupply, uint256 swapFeePercentage ) internal pure returns (uint256, uint256[] memory) { // BPT in, so we round up overall. uint256[] memory balanceRatiosWithoutFee = new uint256[](amountsOut.length); uint256 invariantRatioWithoutFees = 0; for (uint256 i = 0; i < balances.length; i++) { balanceRatiosWithoutFee[i] = balances[i].sub(amountsOut[i]).divUp(balances[i]); invariantRatioWithoutFees = invariantRatioWithoutFees.add( balanceRatiosWithoutFee[i].mulUp(normalizedWeights[i]) ); } (uint256 invariantRatio, uint256[] memory swapFees) = _computeExitExactTokensOutInvariantRatio( balances, normalizedWeights, amountsOut, balanceRatiosWithoutFee, invariantRatioWithoutFees, swapFeePercentage ); uint256 bptIn = bptTotalSupply.mulUp(invariantRatio.complement()); return (bptIn, swapFees); } /** * @dev Intermediate function to avoid stack-too-deep errors. */ function _computeExitExactTokensOutInvariantRatio( uint256[] memory balances, uint256[] memory normalizedWeights, uint256[] memory amountsOut, uint256[] memory balanceRatiosWithoutFee, uint256 invariantRatioWithoutFees, uint256 swapFeePercentage ) private pure returns (uint256 invariantRatio, uint256[] memory swapFees) { swapFees = new uint256[](amountsOut.length); invariantRatio = FixedPoint.ONE; for (uint256 i = 0; i < balances.length; i++) { // Swap fees are typically charged on 'token in', but there is no 'token in' here, so we apply it to // 'token out'. This results in slightly larger price impact. uint256 amountOutWithFee; if (invariantRatioWithoutFees > balanceRatiosWithoutFee[i]) { uint256 nonTaxableAmount = balances[i].mulDown(invariantRatioWithoutFees.complement()); uint256 taxableAmount = amountsOut[i].sub(nonTaxableAmount); uint256 taxableAmountPlusFees = taxableAmount.divUp(FixedPoint.ONE.sub(swapFeePercentage)); swapFees[i] = taxableAmountPlusFees - taxableAmount; amountOutWithFee = nonTaxableAmount.add(taxableAmountPlusFees); } else { amountOutWithFee = amountsOut[i]; } uint256 balanceRatio = balances[i].sub(amountOutWithFee).divDown(balances[i]); invariantRatio = invariantRatio.mulDown(balanceRatio.powDown(normalizedWeights[i])); } } function _calcTokenOutGivenExactBptIn( uint256 balance, uint256 normalizedWeight, uint256 bptAmountIn, uint256 bptTotalSupply, uint256 swapFeePercentage ) internal pure returns (uint256 amountOut, uint256 swapFee) { /***************************************************************************************** // exactBPTInForTokenOut // // a = amountOut // // b = balance / / totalBPT - bptIn \ (1 / w) \ // // bptIn = bptAmountIn a = b * | 1 - | -------------------------- | ^ | // // bpt = totalBPT \ \ totalBPT / / // // w = weight // *****************************************************************************************/ // Token out, so we round down overall. The multiplication rounds down, but the power rounds up (so the base // rounds up). Because (totalBPT - bptIn) / totalBPT <= 1, the exponent rounds down. // Calculate the factor by which the invariant will decrease after burning BPTAmountIn uint256 invariantRatio = bptTotalSupply.sub(bptAmountIn).divUp(bptTotalSupply); _require(invariantRatio >= _MIN_INVARIANT_RATIO, Errors.MIN_BPT_IN_FOR_TOKEN_OUT); // Calculate by how much the token balance has to decrease to match invariantRatio uint256 balanceRatio = invariantRatio.powUp(FixedPoint.ONE.divDown(normalizedWeight)); // Because of rounding up, balanceRatio can be greater than one. Using complement prevents reverts. uint256 amountOutWithoutFee = balance.mulDown(balanceRatio.complement()); // We can now compute how much excess balance is being withdrawn as a result of the virtual swaps, which result // in swap fees. uint256 taxablePercentage = normalizedWeight.complement(); // Swap fees are typically charged on 'token in', but there is no 'token in' here, so we apply it // to 'token out'. This results in slightly larger price impact. Fees are rounded up. uint256 taxableAmount = amountOutWithoutFee.mulUp(taxablePercentage); uint256 nonTaxableAmount = amountOutWithoutFee.sub(taxableAmount); swapFee = taxableAmount.mulUp(swapFeePercentage); amountOut = nonTaxableAmount.add(taxableAmount.sub(swapFee)); } function _calcTokensOutGivenExactBptIn( uint256[] memory balances, uint256 bptAmountIn, uint256 totalBPT ) internal pure returns (uint256[] memory) { /********************************************************************************************** // exactBPTInForTokensOut // // (per token) // // aO = amountOut / bptIn \ // // b = balance a0 = b * | --------------------- | // // bptIn = bptAmountIn \ totalBPT / // // bpt = totalBPT // **********************************************************************************************/ // Since we're computing an amount out, we round down overall. This means rounding down on both the // multiplication and division. uint256 bptRatio = bptAmountIn.divDown(totalBPT); uint256[] memory amountsOut = new uint256[](balances.length); for (uint256 i = 0; i < balances.length; i++) { amountsOut[i] = balances[i].mulDown(bptRatio); } return amountsOut; } function _calcDueTokenProtocolSwapFeeAmount( uint256 balance, uint256 normalizedWeight, uint256 previousInvariant, uint256 currentInvariant, uint256 protocolSwapFeePercentage ) internal pure returns (uint256) { /********************************************************************************* /* protocolSwapFeePercentage * balanceToken * ( 1 - (previousInvariant / currentInvariant) ^ (1 / weightToken)) *********************************************************************************/ if (currentInvariant <= previousInvariant) { // This shouldn't happen outside of rounding errors, but have this safeguard nonetheless to prevent the Pool // from entering a locked state in which joins and exits revert while computing accumulated swap fees. return 0; } // We round down to prevent issues in the Pool's accounting, even if it means paying slightly less in protocol // fees to the Vault. // Fee percentage and balance multiplications round down, while the subtrahend (power) rounds up (as does the // base). Because previousInvariant / currentInvariant <= 1, the exponent rounds down. uint256 base = previousInvariant.divUp(currentInvariant); uint256 exponent = FixedPoint.ONE.divDown(normalizedWeight); // Because the exponent is larger than one, the base of the power function has a lower bound. We cap to this // value to avoid numeric issues, which means in the extreme case (where the invariant growth is larger than // 1 / min exponent) the Pool will pay less in protocol fees than it should. base = Math.max(base, FixedPoint.MIN_POW_BASE_FREE_EXPONENT); uint256 power = base.powUp(exponent); uint256 tokenAccruedFees = balance.mulDown(power.complement()); return tokenAccruedFees.mulDown(protocolSwapFeePercentage); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; import "./BaseWeightedPool.sol"; library WeightedPoolUserDataHelpers { function joinKind(bytes memory self) internal pure returns (BaseWeightedPool.JoinKind) { return abi.decode(self, (BaseWeightedPool.JoinKind)); } function exitKind(bytes memory self) internal pure returns (BaseWeightedPool.ExitKind) { return abi.decode(self, (BaseWeightedPool.ExitKind)); } // Joins function initialAmountsIn(bytes memory self) internal pure returns (uint256[] memory amountsIn) { (, amountsIn) = abi.decode(self, (BaseWeightedPool.JoinKind, uint256[])); } function exactTokensInForBptOut(bytes memory self) internal pure returns (uint256[] memory amountsIn, uint256 minBPTAmountOut) { (, amountsIn, minBPTAmountOut) = abi.decode(self, (BaseWeightedPool.JoinKind, uint256[], uint256)); } function tokenInForExactBptOut(bytes memory self) internal pure returns (uint256 bptAmountOut, uint256 tokenIndex) { (, bptAmountOut, tokenIndex) = abi.decode(self, (BaseWeightedPool.JoinKind, uint256, uint256)); } function allTokensInForExactBptOut(bytes memory self) internal pure returns (uint256 bptAmountOut) { (, bptAmountOut) = abi.decode(self, (BaseWeightedPool.JoinKind, uint256)); } // Exits function exactBptInForTokenOut(bytes memory self) internal pure returns (uint256 bptAmountIn, uint256 tokenIndex) { (, bptAmountIn, tokenIndex) = abi.decode(self, (BaseWeightedPool.ExitKind, uint256, uint256)); } function exactBptInForTokensOut(bytes memory self) internal pure returns (uint256 bptAmountIn) { (, bptAmountIn) = abi.decode(self, (BaseWeightedPool.ExitKind, uint256)); } function bptInForExactTokensOut(bytes memory self) internal pure returns (uint256[] memory amountsOut, uint256 maxBPTAmountIn) { (, amountsOut, maxBPTAmountIn) = abi.decode(self, (BaseWeightedPool.ExitKind, uint256[], uint256)); } } // SPDX-License-Identifier: MIT // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the “Software”), to deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the // Software. // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; /* solhint-disable */ /** * @dev Exponentiation and logarithm functions for 18 decimal fixed point numbers (both base and exponent/argument). * * Exponentiation and logarithm with arbitrary bases (x^y and log_x(y)) are implemented by conversion to natural * exponentiation and logarithm (where the base is Euler's number). * * @author Fernando Martinelli - @fernandomartinelli * @author Sergio Yuhjtman - @sergioyuhjtman * @author Daniel Fernandez - @dmf7z */ library LogExpMath { // All fixed point multiplications and divisions are inlined. This means we need to divide by ONE when multiplying // two numbers, and multiply by ONE when dividing them. // All arguments and return values are 18 decimal fixed point numbers. int256 constant ONE_18 = 1e18; // Internally, intermediate values are computed with higher precision as 20 decimal fixed point numbers, and in the // case of ln36, 36 decimals. int256 constant ONE_20 = 1e20; int256 constant ONE_36 = 1e36; // The domain of natural exponentiation is bound by the word size and number of decimals used. // // Because internally the result will be stored using 20 decimals, the largest possible result is // (2^255 - 1) / 10^20, which makes the largest exponent ln((2^255 - 1) / 10^20) = 130.700829182905140221. // The smallest possible result is 10^(-18), which makes largest negative argument // ln(10^(-18)) = -41.446531673892822312. // We use 130.0 and -41.0 to have some safety margin. int256 constant MAX_NATURAL_EXPONENT = 130e18; int256 constant MIN_NATURAL_EXPONENT = -41e18; // Bounds for ln_36's argument. Both ln(0.9) and ln(1.1) can be represented with 36 decimal places in a fixed point // 256 bit integer. int256 constant LN_36_LOWER_BOUND = ONE_18 - 1e17; int256 constant LN_36_UPPER_BOUND = ONE_18 + 1e17; uint256 constant MILD_EXPONENT_BOUND = 2**254 / uint256(ONE_20); // 18 decimal constants int256 constant x0 = 128000000000000000000; // 2ˆ7 int256 constant a0 = 38877084059945950922200000000000000000000000000000000000; // eˆ(x0) (no decimals) int256 constant x1 = 64000000000000000000; // 2ˆ6 int256 constant a1 = 6235149080811616882910000000; // eˆ(x1) (no decimals) // 20 decimal constants int256 constant x2 = 3200000000000000000000; // 2ˆ5 int256 constant a2 = 7896296018268069516100000000000000; // eˆ(x2) int256 constant x3 = 1600000000000000000000; // 2ˆ4 int256 constant a3 = 888611052050787263676000000; // eˆ(x3) int256 constant x4 = 800000000000000000000; // 2ˆ3 int256 constant a4 = 298095798704172827474000; // eˆ(x4) int256 constant x5 = 400000000000000000000; // 2ˆ2 int256 constant a5 = 5459815003314423907810; // eˆ(x5) int256 constant x6 = 200000000000000000000; // 2ˆ1 int256 constant a6 = 738905609893065022723; // eˆ(x6) int256 constant x7 = 100000000000000000000; // 2ˆ0 int256 constant a7 = 271828182845904523536; // eˆ(x7) int256 constant x8 = 50000000000000000000; // 2ˆ-1 int256 constant a8 = 164872127070012814685; // eˆ(x8) int256 constant x9 = 25000000000000000000; // 2ˆ-2 int256 constant a9 = 128402541668774148407; // eˆ(x9) int256 constant x10 = 12500000000000000000; // 2ˆ-3 int256 constant a10 = 113314845306682631683; // eˆ(x10) int256 constant x11 = 6250000000000000000; // 2ˆ-4 int256 constant a11 = 106449445891785942956; // eˆ(x11) /** * @dev Exponentiation (x^y) with unsigned 18 decimal fixed point base and exponent. * * Reverts if ln(x) * y is smaller than `MIN_NATURAL_EXPONENT`, or larger than `MAX_NATURAL_EXPONENT`. */ function pow(uint256 x, uint256 y) internal pure returns (uint256) { if (y == 0) { // We solve the 0^0 indetermination by making it equal one. return uint256(ONE_18); } if (x == 0) { return 0; } // Instead of computing x^y directly, we instead rely on the properties of logarithms and exponentiation to // arrive at that result. In particular, exp(ln(x)) = x, and ln(x^y) = y * ln(x). This means // x^y = exp(y * ln(x)). // The ln function takes a signed value, so we need to make sure x fits in the signed 256 bit range. _require(x < 2**255, Errors.X_OUT_OF_BOUNDS); int256 x_int256 = int256(x); // We will compute y * ln(x) in a single step. Depending on the value of x, we can either use ln or ln_36. In // both cases, we leave the division by ONE_18 (due to fixed point multiplication) to the end. // This prevents y * ln(x) from overflowing, and at the same time guarantees y fits in the signed 256 bit range. _require(y < MILD_EXPONENT_BOUND, Errors.Y_OUT_OF_BOUNDS); int256 y_int256 = int256(y); int256 logx_times_y; if (LN_36_LOWER_BOUND < x_int256 && x_int256 < LN_36_UPPER_BOUND) { int256 ln_36_x = _ln_36(x_int256); // ln_36_x has 36 decimal places, so multiplying by y_int256 isn't as straightforward, since we can't just // bring y_int256 to 36 decimal places, as it might overflow. Instead, we perform two 18 decimal // multiplications and add the results: one with the first 18 decimals of ln_36_x, and one with the // (downscaled) last 18 decimals. logx_times_y = ((ln_36_x / ONE_18) * y_int256 + ((ln_36_x % ONE_18) * y_int256) / ONE_18); } else { logx_times_y = _ln(x_int256) * y_int256; } logx_times_y /= ONE_18; // Finally, we compute exp(y * ln(x)) to arrive at x^y _require( MIN_NATURAL_EXPONENT <= logx_times_y && logx_times_y <= MAX_NATURAL_EXPONENT, Errors.PRODUCT_OUT_OF_BOUNDS ); return uint256(exp(logx_times_y)); } /** * @dev Natural exponentiation (e^x) with signed 18 decimal fixed point exponent. * * Reverts if `x` is smaller than MIN_NATURAL_EXPONENT, or larger than `MAX_NATURAL_EXPONENT`. */ function exp(int256 x) internal pure returns (int256) { _require(x >= MIN_NATURAL_EXPONENT && x <= MAX_NATURAL_EXPONENT, Errors.INVALID_EXPONENT); if (x < 0) { // We only handle positive exponents: e^(-x) is computed as 1 / e^x. We can safely make x positive since it // fits in the signed 256 bit range (as it is larger than MIN_NATURAL_EXPONENT). // Fixed point division requires multiplying by ONE_18. return ((ONE_18 * ONE_18) / exp(-x)); } // First, we use the fact that e^(x+y) = e^x * e^y to decompose x into a sum of powers of two, which we call x_n, // where x_n == 2^(7 - n), and e^x_n = a_n has been precomputed. We choose the first x_n, x0, to equal 2^7 // because all larger powers are larger than MAX_NATURAL_EXPONENT, and therefore not present in the // decomposition. // At the end of this process we will have the product of all e^x_n = a_n that apply, and the remainder of this // decomposition, which will be lower than the smallest x_n. // exp(x) = k_0 * a_0 * k_1 * a_1 * ... + k_n * a_n * exp(remainder), where each k_n equals either 0 or 1. // We mutate x by subtracting x_n, making it the remainder of the decomposition. // The first two a_n (e^(2^7) and e^(2^6)) are too large if stored as 18 decimal numbers, and could cause // intermediate overflows. Instead we store them as plain integers, with 0 decimals. // Additionally, x0 + x1 is larger than MAX_NATURAL_EXPONENT, which means they will not both be present in the // decomposition. // For each x_n, we test if that term is present in the decomposition (if x is larger than it), and if so deduct // it and compute the accumulated product. int256 firstAN; if (x >= x0) { x -= x0; firstAN = a0; } else if (x >= x1) { x -= x1; firstAN = a1; } else { firstAN = 1; // One with no decimal places } // We now transform x into a 20 decimal fixed point number, to have enhanced precision when computing the // smaller terms. x *= 100; // `product` is the accumulated product of all a_n (except a0 and a1), which starts at 20 decimal fixed point // one. Recall that fixed point multiplication requires dividing by ONE_20. int256 product = ONE_20; if (x >= x2) { x -= x2; product = (product * a2) / ONE_20; } if (x >= x3) { x -= x3; product = (product * a3) / ONE_20; } if (x >= x4) { x -= x4; product = (product * a4) / ONE_20; } if (x >= x5) { x -= x5; product = (product * a5) / ONE_20; } if (x >= x6) { x -= x6; product = (product * a6) / ONE_20; } if (x >= x7) { x -= x7; product = (product * a7) / ONE_20; } if (x >= x8) { x -= x8; product = (product * a8) / ONE_20; } if (x >= x9) { x -= x9; product = (product * a9) / ONE_20; } // x10 and x11 are unnecessary here since we have high enough precision already. // Now we need to compute e^x, where x is small (in particular, it is smaller than x9). We use the Taylor series // expansion for e^x: 1 + x + (x^2 / 2!) + (x^3 / 3!) + ... + (x^n / n!). int256 seriesSum = ONE_20; // The initial one in the sum, with 20 decimal places. int256 term; // Each term in the sum, where the nth term is (x^n / n!). // The first term is simply x. term = x; seriesSum += term; // Each term (x^n / n!) equals the previous one times x, divided by n. Since x is a fixed point number, // multiplying by it requires dividing by ONE_20, but dividing by the non-fixed point n values does not. term = ((term * x) / ONE_20) / 2; seriesSum += term; term = ((term * x) / ONE_20) / 3; seriesSum += term; term = ((term * x) / ONE_20) / 4; seriesSum += term; term = ((term * x) / ONE_20) / 5; seriesSum += term; term = ((term * x) / ONE_20) / 6; seriesSum += term; term = ((term * x) / ONE_20) / 7; seriesSum += term; term = ((term * x) / ONE_20) / 8; seriesSum += term; term = ((term * x) / ONE_20) / 9; seriesSum += term; term = ((term * x) / ONE_20) / 10; seriesSum += term; term = ((term * x) / ONE_20) / 11; seriesSum += term; term = ((term * x) / ONE_20) / 12; seriesSum += term; // 12 Taylor terms are sufficient for 18 decimal precision. // We now have the first a_n (with no decimals), and the product of all other a_n present, and the Taylor // approximation of the exponentiation of the remainder (both with 20 decimals). All that remains is to multiply // all three (one 20 decimal fixed point multiplication, dividing by ONE_20, and one integer multiplication), // and then drop two digits to return an 18 decimal value. return (((product * seriesSum) / ONE_20) * firstAN) / 100; } /** * @dev Logarithm (log(arg, base), with signed 18 decimal fixed point base and argument. */ function log(int256 arg, int256 base) internal pure returns (int256) { // This performs a simple base change: log(arg, base) = ln(arg) / ln(base). // Both logBase and logArg are computed as 36 decimal fixed point numbers, either by using ln_36, or by // upscaling. int256 logBase; if (LN_36_LOWER_BOUND < base && base < LN_36_UPPER_BOUND) { logBase = _ln_36(base); } else { logBase = _ln(base) * ONE_18; } int256 logArg; if (LN_36_LOWER_BOUND < arg && arg < LN_36_UPPER_BOUND) { logArg = _ln_36(arg); } else { logArg = _ln(arg) * ONE_18; } // When dividing, we multiply by ONE_18 to arrive at a result with 18 decimal places return (logArg * ONE_18) / logBase; } /** * @dev Natural logarithm (ln(a)) with signed 18 decimal fixed point argument. */ function ln(int256 a) internal pure returns (int256) { // The real natural logarithm is not defined for negative numbers or zero. _require(a > 0, Errors.OUT_OF_BOUNDS); if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) { return _ln_36(a) / ONE_18; } else { return _ln(a); } } /** * @dev Internal natural logarithm (ln(a)) with signed 18 decimal fixed point argument. */ function _ln(int256 a) private pure returns (int256) { if (a < ONE_18) { // Since ln(a^k) = k * ln(a), we can compute ln(a) as ln(a) = ln((1/a)^(-1)) = - ln((1/a)). If a is less // than one, 1/a will be greater than one, and this if statement will not be entered in the recursive call. // Fixed point division requires multiplying by ONE_18. return (-_ln((ONE_18 * ONE_18) / a)); } // First, we use the fact that ln^(a * b) = ln(a) + ln(b) to decompose ln(a) into a sum of powers of two, which // we call x_n, where x_n == 2^(7 - n), which are the natural logarithm of precomputed quantities a_n (that is, // ln(a_n) = x_n). We choose the first x_n, x0, to equal 2^7 because the exponential of all larger powers cannot // be represented as 18 fixed point decimal numbers in 256 bits, and are therefore larger than a. // At the end of this process we will have the sum of all x_n = ln(a_n) that apply, and the remainder of this // decomposition, which will be lower than the smallest a_n. // ln(a) = k_0 * x_0 + k_1 * x_1 + ... + k_n * x_n + ln(remainder), where each k_n equals either 0 or 1. // We mutate a by subtracting a_n, making it the remainder of the decomposition. // For reasons related to how `exp` works, the first two a_n (e^(2^7) and e^(2^6)) are not stored as fixed point // numbers with 18 decimals, but instead as plain integers with 0 decimals, so we need to multiply them by // ONE_18 to convert them to fixed point. // For each a_n, we test if that term is present in the decomposition (if a is larger than it), and if so divide // by it and compute the accumulated sum. int256 sum = 0; if (a >= a0 * ONE_18) { a /= a0; // Integer, not fixed point division sum += x0; } if (a >= a1 * ONE_18) { a /= a1; // Integer, not fixed point division sum += x1; } // All other a_n and x_n are stored as 20 digit fixed point numbers, so we convert the sum and a to this format. sum *= 100; a *= 100; // Because further a_n are 20 digit fixed point numbers, we multiply by ONE_20 when dividing by them. if (a >= a2) { a = (a * ONE_20) / a2; sum += x2; } if (a >= a3) { a = (a * ONE_20) / a3; sum += x3; } if (a >= a4) { a = (a * ONE_20) / a4; sum += x4; } if (a >= a5) { a = (a * ONE_20) / a5; sum += x5; } if (a >= a6) { a = (a * ONE_20) / a6; sum += x6; } if (a >= a7) { a = (a * ONE_20) / a7; sum += x7; } if (a >= a8) { a = (a * ONE_20) / a8; sum += x8; } if (a >= a9) { a = (a * ONE_20) / a9; sum += x9; } if (a >= a10) { a = (a * ONE_20) / a10; sum += x10; } if (a >= a11) { a = (a * ONE_20) / a11; sum += x11; } // a is now a small number (smaller than a_11, which roughly equals 1.06). This means we can use a Taylor series // that converges rapidly for values of `a` close to one - the same one used in ln_36. // Let z = (a - 1) / (a + 1). // ln(a) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1)) // Recall that 20 digit fixed point division requires multiplying by ONE_20, and multiplication requires // division by ONE_20. int256 z = ((a - ONE_20) * ONE_20) / (a + ONE_20); int256 z_squared = (z * z) / ONE_20; // num is the numerator of the series: the z^(2 * n + 1) term int256 num = z; // seriesSum holds the accumulated sum of each term in the series, starting with the initial z int256 seriesSum = num; // In each step, the numerator is multiplied by z^2 num = (num * z_squared) / ONE_20; seriesSum += num / 3; num = (num * z_squared) / ONE_20; seriesSum += num / 5; num = (num * z_squared) / ONE_20; seriesSum += num / 7; num = (num * z_squared) / ONE_20; seriesSum += num / 9; num = (num * z_squared) / ONE_20; seriesSum += num / 11; // 6 Taylor terms are sufficient for 36 decimal precision. // Finally, we multiply by 2 (non fixed point) to compute ln(remainder) seriesSum *= 2; // We now have the sum of all x_n present, and the Taylor approximation of the logarithm of the remainder (both // with 20 decimals). All that remains is to sum these two, and then drop two digits to return a 18 decimal // value. return (sum + seriesSum) / 100; } /** * @dev Intrnal high precision (36 decimal places) natural logarithm (ln(x)) with signed 18 decimal fixed point argument, * for x close to one. * * Should only be used if x is between LN_36_LOWER_BOUND and LN_36_UPPER_BOUND. */ function _ln_36(int256 x) private pure returns (int256) { // Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits // worthwhile. // First, we transform x to a 36 digit fixed point value. x *= ONE_18; // We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1). // ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1)) // Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires // division by ONE_36. int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36); int256 z_squared = (z * z) / ONE_36; // num is the numerator of the series: the z^(2 * n + 1) term int256 num = z; // seriesSum holds the accumulated sum of each term in the series, starting with the initial z int256 seriesSum = num; // In each step, the numerator is multiplied by z^2 num = (num * z_squared) / ONE_36; seriesSum += num / 3; num = (num * z_squared) / ONE_36; seriesSum += num / 5; num = (num * z_squared) / ONE_36; seriesSum += num / 7; num = (num * z_squared) / ONE_36; seriesSum += num / 9; num = (num * z_squared) / ONE_36; seriesSum += num / 11; num = (num * z_squared) / ONE_36; seriesSum += num / 13; num = (num * z_squared) / ONE_36; seriesSum += num / 15; // 8 Taylor terms are sufficient for 36 decimal precision. // All that remains is multiplying by 2 (non fixed point). return seriesSum * 2; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; // solhint-disable /** * @dev Reverts if `condition` is false, with a revert reason containing `errorCode`. Only codes up to 999 are * supported. */ function _require(bool condition, uint256 errorCode) pure { if (!condition) _revert(errorCode); } /** * @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported. */ function _revert(uint256 errorCode) pure { // We're going to dynamically create a revert string based on the error code, with the following format: // 'BAL#{errorCode}' // where the code is left-padded with zeroes to three digits (so they range from 000 to 999). // // We don't have revert strings embedded in the contract to save bytecode size: it takes much less space to store a // number (8 to 16 bits) than the individual string characters. // // The dynamic string creation algorithm that follows could be implemented in Solidity, but assembly allows for a // much denser implementation, again saving bytecode size. Given this function unconditionally reverts, this is a // safe place to rely on it without worrying about how its usage might affect e.g. memory contents. assembly { // First, we need to compute the ASCII representation of the error code. We assume that it is in the 0-999 // range, so we only need to convert three digits. To convert the digits to ASCII, we add 0x30, the value for // the '0' character. let units := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let tenths := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let hundreds := add(mod(errorCode, 10), 0x30) // With the individual characters, we can now construct the full string. The "BAL#" part is a known constant // (0x42414c23): we simply shift this by 24 (to provide space for the 3 bytes of the error code), and add the // characters to it, each shifted by a multiple of 8. // The revert reason is then shifted left by 200 bits (256 minus the length of the string, 7 characters * 8 bits // per character = 56) to locate it in the most significant part of the 256 slot (the beginning of a byte // array). let revertReason := shl(200, add(0x42414c23000000, add(add(units, shl(8, tenths)), shl(16, hundreds)))) // We can now encode the reason in memory, which can be safely overwritten as we're about to revert. The encoded // message will have the following layout: // [ revert reason identifier ] [ string location offset ] [ string length ] [ string contents ] // The Solidity revert reason identifier is 0x08c739a0, the function selector of the Error(string) function. We // also write zeroes to the next 28 bytes of memory, but those are about to be overwritten. mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000) // Next is the offset to the location of the string, which will be placed immediately after (20 bytes away). mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020) // The string length is fixed: 7 characters. mstore(0x24, 7) // Finally, the string itself is stored. mstore(0x44, revertReason) // Even if the string is only 7 bytes long, we need to return a full 32 byte slot containing it. The length of // the encoded message is therefore 4 + 32 + 32 + 32 = 100. revert(0, 100) } } library Errors { // Math uint256 internal constant ADD_OVERFLOW = 0; uint256 internal constant SUB_OVERFLOW = 1; uint256 internal constant SUB_UNDERFLOW = 2; uint256 internal constant MUL_OVERFLOW = 3; uint256 internal constant ZERO_DIVISION = 4; uint256 internal constant DIV_INTERNAL = 5; uint256 internal constant X_OUT_OF_BOUNDS = 6; uint256 internal constant Y_OUT_OF_BOUNDS = 7; uint256 internal constant PRODUCT_OUT_OF_BOUNDS = 8; uint256 internal constant INVALID_EXPONENT = 9; // Input uint256 internal constant OUT_OF_BOUNDS = 100; uint256 internal constant UNSORTED_ARRAY = 101; uint256 internal constant UNSORTED_TOKENS = 102; uint256 internal constant INPUT_LENGTH_MISMATCH = 103; uint256 internal constant ZERO_TOKEN = 104; // Shared pools uint256 internal constant MIN_TOKENS = 200; uint256 internal constant MAX_TOKENS = 201; uint256 internal constant MAX_SWAP_FEE_PERCENTAGE = 202; uint256 internal constant MIN_SWAP_FEE_PERCENTAGE = 203; uint256 internal constant MINIMUM_BPT = 204; uint256 internal constant CALLER_NOT_VAULT = 205; uint256 internal constant UNINITIALIZED = 206; uint256 internal constant BPT_IN_MAX_AMOUNT = 207; uint256 internal constant BPT_OUT_MIN_AMOUNT = 208; uint256 internal constant EXPIRED_PERMIT = 209; uint256 internal constant NOT_TWO_TOKENS = 210; // Pools uint256 internal constant MIN_AMP = 300; uint256 internal constant MAX_AMP = 301; uint256 internal constant MIN_WEIGHT = 302; uint256 internal constant MAX_STABLE_TOKENS = 303; uint256 internal constant MAX_IN_RATIO = 304; uint256 internal constant MAX_OUT_RATIO = 305; uint256 internal constant MIN_BPT_IN_FOR_TOKEN_OUT = 306; uint256 internal constant MAX_OUT_BPT_FOR_TOKEN_IN = 307; uint256 internal constant NORMALIZED_WEIGHT_INVARIANT = 308; uint256 internal constant INVALID_TOKEN = 309; uint256 internal constant UNHANDLED_JOIN_KIND = 310; uint256 internal constant ZERO_INVARIANT = 311; uint256 internal constant ORACLE_INVALID_SECONDS_QUERY = 312; uint256 internal constant ORACLE_NOT_INITIALIZED = 313; uint256 internal constant ORACLE_QUERY_TOO_OLD = 314; uint256 internal constant ORACLE_INVALID_INDEX = 315; uint256 internal constant ORACLE_BAD_SECS = 316; uint256 internal constant AMP_END_TIME_TOO_CLOSE = 317; uint256 internal constant AMP_ONGOING_UPDATE = 318; uint256 internal constant AMP_RATE_TOO_HIGH = 319; uint256 internal constant AMP_NO_ONGOING_UPDATE = 320; uint256 internal constant STABLE_INVARIANT_DIDNT_CONVERGE = 321; uint256 internal constant STABLE_GET_BALANCE_DIDNT_CONVERGE = 322; uint256 internal constant RELAYER_NOT_CONTRACT = 323; uint256 internal constant BASE_POOL_RELAYER_NOT_CALLED = 324; uint256 internal constant REBALANCING_RELAYER_REENTERED = 325; uint256 internal constant GRADUAL_UPDATE_TIME_TRAVEL = 326; uint256 internal constant SWAPS_DISABLED = 327; uint256 internal constant CALLER_IS_NOT_LBP_OWNER = 328; uint256 internal constant PRICE_RATE_OVERFLOW = 329; uint256 internal constant INVALID_JOIN_EXIT_KIND_WHILE_SWAPS_DISABLED = 330; uint256 internal constant WEIGHT_CHANGE_TOO_FAST = 331; uint256 internal constant LOWER_GREATER_THAN_UPPER_TARGET = 332; uint256 internal constant UPPER_TARGET_TOO_HIGH = 333; uint256 internal constant UNHANDLED_BY_LINEAR_POOL = 334; uint256 internal constant OUT_OF_TARGET_RANGE = 335; uint256 internal constant UNHANDLED_EXIT_KIND = 336; uint256 internal constant UNAUTHORIZED_EXIT = 337; uint256 internal constant MAX_MANAGEMENT_SWAP_FEE_PERCENTAGE = 338; uint256 internal constant UNHANDLED_BY_INVESTMENT_POOL = 339; // Lib uint256 internal constant REENTRANCY = 400; uint256 internal constant SENDER_NOT_ALLOWED = 401; uint256 internal constant PAUSED = 402; uint256 internal constant PAUSE_WINDOW_EXPIRED = 403; uint256 internal constant MAX_PAUSE_WINDOW_DURATION = 404; uint256 internal constant MAX_BUFFER_PERIOD_DURATION = 405; uint256 internal constant INSUFFICIENT_BALANCE = 406; uint256 internal constant INSUFFICIENT_ALLOWANCE = 407; uint256 internal constant ERC20_TRANSFER_FROM_ZERO_ADDRESS = 408; uint256 internal constant ERC20_TRANSFER_TO_ZERO_ADDRESS = 409; uint256 internal constant ERC20_MINT_TO_ZERO_ADDRESS = 410; uint256 internal constant ERC20_BURN_FROM_ZERO_ADDRESS = 411; uint256 internal constant ERC20_APPROVE_FROM_ZERO_ADDRESS = 412; uint256 internal constant ERC20_APPROVE_TO_ZERO_ADDRESS = 413; uint256 internal constant ERC20_TRANSFER_EXCEEDS_ALLOWANCE = 414; uint256 internal constant ERC20_DECREASED_ALLOWANCE_BELOW_ZERO = 415; uint256 internal constant ERC20_TRANSFER_EXCEEDS_BALANCE = 416; uint256 internal constant ERC20_BURN_EXCEEDS_ALLOWANCE = 417; uint256 internal constant SAFE_ERC20_CALL_FAILED = 418; uint256 internal constant ADDRESS_INSUFFICIENT_BALANCE = 419; uint256 internal constant ADDRESS_CANNOT_SEND_VALUE = 420; uint256 internal constant SAFE_CAST_VALUE_CANT_FIT_INT256 = 421; uint256 internal constant GRANT_SENDER_NOT_ADMIN = 422; uint256 internal constant REVOKE_SENDER_NOT_ADMIN = 423; uint256 internal constant RENOUNCE_SENDER_NOT_ALLOWED = 424; uint256 internal constant BUFFER_PERIOD_EXPIRED = 425; uint256 internal constant CALLER_IS_NOT_OWNER = 426; uint256 internal constant NEW_OWNER_IS_ZERO = 427; uint256 internal constant CODE_DEPLOYMENT_FAILED = 428; uint256 internal constant CALL_TO_NON_CONTRACT = 429; uint256 internal constant LOW_LEVEL_CALL_FAILED = 430; // Vault uint256 internal constant INVALID_POOL_ID = 500; uint256 internal constant CALLER_NOT_POOL = 501; uint256 internal constant SENDER_NOT_ASSET_MANAGER = 502; uint256 internal constant USER_DOESNT_ALLOW_RELAYER = 503; uint256 internal constant INVALID_SIGNATURE = 504; uint256 internal constant EXIT_BELOW_MIN = 505; uint256 internal constant JOIN_ABOVE_MAX = 506; uint256 internal constant SWAP_LIMIT = 507; uint256 internal constant SWAP_DEADLINE = 508; uint256 internal constant CANNOT_SWAP_SAME_TOKEN = 509; uint256 internal constant UNKNOWN_AMOUNT_IN_FIRST_SWAP = 510; uint256 internal constant MALCONSTRUCTED_MULTIHOP_SWAP = 511; uint256 internal constant INTERNAL_BALANCE_OVERFLOW = 512; uint256 internal constant INSUFFICIENT_INTERNAL_BALANCE = 513; uint256 internal constant INVALID_ETH_INTERNAL_BALANCE = 514; uint256 internal constant INVALID_POST_LOAN_BALANCE = 515; uint256 internal constant INSUFFICIENT_ETH = 516; uint256 internal constant UNALLOCATED_ETH = 517; uint256 internal constant ETH_TRANSFER = 518; uint256 internal constant CANNOT_USE_ETH_SENTINEL = 519; uint256 internal constant TOKENS_MISMATCH = 520; uint256 internal constant TOKEN_NOT_REGISTERED = 521; uint256 internal constant TOKEN_ALREADY_REGISTERED = 522; uint256 internal constant TOKENS_ALREADY_SET = 523; uint256 internal constant TOKENS_LENGTH_MUST_BE_2 = 524; uint256 internal constant NONZERO_TOKEN_BALANCE = 525; uint256 internal constant BALANCE_TOTAL_OVERFLOW = 526; uint256 internal constant POOL_NO_TOKENS = 527; uint256 internal constant INSUFFICIENT_FLASH_LOAN_BALANCE = 528; // Fees uint256 internal constant SWAP_FEE_PERCENTAGE_TOO_HIGH = 600; uint256 internal constant FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH = 601; uint256 internal constant INSUFFICIENT_FLASH_LOAN_FEE_AMOUNT = 602; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/math/Math.sol"; import "@balancer-labs/v2-solidity-utils/contracts/math/FixedPoint.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/InputHelpers.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/TemporarilyPausable.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/WordCodec.sol"; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ERC20.sol"; import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol"; import "@balancer-labs/v2-vault/contracts/interfaces/IBasePool.sol"; import "@balancer-labs/v2-asset-manager-utils/contracts/IAssetManager.sol"; import "./BalancerPoolToken.sol"; import "./BasePoolAuthorization.sol"; // solhint-disable max-states-count /** * @dev Reference implementation for the base layer of a Pool contract that manages a single Pool with optional * Asset Managers, an admin-controlled swap fee percentage, and an emergency pause mechanism. * * Note that neither swap fees nor the pause mechanism are used by this contract. They are passed through so that * derived contracts can use them via the `_addSwapFeeAmount` and `_subtractSwapFeeAmount` functions, and the * `whenNotPaused` modifier. * * No admin permissions are checked here: instead, this contract delegates that to the Vault's own Authorizer. * * Because this contract doesn't implement the swap hooks, derived contracts should generally inherit from * BaseGeneralPool or BaseMinimalSwapInfoPool. Otherwise, subclasses must inherit from the corresponding interfaces * and implement the swap callbacks themselves. */ abstract contract BasePool is IBasePool, BasePoolAuthorization, BalancerPoolToken, TemporarilyPausable { using WordCodec for bytes32; using FixedPoint for uint256; uint256 private constant _MIN_TOKENS = 2; uint256 private constant _MINIMUM_BPT = 1e6; // 1e18 corresponds to 1.0, or a 100% fee uint256 private constant _MIN_SWAP_FEE_PERCENTAGE = 1e12; // 0.0001% uint256 private constant _MAX_SWAP_FEE_PERCENTAGE = 1e17; // 10% - this fits in 64 bits // Storage slot that can be used to store unrelated pieces of information. In particular, by default is used // to store only the swap fee percentage of a pool. But it can be extended to store some more pieces of information. // The swap fee percentage is stored in the most-significant 64 bits, therefore the remaining 192 bits can be // used to store any other piece of information. bytes32 private _miscData; uint256 private constant _SWAP_FEE_PERCENTAGE_OFFSET = 192; IVault private immutable _vault; bytes32 private immutable _poolId; event SwapFeePercentageChanged(uint256 swapFeePercentage); constructor( IVault vault, IVault.PoolSpecialization specialization, string memory name, string memory symbol, IERC20[] memory tokens, address[] memory assetManagers, uint256 swapFeePercentage, uint256 pauseWindowDuration, uint256 bufferPeriodDuration, address owner ) // Base Pools are expected to be deployed using factories. By using the factory address as the action // disambiguator, we make all Pools deployed by the same factory share action identifiers. This allows for // simpler management of permissions (such as being able to manage granting the 'set fee percentage' action in // any Pool created by the same factory), while still making action identifiers unique among different factories // if the selectors match, preventing accidental errors. Authentication(bytes32(uint256(msg.sender))) BalancerPoolToken(name, symbol) BasePoolAuthorization(owner) TemporarilyPausable(pauseWindowDuration, bufferPeriodDuration) { _require(tokens.length >= _MIN_TOKENS, Errors.MIN_TOKENS); _require(tokens.length <= _getMaxTokens(), Errors.MAX_TOKENS); // The Vault only requires the token list to be ordered for the Two Token Pools specialization. However, // to make the developer experience consistent, we are requiring this condition for all the native pools. // Also, since these Pools will register tokens only once, we can ensure the Pool tokens will follow the same // order. We rely on this property to make Pools simpler to write, as it lets us assume that the // order of token-specific parameters (such as token weights) will not change. InputHelpers.ensureArrayIsSorted(tokens); _setSwapFeePercentage(swapFeePercentage); bytes32 poolId = vault.registerPool(specialization); vault.registerTokens(poolId, tokens, assetManagers); // Set immutable state variables - these cannot be read from during construction _vault = vault; _poolId = poolId; } // Getters / Setters function getVault() public view returns (IVault) { return _vault; } function getPoolId() public view override returns (bytes32) { return _poolId; } function _getTotalTokens() internal view virtual returns (uint256); function _getMaxTokens() internal pure virtual returns (uint256); function _getMinimumBpt() internal pure virtual returns (uint256) { return _MINIMUM_BPT; } function getSwapFeePercentage() public view returns (uint256) { return _miscData.decodeUint64(_SWAP_FEE_PERCENTAGE_OFFSET); } function setSwapFeePercentage(uint256 swapFeePercentage) external virtual authenticate whenNotPaused { _setSwapFeePercentage(swapFeePercentage); } function _setSwapFeePercentage(uint256 swapFeePercentage) private { _require(swapFeePercentage >= _MIN_SWAP_FEE_PERCENTAGE, Errors.MIN_SWAP_FEE_PERCENTAGE); _require(swapFeePercentage <= _MAX_SWAP_FEE_PERCENTAGE, Errors.MAX_SWAP_FEE_PERCENTAGE); _miscData = _miscData.insertUint64(swapFeePercentage, _SWAP_FEE_PERCENTAGE_OFFSET); emit SwapFeePercentageChanged(swapFeePercentage); } function setAssetManagerPoolConfig(IERC20 token, bytes memory poolConfig) public virtual authenticate whenNotPaused { _setAssetManagerPoolConfig(token, poolConfig); } function _setAssetManagerPoolConfig(IERC20 token, bytes memory poolConfig) private { bytes32 poolId = getPoolId(); (, , , address assetManager) = getVault().getPoolTokenInfo(poolId, token); IAssetManager(assetManager).setConfig(poolId, poolConfig); } function setPaused(bool paused) external authenticate { _setPaused(paused); } function _isOwnerOnlyAction(bytes32 actionId) internal view virtual override returns (bool) { return (actionId == getActionId(this.setSwapFeePercentage.selector)) || (actionId == getActionId(this.setAssetManagerPoolConfig.selector)); } function _getMiscData() internal view returns (bytes32) { return _miscData; } /** * Inserts data into the least-significant 192 bits of the misc data storage slot. * Note that the remaining 64 bits are used for the swap fee percentage and cannot be overloaded. */ function _setMiscData(bytes32 newData) internal { _miscData = _miscData.insertBits192(newData, 0); } // Join / Exit Hooks modifier onlyVault(bytes32 poolId) { _require(msg.sender == address(getVault()), Errors.CALLER_NOT_VAULT); _require(poolId == getPoolId(), Errors.INVALID_POOL_ID); _; } function onJoinPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) public virtual override onlyVault(poolId) returns (uint256[] memory, uint256[] memory) { uint256[] memory scalingFactors = _scalingFactors(); if (totalSupply() == 0) { (uint256 bptAmountOut, uint256[] memory amountsIn) = _onInitializePool( poolId, sender, recipient, scalingFactors, userData ); // On initialization, we lock _getMinimumBpt() by minting it for the zero address. This BPT acts as a // minimum as it will never be burned, which reduces potential issues with rounding, and also prevents the // Pool from ever being fully drained. _require(bptAmountOut >= _getMinimumBpt(), Errors.MINIMUM_BPT); _mintPoolTokens(address(0), _getMinimumBpt()); _mintPoolTokens(recipient, bptAmountOut - _getMinimumBpt()); // amountsIn are amounts entering the Pool, so we round up. _downscaleUpArray(amountsIn, scalingFactors); return (amountsIn, new uint256[](_getTotalTokens())); } else { _upscaleArray(balances, scalingFactors); (uint256 bptAmountOut, uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts) = _onJoinPool( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, scalingFactors, userData ); // Note we no longer use `balances` after calling `_onJoinPool`, which may mutate it. _mintPoolTokens(recipient, bptAmountOut); // amountsIn are amounts entering the Pool, so we round up. _downscaleUpArray(amountsIn, scalingFactors); // dueProtocolFeeAmounts are amounts exiting the Pool, so we round down. _downscaleDownArray(dueProtocolFeeAmounts, scalingFactors); return (amountsIn, dueProtocolFeeAmounts); } } function onExitPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) public virtual override onlyVault(poolId) returns (uint256[] memory, uint256[] memory) { uint256[] memory scalingFactors = _scalingFactors(); _upscaleArray(balances, scalingFactors); (uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts) = _onExitPool( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, scalingFactors, userData ); // Note we no longer use `balances` after calling `_onExitPool`, which may mutate it. _burnPoolTokens(sender, bptAmountIn); // Both amountsOut and dueProtocolFeeAmounts are amounts exiting the Pool, so we round down. _downscaleDownArray(amountsOut, scalingFactors); _downscaleDownArray(dueProtocolFeeAmounts, scalingFactors); return (amountsOut, dueProtocolFeeAmounts); } // Query functions /** * @dev Returns the amount of BPT that would be granted to `recipient` if the `onJoinPool` hook were called by the * Vault with the same arguments, along with the number of tokens `sender` would have to supply. * * This function is not meant to be called directly, but rather from a helper contract that fetches current Vault * data, such as the protocol swap fee percentage and Pool balances. * * Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must * explicitly use eth_call instead of eth_sendTransaction. */ function queryJoin( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256 bptOut, uint256[] memory amountsIn) { InputHelpers.ensureInputLengthMatch(balances.length, _getTotalTokens()); _queryAction( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData, _onJoinPool, _downscaleUpArray ); // The `return` opcode is executed directly inside `_queryAction`, so execution never reaches this statement, // and we don't need to return anything here - it just silences compiler warnings. return (bptOut, amountsIn); } /** * @dev Returns the amount of BPT that would be burned from `sender` if the `onExitPool` hook were called by the * Vault with the same arguments, along with the number of tokens `recipient` would receive. * * This function is not meant to be called directly, but rather from a helper contract that fetches current Vault * data, such as the protocol swap fee percentage and Pool balances. * * Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must * explicitly use eth_call instead of eth_sendTransaction. */ function queryExit( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256 bptIn, uint256[] memory amountsOut) { InputHelpers.ensureInputLengthMatch(balances.length, _getTotalTokens()); _queryAction( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData, _onExitPool, _downscaleDownArray ); // The `return` opcode is executed directly inside `_queryAction`, so execution never reaches this statement, // and we don't need to return anything here - it just silences compiler warnings. return (bptIn, amountsOut); } // Internal hooks to be overridden by derived contracts - all token amounts (except BPT) in these interfaces are // upscaled. /** * @dev Called when the Pool is joined for the first time; that is, when the BPT total supply is zero. * * Returns the amount of BPT to mint, and the token amounts the Pool will receive in return. * * Minted BPT will be sent to `recipient`, except for _getMinimumBpt(), which will be deducted from this amount and * sent to the zero address instead. This will cause that BPT to remain forever locked there, preventing total BTP * from ever dropping below that value, and ensuring `_onInitializePool` can only be called once in the entire * Pool's lifetime. * * The tokens granted to the Pool will be transferred from `sender`. These amounts are considered upscaled and will * be downscaled (rounding up) before being returned to the Vault. */ function _onInitializePool( bytes32 poolId, address sender, address recipient, uint256[] memory scalingFactors, bytes memory userData ) internal virtual returns (uint256 bptAmountOut, uint256[] memory amountsIn); /** * @dev Called whenever the Pool is joined after the first initialization join (see `_onInitializePool`). * * Returns the amount of BPT to mint, the token amounts that the Pool will receive in return, and the number of * tokens to pay in protocol swap fees. * * Implementations of this function might choose to mutate the `balances` array to save gas (e.g. when * performing intermediate calculations, such as subtraction of due protocol fees). This can be done safely. * * Minted BPT will be sent to `recipient`. * * The tokens granted to the Pool will be transferred from `sender`. These amounts are considered upscaled and will * be downscaled (rounding up) before being returned to the Vault. * * Due protocol swap fees will be taken from the Pool's balance in the Vault (see `IBasePool.onJoinPool`). These * amounts are considered upscaled and will be downscaled (rounding down) before being returned to the Vault. */ function _onJoinPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, uint256[] memory scalingFactors, bytes memory userData ) internal virtual returns ( uint256 bptAmountOut, uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts ); /** * @dev Called whenever the Pool is exited. * * Returns the amount of BPT to burn, the token amounts for each Pool token that the Pool will grant in return, and * the number of tokens to pay in protocol swap fees. * * Implementations of this function might choose to mutate the `balances` array to save gas (e.g. when * performing intermediate calculations, such as subtraction of due protocol fees). This can be done safely. * * BPT will be burnt from `sender`. * * The Pool will grant tokens to `recipient`. These amounts are considered upscaled and will be downscaled * (rounding down) before being returned to the Vault. * * Due protocol swap fees will be taken from the Pool's balance in the Vault (see `IBasePool.onExitPool`). These * amounts are considered upscaled and will be downscaled (rounding down) before being returned to the Vault. */ function _onExitPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, uint256[] memory scalingFactors, bytes memory userData ) internal virtual returns ( uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts ); // Internal functions /** * @dev Adds swap fee amount to `amount`, returning a higher value. */ function _addSwapFeeAmount(uint256 amount) internal view returns (uint256) { // This returns amount + fee amount, so we round up (favoring a higher fee amount). return amount.divUp(FixedPoint.ONE.sub(getSwapFeePercentage())); } /** * @dev Subtracts swap fee amount from `amount`, returning a lower value. */ function _subtractSwapFeeAmount(uint256 amount) internal view returns (uint256) { // This returns amount - fee amount, so we round up (favoring a higher fee amount). uint256 feeAmount = amount.mulUp(getSwapFeePercentage()); return amount.sub(feeAmount); } // Scaling /** * @dev Returns a scaling factor that, when multiplied to a token amount for `token`, normalizes its balance as if * it had 18 decimals. */ function _computeScalingFactor(IERC20 token) internal view returns (uint256) { // Tokens that don't implement the `decimals` method are not supported. uint256 tokenDecimals = ERC20(address(token)).decimals(); // Tokens with more than 18 decimals are not supported. uint256 decimalsDifference = Math.sub(18, tokenDecimals); return FixedPoint.ONE * 10**decimalsDifference; } /** * @dev Returns the scaling factor for one of the Pool's tokens. Reverts if `token` is not a token registered by the * Pool. * * All scaling factors are fixed-point values with 18 decimals, to allow for this function to be overridden by * derived contracts that need to apply further scaling, making these factors potentially non-integer. * * The largest 'base' scaling factor (i.e. in tokens with less than 18 decimals) is 10**18, which in fixed-point is * 10**36. This value can be multiplied with a 112 bit Vault balance with no overflow by a factor of ~1e7, making * even relatively 'large' factors safe to use. * * The 1e7 figure is the result of 2**256 / (1e18 * 1e18 * 2**112). */ function _scalingFactor(IERC20 token) internal view virtual returns (uint256); /** * @dev Same as `_scalingFactor()`, except for all registered tokens (in the same order as registered). The Vault * will always pass balances in this order when calling any of the Pool hooks. */ function _scalingFactors() internal view virtual returns (uint256[] memory); function getScalingFactors() external view returns (uint256[] memory) { return _scalingFactors(); } /** * @dev Applies `scalingFactor` to `amount`, resulting in a larger or equal value depending on whether it needed * scaling or not. */ function _upscale(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { // Upscale rounding wouldn't necessarily always go in the same direction: in a swap for example the balance of // token in should be rounded up, and that of token out rounded down. This is the only place where we round in // the same direction for all amounts, as the impact of this rounding is expected to be minimal (and there's no // rounding error unless `_scalingFactor()` is overriden). return FixedPoint.mulDown(amount, scalingFactor); } /** * @dev Same as `_upscale`, but for an entire array. This function does not return anything, but instead *mutates* * the `amounts` array. */ function _upscaleArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view { for (uint256 i = 0; i < _getTotalTokens(); ++i) { amounts[i] = FixedPoint.mulDown(amounts[i], scalingFactors[i]); } } /** * @dev Reverses the `scalingFactor` applied to `amount`, resulting in a smaller or equal value depending on * whether it needed scaling or not. The result is rounded down. */ function _downscaleDown(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { return FixedPoint.divDown(amount, scalingFactor); } /** * @dev Same as `_downscaleDown`, but for an entire array. This function does not return anything, but instead * *mutates* the `amounts` array. */ function _downscaleDownArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view { for (uint256 i = 0; i < _getTotalTokens(); ++i) { amounts[i] = FixedPoint.divDown(amounts[i], scalingFactors[i]); } } /** * @dev Reverses the `scalingFactor` applied to `amount`, resulting in a smaller or equal value depending on * whether it needed scaling or not. The result is rounded up. */ function _downscaleUp(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { return FixedPoint.divUp(amount, scalingFactor); } /** * @dev Same as `_downscaleUp`, but for an entire array. This function does not return anything, but instead * *mutates* the `amounts` array. */ function _downscaleUpArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view { for (uint256 i = 0; i < _getTotalTokens(); ++i) { amounts[i] = FixedPoint.divUp(amounts[i], scalingFactors[i]); } } function _getAuthorizer() internal view override returns (IAuthorizer) { // Access control management is delegated to the Vault's Authorizer. This lets Balancer Governance manage which // accounts can call permissioned functions: for example, to perform emergency pauses. // If the owner is delegated, then *all* permissioned functions, including `setSwapFeePercentage`, will be under // Governance control. return getVault().getAuthorizer(); } function _queryAction( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData, function(bytes32, address, address, uint256[] memory, uint256, uint256, uint256[] memory, bytes memory) internal returns (uint256, uint256[] memory, uint256[] memory) _action, function(uint256[] memory, uint256[] memory) internal view _downscaleArray ) private { // This uses the same technique used by the Vault in queryBatchSwap. Refer to that function for a detailed // explanation. if (msg.sender != address(this)) { // We perform an external call to ourselves, forwarding the same calldata. In this call, the else clause of // the preceding if statement will be executed instead. // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(msg.data); // solhint-disable-next-line no-inline-assembly assembly { // This call should always revert to decode the bpt and token amounts from the revert reason switch success case 0 { // Note we are manually writing the memory slot 0. We can safely overwrite whatever is // stored there as we take full control of the execution and then immediately return. // We copy the first 4 bytes to check if it matches with the expected signature, otherwise // there was another revert reason and we should forward it. returndatacopy(0, 0, 0x04) let error := and(mload(0), 0xffffffff00000000000000000000000000000000000000000000000000000000) // If the first 4 bytes don't match with the expected signature, we forward the revert reason. if eq(eq(error, 0x43adbafb00000000000000000000000000000000000000000000000000000000), 0) { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } // The returndata contains the signature, followed by the raw memory representation of the // `bptAmount` and `tokenAmounts` (array: length + data). We need to return an ABI-encoded // representation of these. // An ABI-encoded response will include one additional field to indicate the starting offset of // the `tokenAmounts` array. The `bptAmount` will be laid out in the first word of the // returndata. // // In returndata: // [ signature ][ bptAmount ][ tokenAmounts length ][ tokenAmounts values ] // [ 4 bytes ][ 32 bytes ][ 32 bytes ][ (32 * length) bytes ] // // We now need to return (ABI-encoded values): // [ bptAmount ][ tokeAmounts offset ][ tokenAmounts length ][ tokenAmounts values ] // [ 32 bytes ][ 32 bytes ][ 32 bytes ][ (32 * length) bytes ] // We copy 32 bytes for the `bptAmount` from returndata into memory. // Note that we skip the first 4 bytes for the error signature returndatacopy(0, 0x04, 32) // The offsets are 32-bytes long, so the array of `tokenAmounts` will start after // the initial 64 bytes. mstore(0x20, 64) // We now copy the raw memory array for the `tokenAmounts` from returndata into memory. // Since bpt amount and offset take up 64 bytes, we start copying at address 0x40. We also // skip the first 36 bytes from returndata, which correspond to the signature plus bpt amount. returndatacopy(0x40, 0x24, sub(returndatasize(), 36)) // We finally return the ABI-encoded uint256 and the array, which has a total length equal to // the size of returndata, plus the 32 bytes of the offset but without the 4 bytes of the // error signature. return(0, add(returndatasize(), 28)) } default { // This call should always revert, but we fail nonetheless if that didn't happen invalid() } } } else { uint256[] memory scalingFactors = _scalingFactors(); _upscaleArray(balances, scalingFactors); (uint256 bptAmount, uint256[] memory tokenAmounts, ) = _action( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, scalingFactors, userData ); _downscaleArray(tokenAmounts, scalingFactors); // solhint-disable-next-line no-inline-assembly assembly { // We will return a raw representation of `bptAmount` and `tokenAmounts` in memory, which is composed of // a 32-byte uint256, followed by a 32-byte for the array length, and finally the 32-byte uint256 values // Because revert expects a size in bytes, we multiply the array length (stored at `tokenAmounts`) by 32 let size := mul(mload(tokenAmounts), 32) // We store the `bptAmount` in the previous slot to the `tokenAmounts` array. We can make sure there // will be at least one available slot due to how the memory scratch space works. // We can safely overwrite whatever is stored in this slot as we will revert immediately after that. let start := sub(tokenAmounts, 0x20) mstore(start, bptAmount) // We send one extra value for the error signature "QueryError(uint256,uint256[])" which is 0x43adbafb // We use the previous slot to `bptAmount`. mstore(sub(start, 0x20), 0x0000000000000000000000000000000000000000000000000000000043adbafb) start := sub(start, 0x04) // When copying from `tokenAmounts` into returndata, we copy the additional 68 bytes to also return // the `bptAmount`, the array 's length, and the error signature. revert(start, add(size, 68)) } } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./IBasePool.sol"; /** * @dev Pool contracts with the MinimalSwapInfo or TwoToken specialization settings should implement this interface. * * This is called by the Vault when a user calls `IVault.swap` or `IVault.batchSwap` to swap with this Pool. * Returns the number of tokens the Pool will grant to the user in a 'given in' swap, or that the user will grant * to the pool in a 'given out' swap. * * This can often be implemented by a `view` function, since many pricing algorithms don't need to track state * changes in swaps. However, contracts implementing this in non-view functions should check that the caller is * indeed the Vault. */ interface IMinimalSwapInfoPool is IBasePool { function onSwap( SwapRequest memory swapRequest, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut ) external returns (uint256 amount); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow checks. * Adapted from OpenZeppelin's SafeMath library */ library Math { /** * @dev Returns the addition of two unsigned integers of 256 bits, reverting on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; _require(c >= a, Errors.ADD_OVERFLOW); return c; } /** * @dev Returns the addition of two signed integers, reverting on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; _require((b >= 0 && c >= a) || (b < 0 && c < a), Errors.ADD_OVERFLOW); return c; } /** * @dev Returns the subtraction of two unsigned integers of 256 bits, reverting on overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { _require(b <= a, Errors.SUB_OVERFLOW); uint256 c = a - b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; _require((b >= 0 && c <= a) || (b < 0 && c > a), Errors.SUB_OVERFLOW); return c; } /** * @dev Returns the largest of two numbers of 256 bits. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers of 256 bits. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; _require(a == 0 || c / a == b, Errors.MUL_OVERFLOW); return c; } function div( uint256 a, uint256 b, bool roundUp ) internal pure returns (uint256) { return roundUp ? divUp(a, b) : divDown(a, b); } function divDown(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); return a / b; } function divUp(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); if (a == 0) { return 0; } else { return 1 + (a - 1) / b; } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "./BalancerErrors.sol"; import "./ITemporarilyPausable.sol"; /** * @dev Allows for a contract to be paused during an initial period after deployment, disabling functionality. Can be * used as an emergency switch in case a security vulnerability or threat is identified. * * The contract can only be paused during the Pause Window, a period that starts at deployment. It can also be * unpaused and repaused any number of times during this period. This is intended to serve as a safety measure: it lets * system managers react quickly to potentially dangerous situations, knowing that this action is reversible if careful * analysis later determines there was a false alarm. * * If the contract is paused when the Pause Window finishes, it will remain in the paused state through an additional * Buffer Period, after which it will be automatically unpaused forever. This is to ensure there is always enough time * to react to an emergency, even if the threat is discovered shortly before the Pause Window expires. * * Note that since the contract can only be paused within the Pause Window, unpausing during the Buffer Period is * irreversible. */ abstract contract TemporarilyPausable is ITemporarilyPausable { // The Pause Window and Buffer Period are timestamp-based: they should not be relied upon for sub-minute accuracy. // solhint-disable not-rely-on-time uint256 private constant _MAX_PAUSE_WINDOW_DURATION = 90 days; uint256 private constant _MAX_BUFFER_PERIOD_DURATION = 30 days; uint256 private immutable _pauseWindowEndTime; uint256 private immutable _bufferPeriodEndTime; bool private _paused; constructor(uint256 pauseWindowDuration, uint256 bufferPeriodDuration) { _require(pauseWindowDuration <= _MAX_PAUSE_WINDOW_DURATION, Errors.MAX_PAUSE_WINDOW_DURATION); _require(bufferPeriodDuration <= _MAX_BUFFER_PERIOD_DURATION, Errors.MAX_BUFFER_PERIOD_DURATION); uint256 pauseWindowEndTime = block.timestamp + pauseWindowDuration; _pauseWindowEndTime = pauseWindowEndTime; _bufferPeriodEndTime = pauseWindowEndTime + bufferPeriodDuration; } /** * @dev Reverts if the contract is paused. */ modifier whenNotPaused() { _ensureNotPaused(); _; } /** * @dev Returns the current contract pause status, as well as the end times of the Pause Window and Buffer * Period. */ function getPausedState() external view override returns ( bool paused, uint256 pauseWindowEndTime, uint256 bufferPeriodEndTime ) { paused = !_isNotPaused(); pauseWindowEndTime = _getPauseWindowEndTime(); bufferPeriodEndTime = _getBufferPeriodEndTime(); } /** * @dev Sets the pause state to `paused`. The contract can only be paused until the end of the Pause Window, and * unpaused until the end of the Buffer Period. * * Once the Buffer Period expires, this function reverts unconditionally. */ function _setPaused(bool paused) internal { if (paused) { _require(block.timestamp < _getPauseWindowEndTime(), Errors.PAUSE_WINDOW_EXPIRED); } else { _require(block.timestamp < _getBufferPeriodEndTime(), Errors.BUFFER_PERIOD_EXPIRED); } _paused = paused; emit PausedStateChanged(paused); } /** * @dev Reverts if the contract is paused. */ function _ensureNotPaused() internal view { _require(_isNotPaused(), Errors.PAUSED); } /** * @dev Returns true if the contract is unpaused. * * Once the Buffer Period expires, the gas cost of calling this function is reduced dramatically, as storage is no * longer accessed. */ function _isNotPaused() internal view returns (bool) { // After the Buffer Period, the (inexpensive) timestamp check short-circuits the storage access. return block.timestamp > _getBufferPeriodEndTime() || !_paused; } // These getters lead to reduced bytecode size by inlining the immutable variables in a single place. function _getPauseWindowEndTime() private view returns (uint256) { return _pauseWindowEndTime; } function _getBufferPeriodEndTime() private view returns (uint256) { return _bufferPeriodEndTime; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev Library for encoding and decoding values stored inside a 256 bit word. Typically used to pack multiple values in * a single storage slot, saving gas by performing less storage accesses. * * Each value is defined by its size and the least significant bit in the word, also known as offset. For example, two * 128 bit values may be encoded in a word by assigning one an offset of 0, and the other an offset of 128. */ library WordCodec { // Masks are values with the least significant N bits set. They can be used to extract an encoded value from a word, // or to insert a new one replacing the old. uint256 private constant _MASK_1 = 2**(1) - 1; uint256 private constant _MASK_5 = 2**(5) - 1; uint256 private constant _MASK_7 = 2**(7) - 1; uint256 private constant _MASK_10 = 2**(10) - 1; uint256 private constant _MASK_16 = 2**(16) - 1; uint256 private constant _MASK_22 = 2**(22) - 1; uint256 private constant _MASK_31 = 2**(31) - 1; uint256 private constant _MASK_32 = 2**(32) - 1; uint256 private constant _MASK_53 = 2**(53) - 1; uint256 private constant _MASK_64 = 2**(64) - 1; uint256 private constant _MASK_128 = 2**(128) - 1; uint256 private constant _MASK_192 = 2**(192) - 1; // Largest positive values that can be represented as N bits signed integers. int256 private constant _MAX_INT_22 = 2**(21) - 1; int256 private constant _MAX_INT_53 = 2**(52) - 1; // In-place insertion /** * @dev Inserts a boolean value shifted by an offset into a 256 bit word, replacing the old value. Returns the new * word. */ function insertBool( bytes32 word, bool value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_1 << offset)); return clearedWord | bytes32(uint256(value ? 1 : 0) << offset); } // Unsigned /** * @dev Inserts a 5 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` only uses its least significant 5 bits, otherwise it may overwrite sibling bytes. */ function insertUint5( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_5 << offset)); return clearedWord | bytes32(value << offset); } /** * @dev Inserts a 7 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` only uses its least significant 7 bits, otherwise it may overwrite sibling bytes. */ function insertUint7( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_7 << offset)); return clearedWord | bytes32(value << offset); } /** * @dev Inserts a 10 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` only uses its least significant 10 bits, otherwise it may overwrite sibling bytes. */ function insertUint10( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_10 << offset)); return clearedWord | bytes32(value << offset); } /** * @dev Inserts a 16 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. * Returns the new word. * * Assumes `value` only uses its least significant 16 bits, otherwise it may overwrite sibling bytes. */ function insertUint16( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_16 << offset)); return clearedWord | bytes32(value << offset); } /** * @dev Inserts a 31 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` can be represented using 31 bits. */ function insertUint31( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_31 << offset)); return clearedWord | bytes32(value << offset); } /** * @dev Inserts a 32 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` only uses its least significant 32 bits, otherwise it may overwrite sibling bytes. */ function insertUint32( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_32 << offset)); return clearedWord | bytes32(value << offset); } /** * @dev Inserts a 64 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` only uses its least significant 64 bits, otherwise it may overwrite sibling bytes. */ function insertUint64( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_64 << offset)); return clearedWord | bytes32(value << offset); } // Signed /** * @dev Inserts a 22 bits signed integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` can be represented using 22 bits. */ function insertInt22( bytes32 word, int256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_22 << offset)); // Integer values need masking to remove the upper bits of negative values. return clearedWord | bytes32((uint256(value) & _MASK_22) << offset); } // Bytes /** * @dev Inserts 192 bit shifted by an offset into a 256 bit word, replacing the old value. Returns the new word. * * Assumes `value` can be represented using 192 bits. */ function insertBits192( bytes32 word, bytes32 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_192 << offset)); return clearedWord | bytes32((uint256(value) & _MASK_192) << offset); } // Encoding // Unsigned /** * @dev Encodes an unsigned integer shifted by an offset. This performs no size checks: it is up to the caller to * ensure that the values are bounded. * * The return value can be logically ORed with other encoded values to form a 256 bit word. */ function encodeUint(uint256 value, uint256 offset) internal pure returns (bytes32) { return bytes32(value << offset); } // Signed /** * @dev Encodes a 22 bits signed integer shifted by an offset. * * The return value can be logically ORed with other encoded values to form a 256 bit word. */ function encodeInt22(int256 value, uint256 offset) internal pure returns (bytes32) { // Integer values need masking to remove the upper bits of negative values. return bytes32((uint256(value) & _MASK_22) << offset); } /** * @dev Encodes a 53 bits signed integer shifted by an offset. * * The return value can be logically ORed with other encoded values to form a 256 bit word. */ function encodeInt53(int256 value, uint256 offset) internal pure returns (bytes32) { // Integer values need masking to remove the upper bits of negative values. return bytes32((uint256(value) & _MASK_53) << offset); } // Decoding /** * @dev Decodes and returns a boolean shifted by an offset from a 256 bit word. */ function decodeBool(bytes32 word, uint256 offset) internal pure returns (bool) { return (uint256(word >> offset) & _MASK_1) == 1; } // Unsigned /** * @dev Decodes and returns a 5 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint5(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_5; } /** * @dev Decodes and returns a 7 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint7(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_7; } /** * @dev Decodes and returns a 10 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint10(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_10; } /** * @dev Decodes and returns a 16 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint16(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_16; } /** * @dev Decodes and returns a 31 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint31(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_31; } /** * @dev Decodes and returns a 32 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint32(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_32; } /** * @dev Decodes and returns a 64 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint64(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_64; } /** * @dev Decodes and returns a 128 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint128(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_128; } // Signed /** * @dev Decodes and returns a 22 bits signed integer shifted by an offset from a 256 bit word. */ function decodeInt22(bytes32 word, uint256 offset) internal pure returns (int256) { int256 value = int256(uint256(word >> offset) & _MASK_22); // In case the decoded value is greater than the max positive integer that can be represented with 22 bits, // we know it was originally a negative integer. Therefore, we mask it to restore the sign in the 256 bit // representation. return value > _MAX_INT_22 ? (value | int256(~_MASK_22)) : value; } /** * @dev Decodes and returns a 53 bits signed integer shifted by an offset from a 256 bit word. */ function decodeInt53(bytes32 word, uint256 offset) internal pure returns (int256) { int256 value = int256(uint256(word >> offset) & _MASK_53); // In case the decoded value is greater than the max positive integer that can be represented with 53 bits, // we know it was originally a negative integer. Therefore, we mask it to restore the sign in the 256 bit // representation. return value > _MAX_INT_53 ? (value | int256(~_MASK_53)) : value; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; import "./IERC20.sol"; import "./SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @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. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * 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 See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view 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(msg.sender, 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(msg.sender, 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); _approve( sender, msg.sender, _allowances[sender][msg.sender].sub(amount, Errors.ERC20_TRANSFER_EXCEEDS_ALLOWANCE) ); 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(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 virtual returns (bool) { _approve( msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, Errors.ERC20_DECREASED_ALLOWANCE_BELOW_ZERO) ); 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 virtual { _require(sender != address(0), Errors.ERC20_TRANSFER_FROM_ZERO_ADDRESS); _require(recipient != address(0), Errors.ERC20_TRANSFER_TO_ZERO_ADDRESS); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, Errors.ERC20_TRANSFER_EXCEEDS_BALANCE); _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 virtual { _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(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), Errors.ERC20_BURN_FROM_ZERO_ADDRESS); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, Errors.ERC20_BURN_EXCEEDS_ALLOWANCE); _totalSupply = _totalSupply.sub(amount); emit Transfer(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 { _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @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 to 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 {} } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/ISignaturesValidator.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/ITemporarilyPausable.sol"; import "@balancer-labs/v2-solidity-utils/contracts/misc/IWETH.sol"; import "./IAsset.sol"; import "./IAuthorizer.sol"; import "./IFlashLoanRecipient.sol"; import "./IProtocolFeesCollector.sol"; pragma solidity ^0.7.0; /** * @dev Full external interface for the Vault core contract - no external or public methods exist in the contract that * don't override one of these declarations. */ interface IVault is ISignaturesValidator, ITemporarilyPausable { // Generalities about the Vault: // // - Whenever documentation refers to 'tokens', it strictly refers to ERC20-compliant token contracts. Tokens are // transferred out of the Vault by calling the `IERC20.transfer` function, and transferred in by calling // `IERC20.transferFrom`. In these cases, the sender must have previously allowed the Vault to use their tokens by // calling `IERC20.approve`. The only deviation from the ERC20 standard that is supported is functions not returning // a boolean value: in these scenarios, a non-reverting call is assumed to be successful. // // - All non-view functions in the Vault are non-reentrant: calling them while another one is mid-execution (e.g. // while execution control is transferred to a token contract during a swap) will result in a revert. View // functions can be called in a re-reentrant way, but doing so might cause them to return inconsistent results. // Contracts calling view functions in the Vault must make sure the Vault has not already been entered. // // - View functions revert if referring to either unregistered Pools, or unregistered tokens for registered Pools. // Authorizer // // Some system actions are permissioned, like setting and collecting protocol fees. This permissioning system exists // outside of the Vault in the Authorizer contract: the Vault simply calls the Authorizer to check if the caller // can perform a given action. /** * @dev Returns the Vault's Authorizer. */ function getAuthorizer() external view returns (IAuthorizer); /** * @dev Sets a new Authorizer for the Vault. The caller must be allowed by the current Authorizer to do this. * * Emits an `AuthorizerChanged` event. */ function setAuthorizer(IAuthorizer newAuthorizer) external; /** * @dev Emitted when a new authorizer is set by `setAuthorizer`. */ event AuthorizerChanged(IAuthorizer indexed newAuthorizer); // Relayers // // Additionally, it is possible for an account to perform certain actions on behalf of another one, using their // Vault ERC20 allowance and Internal Balance. These accounts are said to be 'relayers' for these Vault functions, // and are expected to be smart contracts with sound authentication mechanisms. For an account to be able to wield // this power, two things must occur: // - The Authorizer must grant the account the permission to be a relayer for the relevant Vault function. This // means that Balancer governance must approve each individual contract to act as a relayer for the intended // functions. // - Each user must approve the relayer to act on their behalf. // This double protection means users cannot be tricked into approving malicious relayers (because they will not // have been allowed by the Authorizer via governance), nor can malicious relayers approved by a compromised // Authorizer or governance drain user funds, since they would also need to be approved by each individual user. /** * @dev Returns true if `user` has approved `relayer` to act as a relayer for them. */ function hasApprovedRelayer(address user, address relayer) external view returns (bool); /** * @dev Allows `relayer` to act as a relayer for `sender` if `approved` is true, and disallows it otherwise. * * Emits a `RelayerApprovalChanged` event. */ function setRelayerApproval( address sender, address relayer, bool approved ) external; /** * @dev Emitted every time a relayer is approved or disapproved by `setRelayerApproval`. */ event RelayerApprovalChanged(address indexed relayer, address indexed sender, bool approved); // Internal Balance // // Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later // transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination // when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced // gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users. // // Internal Balance management features batching, which means a single contract call can be used to perform multiple // operations of different kinds, with different senders and recipients, at once. /** * @dev Returns `user`'s Internal Balance for a set of tokens. */ function getInternalBalance(address user, IERC20[] memory tokens) external view returns (uint256[] memory); /** * @dev Performs a set of user balance operations, which involve Internal Balance (deposit, withdraw or transfer) * and plain ERC20 transfers using the Vault's allowance. This last feature is particularly useful for relayers, as * it lets integrators reuse a user's Vault allowance. * * For each operation, if the caller is not `sender`, it must be an authorized relayer for them. */ function manageUserBalance(UserBalanceOp[] memory ops) external payable; /** * @dev Data for `manageUserBalance` operations, which include the possibility for ETH to be sent and received without manual WETH wrapping or unwrapping. */ struct UserBalanceOp { UserBalanceOpKind kind; IAsset asset; uint256 amount; address sender; address payable recipient; } // There are four possible operations in `manageUserBalance`: // // - DEPOSIT_INTERNAL // Increases the Internal Balance of the `recipient` account by transferring tokens from the corresponding // `sender`. The sender must have allowed the Vault to use their tokens via `IERC20.approve()`. // // ETH can be used by passing the ETH sentinel value as the asset and forwarding ETH in the call: it will be wrapped // and deposited as WETH. Any ETH amount remaining will be sent back to the caller (not the sender, which is // relevant for relayers). // // Emits an `InternalBalanceChanged` event. // // // - WITHDRAW_INTERNAL // Decreases the Internal Balance of the `sender` account by transferring tokens to the `recipient`. // // ETH can be used by passing the ETH sentinel value as the asset. This will deduct WETH instead, unwrap it and send // it to the recipient as ETH. // // Emits an `InternalBalanceChanged` event. // // // - TRANSFER_INTERNAL // Transfers tokens from the Internal Balance of the `sender` account to the Internal Balance of `recipient`. // // Reverts if the ETH sentinel value is passed. // // Emits an `InternalBalanceChanged` event. // // // - TRANSFER_EXTERNAL // Transfers tokens from `sender` to `recipient`, using the Vault's ERC20 allowance. This is typically used by // relayers, as it lets them reuse a user's Vault allowance. // // Reverts if the ETH sentinel value is passed. // // Emits an `ExternalBalanceTransfer` event. enum UserBalanceOpKind { DEPOSIT_INTERNAL, WITHDRAW_INTERNAL, TRANSFER_INTERNAL, TRANSFER_EXTERNAL } /** * @dev Emitted when a user's Internal Balance changes, either from calls to `manageUserBalance`, or through * interacting with Pools using Internal Balance. * * Because Internal Balance works exclusively with ERC20 tokens, ETH deposits and withdrawals will use the WETH * address. */ event InternalBalanceChanged(address indexed user, IERC20 indexed token, int256 delta); /** * @dev Emitted when a user's Vault ERC20 allowance is used by the Vault to transfer tokens to an external account. */ event ExternalBalanceTransfer(IERC20 indexed token, address indexed sender, address recipient, uint256 amount); // Pools // // There are three specialization settings for Pools, which allow for cheaper swaps at the cost of reduced // functionality: // // - General: no specialization, suited for all Pools. IGeneralPool is used for swap request callbacks, passing the // balance of all tokens in the Pool. These Pools have the largest swap costs (because of the extra storage reads), // which increase with the number of registered tokens. // // - Minimal Swap Info: IMinimalSwapInfoPool is used instead of IGeneralPool, which saves gas by only passing the // balance of the two tokens involved in the swap. This is suitable for some pricing algorithms, like the weighted // constant product one popularized by Balancer V1. Swap costs are smaller compared to general Pools, and are // independent of the number of registered tokens. // // - Two Token: only allows two tokens to be registered. This achieves the lowest possible swap gas cost. Like // minimal swap info Pools, these are called via IMinimalSwapInfoPool. enum PoolSpecialization { GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN } /** * @dev Registers the caller account as a Pool with a given specialization setting. Returns the Pool's ID, which * is used in all Pool-related functions. Pools cannot be deregistered, nor can the Pool's specialization be * changed. * * The caller is expected to be a smart contract that implements either `IGeneralPool` or `IMinimalSwapInfoPool`, * depending on the chosen specialization setting. This contract is known as the Pool's contract. * * Note that the same contract may register itself as multiple Pools with unique Pool IDs, or in other words, * multiple Pools may share the same contract. * * Emits a `PoolRegistered` event. */ function registerPool(PoolSpecialization specialization) external returns (bytes32); /** * @dev Emitted when a Pool is registered by calling `registerPool`. */ event PoolRegistered(bytes32 indexed poolId, address indexed poolAddress, PoolSpecialization specialization); /** * @dev Returns a Pool's contract address and specialization setting. */ function getPool(bytes32 poolId) external view returns (address, PoolSpecialization); /** * @dev Registers `tokens` for the `poolId` Pool. Must be called by the Pool's contract. * * Pools can only interact with tokens they have registered. Users join a Pool by transferring registered tokens, * exit by receiving registered tokens, and can only swap registered tokens. * * Each token can only be registered once. For Pools with the Two Token specialization, `tokens` must have a length * of two, that is, both tokens must be registered in the same `registerTokens` call, and they must be sorted in * ascending order. * * The `tokens` and `assetManagers` arrays must have the same length, and each entry in these indicates the Asset * Manager for the corresponding token. Asset Managers can manage a Pool's tokens via `managePoolBalance`, * depositing and withdrawing them directly, and can even set their balance to arbitrary amounts. They are therefore * expected to be highly secured smart contracts with sound design principles, and the decision to register an * Asset Manager should not be made lightly. * * Pools can choose not to assign an Asset Manager to a given token by passing in the zero address. Once an Asset * Manager is set, it cannot be changed except by deregistering the associated token and registering again with a * different Asset Manager. * * Emits a `TokensRegistered` event. */ function registerTokens( bytes32 poolId, IERC20[] memory tokens, address[] memory assetManagers ) external; /** * @dev Emitted when a Pool registers tokens by calling `registerTokens`. */ event TokensRegistered(bytes32 indexed poolId, IERC20[] tokens, address[] assetManagers); /** * @dev Deregisters `tokens` for the `poolId` Pool. Must be called by the Pool's contract. * * Only registered tokens (via `registerTokens`) can be deregistered. Additionally, they must have zero total * balance. For Pools with the Two Token specialization, `tokens` must have a length of two, that is, both tokens * must be deregistered in the same `deregisterTokens` call. * * A deregistered token can be re-registered later on, possibly with a different Asset Manager. * * Emits a `TokensDeregistered` event. */ function deregisterTokens(bytes32 poolId, IERC20[] memory tokens) external; /** * @dev Emitted when a Pool deregisters tokens by calling `deregisterTokens`. */ event TokensDeregistered(bytes32 indexed poolId, IERC20[] tokens); /** * @dev Returns detailed information for a Pool's registered token. * * `cash` is the number of tokens the Vault currently holds for the Pool. `managed` is the number of tokens * withdrawn and held outside the Vault by the Pool's token Asset Manager. The Pool's total balance for `token` * equals the sum of `cash` and `managed`. * * Internally, `cash` and `managed` are stored using 112 bits. No action can ever cause a Pool's token `cash`, * `managed` or `total` balance to be greater than 2^112 - 1. * * `lastChangeBlock` is the number of the block in which `token`'s total balance was last modified (via either a * join, exit, swap, or Asset Manager update). This value is useful to avoid so-called 'sandwich attacks', for * example when developing price oracles. A change of zero (e.g. caused by a swap with amount zero) is considered a * change for this purpose, and will update `lastChangeBlock`. * * `assetManager` is the Pool's token Asset Manager. */ function getPoolTokenInfo(bytes32 poolId, IERC20 token) external view returns ( uint256 cash, uint256 managed, uint256 lastChangeBlock, address assetManager ); /** * @dev Returns a Pool's registered tokens, the total balance for each, and the latest block when *any* of * the tokens' `balances` changed. * * The order of the `tokens` array is the same order that will be used in `joinPool`, `exitPool`, as well as in all * Pool hooks (where applicable). Calls to `registerTokens` and `deregisterTokens` may change this order. * * If a Pool only registers tokens once, and these are sorted in ascending order, they will be stored in the same * order as passed to `registerTokens`. * * Total balances include both tokens held by the Vault and those withdrawn by the Pool's Asset Managers. These are * the amounts used by joins, exits and swaps. For a detailed breakdown of token balances, use `getPoolTokenInfo` * instead. */ function getPoolTokens(bytes32 poolId) external view returns ( IERC20[] memory tokens, uint256[] memory balances, uint256 lastChangeBlock ); /** * @dev Called by users to join a Pool, which transfers tokens from `sender` into the Pool's balance. This will * trigger custom Pool behavior, which will typically grant something in return to `recipient` - often tokenized * Pool shares. * * If the caller is not `sender`, it must be an authorized relayer for them. * * The `assets` and `maxAmountsIn` arrays must have the same length, and each entry indicates the maximum amount * to send for each asset. The amounts to send are decided by the Pool and not the Vault: it just enforces * these maximums. * * If joining a Pool that holds WETH, it is possible to send ETH directly: the Vault will do the wrapping. To enable * this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead of the * WETH address. Note that it is not possible to combine ETH and WETH in the same join. Any excess ETH will be sent * back to the caller (not the sender, which is important for relayers). * * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when * interacting with Pools that register and deregister tokens frequently. If sending ETH however, the array must be * sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the final * `assets` array might not be sorted. Pools with no registered tokens cannot be joined. * * If `fromInternalBalance` is true, the caller's Internal Balance will be preferred: ERC20 transfers will only * be made for the difference between the requested amount and Internal Balance (if any). Note that ETH cannot be * withdrawn from Internal Balance: attempting to do so will trigger a revert. * * This causes the Vault to call the `IBasePool.onJoinPool` hook on the Pool's contract, where Pools implement * their own custom logic. This typically requires additional information from the user (such as the expected number * of Pool shares). This can be encoded in the `userData` argument, which is ignored by the Vault and passed * directly to the Pool's contract, as is `recipient`. * * Emits a `PoolBalanceChanged` event. */ function joinPool( bytes32 poolId, address sender, address recipient, JoinPoolRequest memory request ) external payable; struct JoinPoolRequest { IAsset[] assets; uint256[] maxAmountsIn; bytes userData; bool fromInternalBalance; } /** * @dev Called by users to exit a Pool, which transfers tokens from the Pool's balance to `recipient`. This will * trigger custom Pool behavior, which will typically ask for something in return from `sender` - often tokenized * Pool shares. The amount of tokens that can be withdrawn is limited by the Pool's `cash` balance (see * `getPoolTokenInfo`). * * If the caller is not `sender`, it must be an authorized relayer for them. * * The `tokens` and `minAmountsOut` arrays must have the same length, and each entry in these indicates the minimum * token amount to receive for each token contract. The amounts to send are decided by the Pool and not the Vault: * it just enforces these minimums. * * If exiting a Pool that holds WETH, it is possible to receive ETH directly: the Vault will do the unwrapping. To * enable this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead * of the WETH address. Note that it is not possible to combine ETH and WETH in the same exit. * * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when * interacting with Pools that register and deregister tokens frequently. If receiving ETH however, the array must * be sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the * final `assets` array might not be sorted. Pools with no registered tokens cannot be exited. * * If `toInternalBalance` is true, the tokens will be deposited to `recipient`'s Internal Balance. Otherwise, * an ERC20 transfer will be performed. Note that ETH cannot be deposited to Internal Balance: attempting to * do so will trigger a revert. * * `minAmountsOut` is the minimum amount of tokens the user expects to get out of the Pool, for each token in the * `tokens` array. This array must match the Pool's registered tokens. * * This causes the Vault to call the `IBasePool.onExitPool` hook on the Pool's contract, where Pools implement * their own custom logic. This typically requires additional information from the user (such as the expected number * of Pool shares to return). This can be encoded in the `userData` argument, which is ignored by the Vault and * passed directly to the Pool's contract. * * Emits a `PoolBalanceChanged` event. */ function exitPool( bytes32 poolId, address sender, address payable recipient, ExitPoolRequest memory request ) external; struct ExitPoolRequest { IAsset[] assets; uint256[] minAmountsOut; bytes userData; bool toInternalBalance; } /** * @dev Emitted when a user joins or exits a Pool by calling `joinPool` or `exitPool`, respectively. */ event PoolBalanceChanged( bytes32 indexed poolId, address indexed liquidityProvider, IERC20[] tokens, int256[] deltas, uint256[] protocolFeeAmounts ); enum PoolBalanceChangeKind { JOIN, EXIT } // Swaps // // Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. To do this, // they need not trust Pool contracts in any way: all security checks are made by the Vault. They must however be // aware of the Pools' pricing algorithms in order to estimate the prices Pools will quote. // // The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence. // In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'), // and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out'). // More complex swaps, such as one token in to multiple tokens out can be achieved by batching together // individual swaps. // // There are two swap kinds: // - 'given in' swaps, where the amount of tokens in (sent to the Pool) is known, and the Pool determines (via the // `onSwap` hook) the amount of tokens out (to send to the recipient). // - 'given out' swaps, where the amount of tokens out (received from the Pool) is known, and the Pool determines // (via the `onSwap` hook) the amount of tokens in (to receive from the sender). // // Additionally, it is possible to chain swaps using a placeholder input amount, which the Vault replaces with // the calculated output of the previous swap. If the previous swap was 'given in', this will be the calculated // tokenOut amount. If the previous swap was 'given out', it will use the calculated tokenIn amount. These extended // swaps are known as 'multihop' swaps, since they 'hop' through a number of intermediate tokens before arriving at // the final intended token. // // In all cases, tokens are only transferred in and out of the Vault (or withdrawn from and deposited into Internal // Balance) after all individual swaps have been completed, and the net token balance change computed. This makes // certain swap patterns, such as multihops, or swaps that interact with the same token pair in multiple Pools, cost // much less gas than they would otherwise. // // It also means that under certain conditions it is possible to perform arbitrage by swapping with multiple // Pools in a way that results in net token movement out of the Vault (profit), with no tokens being sent in (only // updating the Pool's internal accounting). // // To protect users from front-running or the market changing rapidly, they supply a list of 'limits' for each token // involved in the swap, where either the maximum number of tokens to send (by passing a positive value) or the // minimum amount of tokens to receive (by passing a negative value) is specified. // // Additionally, a 'deadline' timestamp can also be provided, forcing the swap to fail if it occurs after // this point in time (e.g. if the transaction failed to be included in a block promptly). // // If interacting with Pools that hold WETH, it is possible to both send and receive ETH directly: the Vault will do // the wrapping and unwrapping. To enable this mechanism, the IAsset sentinel value (the zero address) must be // passed in the `assets` array instead of the WETH address. Note that it is possible to combine ETH and WETH in the // same swap. Any excess ETH will be sent back to the caller (not the sender, which is relevant for relayers). // // Finally, Internal Balance can be used when either sending or receiving tokens. enum SwapKind { GIVEN_IN, GIVEN_OUT } /** * @dev Performs a swap with a single Pool. * * If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens * taken from the Pool, which must be greater than or equal to `limit`. * * If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens * sent to the Pool, which must be less than or equal to `limit`. * * Internal Balance usage and the recipient are determined by the `funds` struct. * * Emits a `Swap` event. */ function swap( SingleSwap memory singleSwap, FundManagement memory funds, uint256 limit, uint256 deadline ) external payable returns (uint256); /** * @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on * the `kind` value. * * `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address). * Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault. * * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be * used to extend swap behavior. */ struct SingleSwap { bytes32 poolId; SwapKind kind; IAsset assetIn; IAsset assetOut; uint256 amount; bytes userData; } /** * @dev Performs a series of swaps with one or multiple Pools. In each individual swap, the caller determines either * the amount of tokens sent to or received from the Pool, depending on the `kind` value. * * Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the * Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at * the same index in the `assets` array. * * Swaps are executed sequentially, in the order specified by the `swaps` array. Each array element describes a * Pool, the token to be sent to this Pool, the token to receive from it, and an amount that is either `amountIn` or * `amountOut` depending on the swap kind. * * Multihop swaps can be executed by passing an `amount` value of zero for a swap. This will cause the amount in/out * of the previous swap to be used as the amount in for the current one. In a 'given in' swap, 'tokenIn' must equal * the previous swap's `tokenOut`. For a 'given out' swap, `tokenOut` must equal the previous swap's `tokenIn`. * * The `assets` array contains the addresses of all assets involved in the swaps. These are either token addresses, * or the IAsset sentinel value for ETH (the zero address). Each entry in the `swaps` array specifies tokens in and * out by referencing an index in `assets`. Note that Pools never interact with ETH directly: it will be wrapped to * or unwrapped from WETH by the Vault. * * Internal Balance usage, sender, and recipient are determined by the `funds` struct. The `limits` array specifies * the minimum or maximum amount of each token the vault is allowed to transfer. * * `batchSwap` can be used to make a single swap, like `swap` does, but doing so requires more gas than the * equivalent `swap` call. * * Emits `Swap` events. */ function batchSwap( SwapKind kind, BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds, int256[] memory limits, uint256 deadline ) external payable returns (int256[] memory); /** * @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the * `assets` array passed to that function, and ETH assets are converted to WETH. * * If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out * from the previous swap, depending on the swap kind. * * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be * used to extend swap behavior. */ struct BatchSwapStep { bytes32 poolId; uint256 assetInIndex; uint256 assetOutIndex; uint256 amount; bytes userData; } /** * @dev Emitted for each individual swap performed by `swap` or `batchSwap`. */ event Swap( bytes32 indexed poolId, IERC20 indexed tokenIn, IERC20 indexed tokenOut, uint256 amountIn, uint256 amountOut ); /** * @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the * `recipient` account. * * If the caller is not `sender`, it must be an authorized relayer for them. * * If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20 * transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender` * must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of * `joinPool`. * * If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of * transferred. This matches the behavior of `exitPool`. * * Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a * revert. */ struct FundManagement { address sender; bool fromInternalBalance; address payable recipient; bool toInternalBalance; } /** * @dev Simulates a call to `batchSwap`, returning an array of Vault asset deltas. Calls to `swap` cannot be * simulated directly, but an equivalent `batchSwap` call can and will yield the exact same result. * * Each element in the array corresponds to the asset at the same index, and indicates the number of tokens (or ETH) * the Vault would take from the sender (if positive) or send to the recipient (if negative). The arguments it * receives are the same that an equivalent `batchSwap` call would receive. * * Unlike `batchSwap`, this function performs no checks on the sender or recipient field in the `funds` struct. * This makes it suitable to be called by off-chain applications via eth_call without needing to hold tokens, * approve them for the Vault, or even know a user's address. * * Note that this function is not 'view' (due to implementation details): the client code must explicitly execute * eth_call instead of eth_sendTransaction. */ function queryBatchSwap( SwapKind kind, BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds ) external returns (int256[] memory assetDeltas); // Flash Loans /** * @dev Performs a 'flash loan', sending tokens to `recipient`, executing the `receiveFlashLoan` hook on it, * and then reverting unless the tokens plus a proportional protocol fee have been returned. * * The `tokens` and `amounts` arrays must have the same length, and each entry in these indicates the loan amount * for each token contract. `tokens` must be sorted in ascending order. * * The 'userData' field is ignored by the Vault, and forwarded as-is to `recipient` as part of the * `receiveFlashLoan` call. * * Emits `FlashLoan` events. */ function flashLoan( IFlashLoanRecipient recipient, IERC20[] memory tokens, uint256[] memory amounts, bytes memory userData ) external; /** * @dev Emitted for each individual flash loan performed by `flashLoan`. */ event FlashLoan(IFlashLoanRecipient indexed recipient, IERC20 indexed token, uint256 amount, uint256 feeAmount); // Asset Management // // Each token registered for a Pool can be assigned an Asset Manager, which is able to freely withdraw the Pool's // tokens from the Vault, deposit them, or assign arbitrary values to its `managed` balance (see // `getPoolTokenInfo`). This makes them extremely powerful and dangerous. Even if an Asset Manager only directly // controls one of the tokens in a Pool, a malicious manager could set that token's balance to manipulate the // prices of the other tokens, and then drain the Pool with swaps. The risk of using Asset Managers is therefore // not constrained to the tokens they are managing, but extends to the entire Pool's holdings. // // However, a properly designed Asset Manager smart contract can be safely used for the Pool's benefit, // for example by lending unused tokens out for interest, or using them to participate in voting protocols. // // This concept is unrelated to the IAsset interface. /** * @dev Performs a set of Pool balance operations, which may be either withdrawals, deposits or updates. * * Pool Balance management features batching, which means a single contract call can be used to perform multiple * operations of different kinds, with different Pools and tokens, at once. * * For each operation, the caller must be registered as the Asset Manager for `token` in `poolId`. */ function managePoolBalance(PoolBalanceOp[] memory ops) external; struct PoolBalanceOp { PoolBalanceOpKind kind; bytes32 poolId; IERC20 token; uint256 amount; } /** * Withdrawals decrease the Pool's cash, but increase its managed balance, leaving the total balance unchanged. * * Deposits increase the Pool's cash, but decrease its managed balance, leaving the total balance unchanged. * * Updates don't affect the Pool's cash balance, but because the managed balance changes, it does alter the total. * The external amount can be either increased or decreased by this call (i.e., reporting a gain or a loss). */ enum PoolBalanceOpKind { WITHDRAW, DEPOSIT, UPDATE } /** * @dev Emitted when a Pool's token Asset Manager alters its balance via `managePoolBalance`. */ event PoolBalanceManaged( bytes32 indexed poolId, address indexed assetManager, IERC20 indexed token, int256 cashDelta, int256 managedDelta ); // Protocol Fees // // Some operations cause the Vault to collect tokens in the form of protocol fees, which can then be withdrawn by // permissioned accounts. // // There are two kinds of protocol fees: // // - flash loan fees: charged on all flash loans, as a percentage of the amounts lent. // // - swap fees: a percentage of the fees charged by Pools when performing swaps. For a number of reasons, including // swap gas costs and interface simplicity, protocol swap fees are not charged on each individual swap. Rather, // Pools are expected to keep track of how much they have charged in swap fees, and pay any outstanding debts to the // Vault when they are joined or exited. This prevents users from joining a Pool with unpaid debt, as well as // exiting a Pool in debt without first paying their share. /** * @dev Returns the current protocol fee module. */ function getProtocolFeesCollector() external view returns (IProtocolFeesCollector); /** * @dev Safety mechanism to pause most Vault operations in the event of an emergency - typically detection of an * error in some part of the system. * * The Vault can only be paused during an initial time period, after which pausing is forever disabled. * * While the contract is paused, the following features are disabled: * - depositing and transferring internal balance * - transferring external balance (using the Vault's allowance) * - swaps * - joining Pools * - Asset Manager interactions * * Internal Balance can still be withdrawn, and Pools exited. */ function setPaused(bool paused) external; /** * @dev Returns the Vault's WETH instance. */ function WETH() external view returns (IWETH); // solhint-disable-previous-line func-name-mixedcase } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./IVault.sol"; import "./IPoolSwapStructs.sol"; /** * @dev Interface for adding and removing liquidity that all Pool contracts should implement. Note that this is not * the complete Pool contract interface, as it is missing the swap hooks. Pool contracts should also inherit from * either IGeneralPool or IMinimalSwapInfoPool */ interface IBasePool is IPoolSwapStructs { /** * @dev Called by the Vault when a user calls `IVault.joinPool` to add liquidity to this Pool. Returns how many of * each registered token the user should provide, as well as the amount of protocol fees the Pool owes to the Vault. * The Vault will then take tokens from `sender` and add them to the Pool's balances, as well as collect * the reported amount in protocol fees, which the pool should calculate based on `protocolSwapFeePercentage`. * * Protocol fees are reported and charged on join events so that the Pool is free of debt whenever new users join. * * `sender` is the account performing the join (from which tokens will be withdrawn), and `recipient` is the account * designated to receive any benefits (typically pool shares). `balances` contains the total balances * for each token the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return. * * `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total * balance. * * `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of * join (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.) * * Contracts implementing this function should check that the caller is indeed the Vault before performing any * state-changing operations, such as minting pool shares. */ function onJoinPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts); /** * @dev Called by the Vault when a user calls `IVault.exitPool` to remove liquidity from this Pool. Returns how many * tokens the Vault should deduct from the Pool's balances, as well as the amount of protocol fees the Pool owes * to the Vault. The Vault will then take tokens from the Pool's balances and send them to `recipient`, * as well as collect the reported amount in protocol fees, which the Pool should calculate based on * `protocolSwapFeePercentage`. * * Protocol fees are charged on exit events to guarantee that users exiting the Pool have paid their share. * * `sender` is the account performing the exit (typically the pool shareholder), and `recipient` is the account * to which the Vault will send the proceeds. `balances` contains the total token balances for each token * the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return. * * `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total * balance. * * `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of * exit (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.) * * Contracts implementing this function should check that the caller is indeed the Vault before performing any * state-changing operations, such as burning pool shares. */ function onExitPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts); function getPoolId() external view returns (bytes32); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; interface IAssetManager { /** * @notice Emitted when asset manager is rebalanced */ event Rebalance(bytes32 poolId); /** * @notice Sets the config */ function setConfig(bytes32 poolId, bytes calldata config) external; /** * Note: No function to read the asset manager config is included in IAssetManager * as the signature is expected to vary between asset manager implementations */ /** * @notice Returns the asset manager's token */ function getToken() external view returns (IERC20); /** * @return the current assets under management of this asset manager */ function getAUM(bytes32 poolId) external view returns (uint256); /** * @return poolCash - The up-to-date cash balance of the pool * @return poolManaged - The up-to-date managed balance of the pool */ function getPoolBalances(bytes32 poolId) external view returns (uint256 poolCash, uint256 poolManaged); /** * @return The difference in tokens between the target investment * and the currently invested amount (i.e. the amount that can be invested) */ function maxInvestableBalance(bytes32 poolId) external view returns (int256); /** * @notice Updates the Vault on the value of the pool's investment returns */ function updateBalanceOfPool(bytes32 poolId) external; /** * @notice Determines whether the pool should rebalance given the provided balances */ function shouldRebalance(uint256 cash, uint256 managed) external view returns (bool); /** * @notice Rebalances funds between the pool and the asset manager to maintain target investment percentage. * @param poolId - the poolId of the pool to be rebalanced * @param force - a boolean representing whether a rebalance should be forced even when the pool is near balance */ function rebalance(bytes32 poolId, bool force) external; /** * @notice allows an authorized rebalancer to remove capital to facilitate large withdrawals * @param poolId - the poolId of the pool to withdraw funds back to * @param amount - the amount of tokens to withdraw back to the pool */ function capitalOut(bytes32 poolId, uint256 amount) external; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ERC20.sol"; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ERC20Permit.sol"; /** * @title Highly opinionated token implementation * @author Balancer Labs * @dev * - Includes functions to increase and decrease allowance as a workaround * for the well-known issue with `approve`: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * - Allows for 'infinite allowance', where an allowance of 0xff..ff is not * decreased by calls to transferFrom * - Lets a token holder use `transferFrom` to send their own tokens, * without first setting allowance * - Emits 'Approval' events whenever allowance is changed by `transferFrom` */ contract BalancerPoolToken is ERC20, ERC20Permit { constructor(string memory tokenName, string memory tokenSymbol) ERC20(tokenName, tokenSymbol) ERC20Permit(tokenName) { // solhint-disable-previous-line no-empty-blocks } // Overrides /** * @dev Override to allow for 'infinite allowance' and let the token owner use `transferFrom` with no self-allowance */ function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { uint256 currentAllowance = allowance(sender, msg.sender); _require(msg.sender == sender || currentAllowance >= amount, Errors.ERC20_TRANSFER_EXCEEDS_ALLOWANCE); _transfer(sender, recipient, amount); if (msg.sender != sender && currentAllowance != uint256(-1)) { // Because of the previous require, we know that if msg.sender != sender then currentAllowance >= amount _approve(sender, msg.sender, currentAllowance - amount); } return true; } /** * @dev Override to allow decreasing allowance by more than the current amount (setting it to zero) */ function decreaseAllowance(address spender, uint256 amount) public override returns (bool) { uint256 currentAllowance = allowance(msg.sender, spender); if (amount >= currentAllowance) { _approve(msg.sender, spender, 0); } else { // No risk of underflow due to if condition _approve(msg.sender, spender, currentAllowance - amount); } return true; } // Internal functions function _mintPoolTokens(address recipient, uint256 amount) internal { _mint(recipient, amount); } function _burnPoolTokens(address sender, uint256 amount) internal { _burn(sender, amount); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/helpers/Authentication.sol"; import "@balancer-labs/v2-vault/contracts/interfaces/IAuthorizer.sol"; import "./BasePool.sol"; /** * @dev Base authorization layer implementation for Pools. * * The owner account can call some of the permissioned functions - access control of the rest is delegated to the * Authorizer. Note that this owner is immutable: more sophisticated permission schemes, such as multiple ownership, * granular roles, etc., could be built on top of this by making the owner a smart contract. * * Access control of all other permissioned functions is delegated to an Authorizer. It is also possible to delegate * control of *all* permissioned functions to the Authorizer by setting the owner address to `_DELEGATE_OWNER`. */ abstract contract BasePoolAuthorization is Authentication { address private immutable _owner; address private constant _DELEGATE_OWNER = 0xBA1BA1ba1BA1bA1bA1Ba1BA1ba1BA1bA1ba1ba1B; constructor(address owner) { _owner = owner; } function getOwner() public view returns (address) { return _owner; } function getAuthorizer() external view returns (IAuthorizer) { return _getAuthorizer(); } function _canPerform(bytes32 actionId, address account) internal view override returns (bool) { if ((getOwner() != _DELEGATE_OWNER) && _isOwnerOnlyAction(actionId)) { // Only the owner can perform "owner only" actions, unless the owner is delegated. return msg.sender == getOwner(); } else { // Non-owner actions are always processed via the Authorizer, as "owner only" ones are when delegated. return _getAuthorizer().canPerform(actionId, account, address(this)); } } function _isOwnerOnlyAction(bytes32 actionId) internal view virtual returns (bool); function _getAuthorizer() internal view virtual returns (IAuthorizer); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev Interface for the TemporarilyPausable helper. */ interface ITemporarilyPausable { /** * @dev Emitted every time the pause state changes by `_setPaused`. */ event PausedStateChanged(bool paused); /** * @dev Returns the current paused state. */ function getPausedState() external view returns ( bool paused, uint256 pauseWindowEndTime, uint256 bufferPeriodEndTime ); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; /** * @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, Errors.ADD_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, Errors.SUB_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, uint256 errorCode) internal pure returns (uint256) { _require(b <= a, errorCode); uint256 c = a - b; return c; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev Interface for the SignatureValidator helper, used to support meta-transactions. */ interface ISignaturesValidator { /** * @dev Returns the EIP712 domain separator. */ function getDomainSeparator() external view returns (bytes32); /** * @dev Returns the next nonce used by an address to sign messages. */ function getNextNonce(address user) external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../openzeppelin/IERC20.sol"; /** * @dev Interface for WETH9. * See https://github.com/gnosis/canonical-weth/blob/0dd1ea3e295eef916d0c6223ec63141137d22d67/contracts/WETH9.sol */ interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint256 amount) external; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev This is an empty interface used to represent either ERC20-conforming token contracts or ETH (using the zero * address sentinel value). We're just relying on the fact that `interface` can be used to declare new address-like * types. * * This concept is unrelated to a Pool's Asset Managers. */ interface IAsset { // solhint-disable-previous-line no-empty-blocks } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; interface IAuthorizer { /** * @dev Returns true if `account` can perform the action described by `actionId` in the contract `where`. */ function canPerform( bytes32 actionId, address account, address where ) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; // Inspired by Aave Protocol's IFlashLoanReceiver. import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; interface IFlashLoanRecipient { /** * @dev When `flashLoan` is called on the Vault, it invokes the `receiveFlashLoan` hook on the recipient. * * At the time of the call, the Vault will have transferred `amounts` for `tokens` to the recipient. Before this * call returns, the recipient must have transferred `amounts` plus `feeAmounts` for each token back to the * Vault, or else the entire flash loan will revert. * * `userData` is the same value passed in the `IVault.flashLoan` call. */ function receiveFlashLoan( IERC20[] memory tokens, uint256[] memory amounts, uint256[] memory feeAmounts, bytes memory userData ) external; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; import "./IVault.sol"; import "./IAuthorizer.sol"; interface IProtocolFeesCollector { event SwapFeePercentageChanged(uint256 newSwapFeePercentage); event FlashLoanFeePercentageChanged(uint256 newFlashLoanFeePercentage); function withdrawCollectedFees( IERC20[] calldata tokens, uint256[] calldata amounts, address recipient ) external; function setSwapFeePercentage(uint256 newSwapFeePercentage) external; function setFlashLoanFeePercentage(uint256 newFlashLoanFeePercentage) external; function getSwapFeePercentage() external view returns (uint256); function getFlashLoanFeePercentage() external view returns (uint256); function getCollectedFeeAmounts(IERC20[] memory tokens) external view returns (uint256[] memory feeAmounts); function getAuthorizer() external view returns (IAuthorizer); function vault() external view returns (IVault); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; import "./IVault.sol"; interface IPoolSwapStructs { // This is not really an interface - it just defines common structs used by other interfaces: IGeneralPool and // IMinimalSwapInfoPool. // // This data structure represents a request for a token swap, where `kind` indicates the swap type ('given in' or // 'given out') which indicates whether or not the amount sent by the pool is known. // // The pool receives `tokenIn` and sends `tokenOut`. `amount` is the number of `tokenIn` tokens the pool will take // in, or the number of `tokenOut` tokens the Pool will send out, depending on the given swap `kind`. // // All other fields are not strictly necessary for most swaps, but are provided to support advanced scenarios in // some Pools. // // `poolId` is the ID of the Pool involved in the swap - this is useful for Pool contracts that implement more than // one Pool. // // The meaning of `lastChangeBlock` depends on the Pool specialization: // - Two Token or Minimal Swap Info: the last block in which either `tokenIn` or `tokenOut` changed its total // balance. // - General: the last block in which *any* of the Pool's registered tokens changed its total balance. // // `from` is the origin address for the funds the Pool receives, and `to` is the destination address // where the Pool sends the outgoing tokens. // // `userData` is extra data provided by the caller - typically a signature from a trusted party. struct SwapRequest { IVault.SwapKind kind; IERC20 tokenIn; IERC20 tokenOut; uint256 amount; // Misc data bytes32 poolId; uint256 lastChangeBlock; address from; address to; bytes userData; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./ERC20.sol"; import "./IERC20Permit.sol"; import "./EIP712.sol"; /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */ abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { mapping(address => uint256) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ constructor(string memory name) EIP712(name, "1") {} /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { // solhint-disable-next-line not-rely-on-time _require(block.timestamp <= deadline, Errors.EXPIRED_PERMIT); uint256 nonce = _nonces[owner]; bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, nonce, deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ecrecover(hash, v, r, s); _require((signer != address(0)) && (signer == owner), Errors.INVALID_SIGNATURE); _nonces[owner] = nonce + 1; _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view override returns (uint256) { return _nonces[owner]; } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over `owner`'s tokens, * given `owner`'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { _HASHED_NAME = keccak256(bytes(name)); _HASHED_VERSION = keccak256(bytes(version)); _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view virtual returns (bytes32) { return keccak256(abi.encode(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION, _getChainId(), address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash)); } function _getChainId() private view returns (uint256 chainId) { // Silence state mutability warning without generating bytecode. // See https://github.com/ethereum/solidity/issues/10090#issuecomment-741789128 and // https://github.com/ethereum/solidity/issues/2691 this; // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "./BalancerErrors.sol"; import "./IAuthentication.sol"; /** * @dev Building block for performing access control on external functions. * * This contract is used via the `authenticate` modifier (or the `_authenticateCaller` function), which can be applied * to external functions to only make them callable by authorized accounts. * * Derived contracts must implement the `_canPerform` function, which holds the actual access control logic. */ abstract contract Authentication is IAuthentication { bytes32 private immutable _actionIdDisambiguator; /** * @dev The main purpose of the `actionIdDisambiguator` is to prevent accidental function selector collisions in * multi contract systems. * * There are two main uses for it: * - if the contract is a singleton, any unique identifier can be used to make the associated action identifiers * unique. The contract's own address is a good option. * - if the contract belongs to a family that shares action identifiers for the same functions, an identifier * shared by the entire family (and no other contract) should be used instead. */ constructor(bytes32 actionIdDisambiguator) { _actionIdDisambiguator = actionIdDisambiguator; } /** * @dev Reverts unless the caller is allowed to call this function. Should only be applied to external functions. */ modifier authenticate() { _authenticateCaller(); _; } /** * @dev Reverts unless the caller is allowed to call the entry point function. */ function _authenticateCaller() internal view { bytes32 actionId = getActionId(msg.sig); _require(_canPerform(actionId, msg.sender), Errors.SENDER_NOT_ALLOWED); } function getActionId(bytes4 selector) public view override returns (bytes32) { // Each external function is dynamically assigned an action identifier as the hash of the disambiguator and the // function selector. Disambiguation is necessary to avoid potential collisions in the function selectors of // multiple contracts. return keccak256(abi.encodePacked(_actionIdDisambiguator, selector)); } function _canPerform(bytes32 actionId, address user) internal view virtual returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; interface IAuthentication { /** * @dev Returns the action identifier associated with the external function described by `selector`. */ function getActionId(bytes4 selector) external view returns (bytes32); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./BaseWeightedPool.sol"; /** * @dev Basic Weighted Pool with immutable weights. */ contract WeightedPool is BaseWeightedPool { using FixedPoint for uint256; uint256 private constant _MAX_TOKENS = 20; uint256 private immutable _totalTokens; IERC20 internal immutable _token0; IERC20 internal immutable _token1; IERC20 internal immutable _token2; IERC20 internal immutable _token3; IERC20 internal immutable _token4; IERC20 internal immutable _token5; IERC20 internal immutable _token6; IERC20 internal immutable _token7; IERC20 internal immutable _token8; IERC20 internal immutable _token9; IERC20 internal immutable _token10; IERC20 internal immutable _token11; IERC20 internal immutable _token12; IERC20 internal immutable _token13; IERC20 internal immutable _token14; IERC20 internal immutable _token15; IERC20 internal immutable _token16; IERC20 internal immutable _token17; IERC20 internal immutable _token18; IERC20 internal immutable _token19; // All token balances are normalized to behave as if the token had 18 decimals. We assume a token's decimals will // not change throughout its lifetime, and store the corresponding scaling factor for each at construction time. // These factors are always greater than or equal to one: tokens with more than 18 decimals are not supported. uint256 internal immutable _scalingFactor0; uint256 internal immutable _scalingFactor1; uint256 internal immutable _scalingFactor2; uint256 internal immutable _scalingFactor3; uint256 internal immutable _scalingFactor4; uint256 internal immutable _scalingFactor5; uint256 internal immutable _scalingFactor6; uint256 internal immutable _scalingFactor7; uint256 internal immutable _scalingFactor8; uint256 internal immutable _scalingFactor9; uint256 internal immutable _scalingFactor10; uint256 internal immutable _scalingFactor11; uint256 internal immutable _scalingFactor12; uint256 internal immutable _scalingFactor13; uint256 internal immutable _scalingFactor14; uint256 internal immutable _scalingFactor15; uint256 internal immutable _scalingFactor16; uint256 internal immutable _scalingFactor17; uint256 internal immutable _scalingFactor18; uint256 internal immutable _scalingFactor19; // The protocol fees will always be charged using the token associated with the max weight in the pool. // Since these Pools will register tokens only once, we can assume this index will be constant. uint256 internal immutable _maxWeightTokenIndex; uint256 internal immutable _normalizedWeight0; uint256 internal immutable _normalizedWeight1; uint256 internal immutable _normalizedWeight2; uint256 internal immutable _normalizedWeight3; uint256 internal immutable _normalizedWeight4; uint256 internal immutable _normalizedWeight5; uint256 internal immutable _normalizedWeight6; uint256 internal immutable _normalizedWeight7; uint256 internal immutable _normalizedWeight8; uint256 internal immutable _normalizedWeight9; uint256 internal immutable _normalizedWeight10; uint256 internal immutable _normalizedWeight11; uint256 internal immutable _normalizedWeight12; uint256 internal immutable _normalizedWeight13; uint256 internal immutable _normalizedWeight14; uint256 internal immutable _normalizedWeight15; uint256 internal immutable _normalizedWeight16; uint256 internal immutable _normalizedWeight17; uint256 internal immutable _normalizedWeight18; uint256 internal immutable _normalizedWeight19; constructor( IVault vault, string memory name, string memory symbol, IERC20[] memory tokens, uint256[] memory normalizedWeights, address[] memory assetManagers, uint256 swapFeePercentage, uint256 pauseWindowDuration, uint256 bufferPeriodDuration, address owner ) BaseWeightedPool( vault, name, symbol, tokens, assetManagers, swapFeePercentage, pauseWindowDuration, bufferPeriodDuration, owner ) { uint256 numTokens = tokens.length; InputHelpers.ensureInputLengthMatch(numTokens, normalizedWeights.length); _totalTokens = numTokens; // Ensure each normalized weight is above them minimum and find the token index of the maximum weight uint256 normalizedSum = 0; uint256 maxWeightTokenIndex = 0; uint256 maxNormalizedWeight = 0; for (uint8 i = 0; i < numTokens; i++) { uint256 normalizedWeight = normalizedWeights[i]; _require(normalizedWeight >= _MIN_WEIGHT, Errors.MIN_WEIGHT); normalizedSum = normalizedSum.add(normalizedWeight); if (normalizedWeight > maxNormalizedWeight) { maxWeightTokenIndex = i; maxNormalizedWeight = normalizedWeight; } } // Ensure that the normalized weights sum to ONE _require(normalizedSum == FixedPoint.ONE, Errors.NORMALIZED_WEIGHT_INVARIANT); _maxWeightTokenIndex = maxWeightTokenIndex; _normalizedWeight0 = normalizedWeights[0]; _normalizedWeight1 = normalizedWeights[1]; _normalizedWeight2 = numTokens > 2 ? normalizedWeights[2] : 0; _normalizedWeight3 = numTokens > 3 ? normalizedWeights[3] : 0; _normalizedWeight4 = numTokens > 4 ? normalizedWeights[4] : 0; _normalizedWeight5 = numTokens > 5 ? normalizedWeights[5] : 0; _normalizedWeight6 = numTokens > 6 ? normalizedWeights[6] : 0; _normalizedWeight7 = numTokens > 7 ? normalizedWeights[7] : 0; _normalizedWeight8 = numTokens > 8 ? normalizedWeights[8] : 0; _normalizedWeight9 = numTokens > 9 ? normalizedWeights[9] : 0; _normalizedWeight10 = numTokens > 10 ? normalizedWeights[10] : 0; _normalizedWeight11 = numTokens > 11 ? normalizedWeights[11] : 0; _normalizedWeight12 = numTokens > 12 ? normalizedWeights[12] : 0; _normalizedWeight13 = numTokens > 13 ? normalizedWeights[13] : 0; _normalizedWeight14 = numTokens > 14 ? normalizedWeights[14] : 0; _normalizedWeight15 = numTokens > 15 ? normalizedWeights[15] : 0; _normalizedWeight16 = numTokens > 16 ? normalizedWeights[16] : 0; _normalizedWeight17 = numTokens > 17 ? normalizedWeights[17] : 0; _normalizedWeight18 = numTokens > 18 ? normalizedWeights[18] : 0; _normalizedWeight19 = numTokens > 19 ? normalizedWeights[19] : 0; // Immutable variables cannot be initialized inside an if statement, so we must do conditional assignments _token0 = tokens[0]; _token1 = tokens[1]; _token2 = numTokens > 2 ? tokens[2] : IERC20(0); _token3 = numTokens > 3 ? tokens[3] : IERC20(0); _token4 = numTokens > 4 ? tokens[4] : IERC20(0); _token5 = numTokens > 5 ? tokens[5] : IERC20(0); _token6 = numTokens > 6 ? tokens[6] : IERC20(0); _token7 = numTokens > 7 ? tokens[7] : IERC20(0); _token8 = numTokens > 8 ? tokens[8] : IERC20(0); _token9 = numTokens > 9 ? tokens[9] : IERC20(0); _token10 = numTokens > 10 ? tokens[10] : IERC20(0); _token11 = numTokens > 11 ? tokens[11] : IERC20(0); _token12 = numTokens > 12 ? tokens[12] : IERC20(0); _token13 = numTokens > 13 ? tokens[13] : IERC20(0); _token14 = numTokens > 14 ? tokens[14] : IERC20(0); _token15 = numTokens > 15 ? tokens[15] : IERC20(0); _token16 = numTokens > 16 ? tokens[16] : IERC20(0); _token17 = numTokens > 17 ? tokens[17] : IERC20(0); _token18 = numTokens > 18 ? tokens[18] : IERC20(0); _token19 = numTokens > 19 ? tokens[19] : IERC20(0); _scalingFactor0 = _computeScalingFactor(tokens[0]); _scalingFactor1 = _computeScalingFactor(tokens[1]); _scalingFactor2 = numTokens > 2 ? _computeScalingFactor(tokens[2]) : 0; _scalingFactor3 = numTokens > 3 ? _computeScalingFactor(tokens[3]) : 0; _scalingFactor4 = numTokens > 4 ? _computeScalingFactor(tokens[4]) : 0; _scalingFactor5 = numTokens > 5 ? _computeScalingFactor(tokens[5]) : 0; _scalingFactor6 = numTokens > 6 ? _computeScalingFactor(tokens[6]) : 0; _scalingFactor7 = numTokens > 7 ? _computeScalingFactor(tokens[7]) : 0; _scalingFactor8 = numTokens > 8 ? _computeScalingFactor(tokens[8]) : 0; _scalingFactor9 = numTokens > 9 ? _computeScalingFactor(tokens[9]) : 0; _scalingFactor10 = numTokens > 10 ? _computeScalingFactor(tokens[10]) : 0; _scalingFactor11 = numTokens > 11 ? _computeScalingFactor(tokens[11]) : 0; _scalingFactor12 = numTokens > 12 ? _computeScalingFactor(tokens[12]) : 0; _scalingFactor13 = numTokens > 13 ? _computeScalingFactor(tokens[13]) : 0; _scalingFactor14 = numTokens > 14 ? _computeScalingFactor(tokens[14]) : 0; _scalingFactor15 = numTokens > 15 ? _computeScalingFactor(tokens[15]) : 0; _scalingFactor16 = numTokens > 16 ? _computeScalingFactor(tokens[16]) : 0; _scalingFactor17 = numTokens > 17 ? _computeScalingFactor(tokens[17]) : 0; _scalingFactor18 = numTokens > 18 ? _computeScalingFactor(tokens[18]) : 0; _scalingFactor19 = numTokens > 19 ? _computeScalingFactor(tokens[19]) : 0; } function _getNormalizedWeight(IERC20 token) internal view virtual override returns (uint256) { // prettier-ignore if (token == _token0) { return _normalizedWeight0; } else if (token == _token1) { return _normalizedWeight1; } else if (token == _token2) { return _normalizedWeight2; } else if (token == _token3) { return _normalizedWeight3; } else if (token == _token4) { return _normalizedWeight4; } else if (token == _token5) { return _normalizedWeight5; } else if (token == _token6) { return _normalizedWeight6; } else if (token == _token7) { return _normalizedWeight7; } else if (token == _token8) { return _normalizedWeight8; } else if (token == _token9) { return _normalizedWeight9; } else if (token == _token10) { return _normalizedWeight10; } else if (token == _token11) { return _normalizedWeight11; } else if (token == _token12) { return _normalizedWeight12; } else if (token == _token13) { return _normalizedWeight13; } else if (token == _token14) { return _normalizedWeight14; } else if (token == _token15) { return _normalizedWeight15; } else if (token == _token16) { return _normalizedWeight16; } else if (token == _token17) { return _normalizedWeight17; } else if (token == _token18) { return _normalizedWeight18; } else if (token == _token19) { return _normalizedWeight19; } else { _revert(Errors.INVALID_TOKEN); } } function _getNormalizedWeights() internal view virtual override returns (uint256[] memory) { uint256 totalTokens = _getTotalTokens(); uint256[] memory normalizedWeights = new uint256[](totalTokens); // prettier-ignore { if (totalTokens > 0) { normalizedWeights[0] = _normalizedWeight0; } else { return normalizedWeights; } if (totalTokens > 1) { normalizedWeights[1] = _normalizedWeight1; } else { return normalizedWeights; } if (totalTokens > 2) { normalizedWeights[2] = _normalizedWeight2; } else { return normalizedWeights; } if (totalTokens > 3) { normalizedWeights[3] = _normalizedWeight3; } else { return normalizedWeights; } if (totalTokens > 4) { normalizedWeights[4] = _normalizedWeight4; } else { return normalizedWeights; } if (totalTokens > 5) { normalizedWeights[5] = _normalizedWeight5; } else { return normalizedWeights; } if (totalTokens > 6) { normalizedWeights[6] = _normalizedWeight6; } else { return normalizedWeights; } if (totalTokens > 7) { normalizedWeights[7] = _normalizedWeight7; } else { return normalizedWeights; } if (totalTokens > 8) { normalizedWeights[8] = _normalizedWeight8; } else { return normalizedWeights; } if (totalTokens > 9) { normalizedWeights[9] = _normalizedWeight9; } else { return normalizedWeights; } if (totalTokens > 10) { normalizedWeights[10] = _normalizedWeight10; } else { return normalizedWeights; } if (totalTokens > 11) { normalizedWeights[11] = _normalizedWeight11; } else { return normalizedWeights; } if (totalTokens > 12) { normalizedWeights[12] = _normalizedWeight12; } else { return normalizedWeights; } if (totalTokens > 13) { normalizedWeights[13] = _normalizedWeight13; } else { return normalizedWeights; } if (totalTokens > 14) { normalizedWeights[14] = _normalizedWeight14; } else { return normalizedWeights; } if (totalTokens > 15) { normalizedWeights[15] = _normalizedWeight15; } else { return normalizedWeights; } if (totalTokens > 16) { normalizedWeights[16] = _normalizedWeight16; } else { return normalizedWeights; } if (totalTokens > 17) { normalizedWeights[17] = _normalizedWeight17; } else { return normalizedWeights; } if (totalTokens > 18) { normalizedWeights[18] = _normalizedWeight18; } else { return normalizedWeights; } if (totalTokens > 19) { normalizedWeights[19] = _normalizedWeight19; } else { return normalizedWeights; } } return normalizedWeights; } function _getNormalizedWeightsAndMaxWeightIndex() internal view virtual override returns (uint256[] memory, uint256) { return (_getNormalizedWeights(), _maxWeightTokenIndex); } function _getMaxTokens() internal pure virtual override returns (uint256) { return _MAX_TOKENS; } function _getTotalTokens() internal view virtual override returns (uint256) { return _totalTokens; } /** * @dev Returns the scaling factor for one of the Pool's tokens. Reverts if `token` is not a token registered by the * Pool. */ function _scalingFactor(IERC20 token) internal view virtual override returns (uint256) { // prettier-ignore if (token == _token0) { return _scalingFactor0; } else if (token == _token1) { return _scalingFactor1; } else if (token == _token2) { return _scalingFactor2; } else if (token == _token3) { return _scalingFactor3; } else if (token == _token4) { return _scalingFactor4; } else if (token == _token5) { return _scalingFactor5; } else if (token == _token6) { return _scalingFactor6; } else if (token == _token7) { return _scalingFactor7; } else if (token == _token8) { return _scalingFactor8; } else if (token == _token9) { return _scalingFactor9; } else if (token == _token10) { return _scalingFactor10; } else if (token == _token11) { return _scalingFactor11; } else if (token == _token12) { return _scalingFactor12; } else if (token == _token13) { return _scalingFactor13; } else if (token == _token14) { return _scalingFactor14; } else if (token == _token15) { return _scalingFactor15; } else if (token == _token16) { return _scalingFactor16; } else if (token == _token17) { return _scalingFactor17; } else if (token == _token18) { return _scalingFactor18; } else if (token == _token19) { return _scalingFactor19; } else { _revert(Errors.INVALID_TOKEN); } } function _scalingFactors() internal view virtual override returns (uint256[] memory) { uint256 totalTokens = _getTotalTokens(); uint256[] memory scalingFactors = new uint256[](totalTokens); // prettier-ignore { if (totalTokens > 0) { scalingFactors[0] = _scalingFactor0; } else { return scalingFactors; } if (totalTokens > 1) { scalingFactors[1] = _scalingFactor1; } else { return scalingFactors; } if (totalTokens > 2) { scalingFactors[2] = _scalingFactor2; } else { return scalingFactors; } if (totalTokens > 3) { scalingFactors[3] = _scalingFactor3; } else { return scalingFactors; } if (totalTokens > 4) { scalingFactors[4] = _scalingFactor4; } else { return scalingFactors; } if (totalTokens > 5) { scalingFactors[5] = _scalingFactor5; } else { return scalingFactors; } if (totalTokens > 6) { scalingFactors[6] = _scalingFactor6; } else { return scalingFactors; } if (totalTokens > 7) { scalingFactors[7] = _scalingFactor7; } else { return scalingFactors; } if (totalTokens > 8) { scalingFactors[8] = _scalingFactor8; } else { return scalingFactors; } if (totalTokens > 9) { scalingFactors[9] = _scalingFactor9; } else { return scalingFactors; } if (totalTokens > 10) { scalingFactors[10] = _scalingFactor10; } else { return scalingFactors; } if (totalTokens > 11) { scalingFactors[11] = _scalingFactor11; } else { return scalingFactors; } if (totalTokens > 12) { scalingFactors[12] = _scalingFactor12; } else { return scalingFactors; } if (totalTokens > 13) { scalingFactors[13] = _scalingFactor13; } else { return scalingFactors; } if (totalTokens > 14) { scalingFactors[14] = _scalingFactor14; } else { return scalingFactors; } if (totalTokens > 15) { scalingFactors[15] = _scalingFactor15; } else { return scalingFactors; } if (totalTokens > 16) { scalingFactors[16] = _scalingFactor16; } else { return scalingFactors; } if (totalTokens > 17) { scalingFactors[17] = _scalingFactor17; } else { return scalingFactors; } if (totalTokens > 18) { scalingFactors[18] = _scalingFactor18; } else { return scalingFactors; } if (totalTokens > 19) { scalingFactors[19] = _scalingFactor19; } else { return scalingFactors; } } return scalingFactors; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol"; import "@balancer-labs/v2-pool-utils/contracts/factories/BasePoolSplitCodeFactory.sol"; import "@balancer-labs/v2-pool-utils/contracts/factories/FactoryWidePauseWindow.sol"; import "./WeightedPool.sol"; contract WeightedPoolNoAMFactory is BasePoolSplitCodeFactory, FactoryWidePauseWindow { constructor(IVault vault) BasePoolSplitCodeFactory(vault, type(WeightedPool).creationCode) { // solhint-disable-previous-line no-empty-blocks } /** * @dev Deploys a new `WeightedPool` without asset managers. */ function create( string memory name, string memory symbol, IERC20[] memory tokens, uint256[] memory weights, uint256 swapFeePercentage, address owner ) external returns (address) { (uint256 pauseWindowDuration, uint256 bufferPeriodDuration) = getPauseConfiguration(); return _create( abi.encode( getVault(), name, symbol, tokens, weights, new address[](tokens.length), // Don't allow asset managers swapFeePercentage, pauseWindowDuration, bufferPeriodDuration, owner ) ); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/helpers/BaseSplitCodeFactory.sol"; import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol"; /** * @dev Same as `BasePoolFactory`, for Pools whose creation code is so large that the factory cannot hold it. */ abstract contract BasePoolSplitCodeFactory is BaseSplitCodeFactory { IVault private immutable _vault; mapping(address => bool) private _isPoolFromFactory; event PoolCreated(address indexed pool); constructor(IVault vault, bytes memory creationCode) BaseSplitCodeFactory(creationCode) { _vault = vault; } /** * @dev Returns the Vault's address. */ function getVault() public view returns (IVault) { return _vault; } /** * @dev Returns true if `pool` was created by this factory. */ function isPoolFromFactory(address pool) external view returns (bool) { return _isPoolFromFactory[pool]; } function _create(bytes memory constructorArgs) internal override returns (address) { address pool = super._create(constructorArgs); _isPoolFromFactory[pool] = true; emit PoolCreated(pool); return pool; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; /** * @dev Utility to create Pool factories for Pools that use the `TemporarilyPausable` contract. * * By calling `TemporarilyPausable`'s constructor with the result of `getPauseConfiguration`, all Pools created by this * factory will share the same Pause Window end time, after which both old and new Pools will not be pausable. */ contract FactoryWidePauseWindow { // This contract relies on timestamps in a similar way as `TemporarilyPausable` does - the same caveats apply. // solhint-disable not-rely-on-time uint256 private constant _INITIAL_PAUSE_WINDOW_DURATION = 90 days; uint256 private constant _BUFFER_PERIOD_DURATION = 30 days; // Time when the pause window for all created Pools expires, and the pause window duration of new Pools becomes // zero. uint256 private immutable _poolsPauseWindowEndTime; constructor() { _poolsPauseWindowEndTime = block.timestamp + _INITIAL_PAUSE_WINDOW_DURATION; } /** * @dev Returns the current `TemporarilyPausable` configuration that will be applied to Pools created by this * factory. * * `pauseWindowDuration` will decrease over time until it reaches zero, at which point both it and * `bufferPeriodDuration` will be zero forever, meaning deployed Pools will not be pausable. */ function getPauseConfiguration() public view returns (uint256 pauseWindowDuration, uint256 bufferPeriodDuration) { uint256 currentTime = block.timestamp; if (currentTime < _poolsPauseWindowEndTime) { // The buffer period is always the same since its duration is related to how much time is needed to respond // to a potential emergency. The Pause Window duration however decreases as the end time approaches. pauseWindowDuration = _poolsPauseWindowEndTime - currentTime; // No need for checked arithmetic. bufferPeriodDuration = _BUFFER_PERIOD_DURATION; } else { // After the end time, newly created Pools have no Pause Window, nor Buffer Period (since they are not // pausable in the first place). pauseWindowDuration = 0; bufferPeriodDuration = 0; } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./BalancerErrors.sol"; import "./CodeDeployer.sol"; /** * @dev Base factory for contracts whose creation code is so large that the factory cannot hold it. This happens when * the contract's creation code grows close to 24kB. * * Note that this factory cannot help with contracts that have a *runtime* (deployed) bytecode larger than 24kB. */ abstract contract BaseSplitCodeFactory { // The contract's creation code is stored as code in two separate addresses, and retrieved via `extcodecopy`. This // means this factory supports contracts with creation code of up to 48kB. // We rely on inline-assembly to achieve this, both to make the entire operation highly gas efficient, and because // `extcodecopy` is not available in Solidity. // solhint-disable no-inline-assembly address private immutable _creationCodeContractA; uint256 private immutable _creationCodeSizeA; address private immutable _creationCodeContractB; uint256 private immutable _creationCodeSizeB; /** * @dev The creation code of a contract Foo can be obtained inside Solidity with `type(Foo).creationCode`. */ constructor(bytes memory creationCode) { uint256 creationCodeSize = creationCode.length; // We are going to deploy two contracts: one with approximately the first half of `creationCode`'s contents // (A), and another with the remaining half (B). // We store the lengths in both immutable and stack variables, since immutable variables cannot be read during // construction. uint256 creationCodeSizeA = creationCodeSize / 2; _creationCodeSizeA = creationCodeSizeA; uint256 creationCodeSizeB = creationCodeSize - creationCodeSizeA; _creationCodeSizeB = creationCodeSizeB; // To deploy the contracts, we're going to use `CodeDeployer.deploy()`, which expects a memory array with // the code to deploy. Note that we cannot simply create arrays for A and B's code by copying or moving // `creationCode`'s contents as they are expected to be very large (> 24kB), so we must operate in-place. // Memory: [ code length ] [ A.data ] [ B.data ] // Creating A's array is simple: we simply replace `creationCode`'s length with A's length. We'll later restore // the original length. bytes memory creationCodeA; assembly { creationCodeA := creationCode mstore(creationCodeA, creationCodeSizeA) } // Memory: [ A.length ] [ A.data ] [ B.data ] // ^ creationCodeA _creationCodeContractA = CodeDeployer.deploy(creationCodeA); // Creating B's array is a bit more involved: since we cannot move B's contents, we are going to create a 'new' // memory array starting at A's last 32 bytes, which will be replaced with B's length. We'll back-up this last // byte to later restore it. bytes memory creationCodeB; bytes32 lastByteA; assembly { // `creationCode` points to the array's length, not data, so by adding A's length to it we arrive at A's // last 32 bytes. creationCodeB := add(creationCode, creationCodeSizeA) lastByteA := mload(creationCodeB) mstore(creationCodeB, creationCodeSizeB) } // Memory: [ A.length ] [ A.data[ : -1] ] [ B.length ][ B.data ] // ^ creationCodeA ^ creationCodeB _creationCodeContractB = CodeDeployer.deploy(creationCodeB); // We now restore the original contents of `creationCode` by writing back the original length and A's last byte. assembly { mstore(creationCodeA, creationCodeSize) mstore(creationCodeB, lastByteA) } } /** * @dev Returns the two addresses where the creation code of the contract crated by this factory is stored. */ function getCreationCodeContracts() public view returns (address contractA, address contractB) { return (_creationCodeContractA, _creationCodeContractB); } /** * @dev Returns the creation code of the contract this factory creates. */ function getCreationCode() public view returns (bytes memory) { return _getCreationCodeWithArgs(""); } /** * @dev Returns the creation code that will result in a contract being deployed with `constructorArgs`. */ function _getCreationCodeWithArgs(bytes memory constructorArgs) private view returns (bytes memory code) { // This function exists because `abi.encode()` cannot be instructed to place its result at a specific address. // We need for the ABI-encoded constructor arguments to be located immediately after the creation code, but // cannot rely on `abi.encodePacked()` to perform concatenation as that would involve copying the creation code, // which would be prohibitively expensive. // Instead, we compute the creation code in a pre-allocated array that is large enough to hold *both* the // creation code and the constructor arguments, and then copy the ABI-encoded arguments (which should not be // overly long) right after the end of the creation code. // Immutable variables cannot be used in assembly, so we store them in the stack first. address creationCodeContractA = _creationCodeContractA; uint256 creationCodeSizeA = _creationCodeSizeA; address creationCodeContractB = _creationCodeContractB; uint256 creationCodeSizeB = _creationCodeSizeB; uint256 creationCodeSize = creationCodeSizeA + creationCodeSizeB; uint256 constructorArgsSize = constructorArgs.length; uint256 codeSize = creationCodeSize + constructorArgsSize; assembly { // First, we allocate memory for `code` by retrieving the free memory pointer and then moving it ahead of // `code` by the size of the creation code plus constructor arguments, and 32 bytes for the array length. code := mload(0x40) mstore(0x40, add(code, add(codeSize, 32))) // We now store the length of the code plus constructor arguments. mstore(code, codeSize) // Next, we concatenate the creation code stored in A and B. let dataStart := add(code, 32) extcodecopy(creationCodeContractA, dataStart, 0, creationCodeSizeA) extcodecopy(creationCodeContractB, add(dataStart, creationCodeSizeA), 0, creationCodeSizeB) } // Finally, we copy the constructorArgs to the end of the array. Unfortunately there is no way to avoid this // copy, as it is not possible to tell Solidity where to store the result of `abi.encode()`. uint256 constructorArgsDataPtr; uint256 constructorArgsCodeDataPtr; assembly { constructorArgsDataPtr := add(constructorArgs, 32) constructorArgsCodeDataPtr := add(add(code, 32), creationCodeSize) } _memcpy(constructorArgsCodeDataPtr, constructorArgsDataPtr, constructorArgsSize); } /** * @dev Deploys a contract with constructor arguments. To create `constructorArgs`, call `abi.encode()` with the * contract's constructor arguments, in order. */ function _create(bytes memory constructorArgs) internal virtual returns (address) { bytes memory creationCode = _getCreationCodeWithArgs(constructorArgs); address destination; assembly { destination := create(0, add(creationCode, 32), mload(creationCode)) } if (destination == address(0)) { // Bubble up inner revert reason // solhint-disable-next-line no-inline-assembly assembly { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } return destination; } // From // https://github.com/Arachnid/solidity-stringutils/blob/b9a6f6615cf18a87a823cbc461ce9e140a61c305/src/strings.sol function _memcpy( uint256 dest, uint256 src, uint256 len ) private pure { // Copy word-length chunks while possible for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint256 mask = 256**(32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "./BalancerErrors.sol"; /** * @dev Library used to deploy contracts with specific code. This can be used for long-term storage of immutable data as * contract code, which can be retrieved via the `extcodecopy` opcode. */ library CodeDeployer { // During contract construction, the full code supplied exists as code, and can be accessed via `codesize` and // `codecopy`. This is not the contract's final code however: whatever the constructor returns is what will be // stored as its code. // // We use this mechanism to have a simple constructor that stores whatever is appended to it. The following opcode // sequence corresponds to the creation code of the following equivalent Solidity contract, plus padding to make the // full code 32 bytes long: // // contract CodeDeployer { // constructor() payable { // uint256 size; // assembly { // size := sub(codesize(), 32) // size of appended data, as constructor is 32 bytes long // codecopy(0, 32, size) // copy all appended data to memory at position 0 // return(0, size) // return appended data for it to be stored as code // } // } // } // // More specifically, it is composed of the following opcodes (plus padding): // // [1] PUSH1 0x20 // [2] CODESIZE // [3] SUB // [4] DUP1 // [6] PUSH1 0x20 // [8] PUSH1 0x00 // [9] CODECOPY // [11] PUSH1 0x00 // [12] RETURN // // The padding is just the 0xfe sequence (invalid opcode). bytes32 private constant _DEPLOYER_CREATION_CODE = 0x602038038060206000396000f3fefefefefefefefefefefefefefefefefefefe; /** * @dev Deploys a contract with `code` as its code, returning the destination address. * * Reverts if deployment fails. */ function deploy(bytes memory code) internal returns (address destination) { bytes32 deployerCreationCode = _DEPLOYER_CREATION_CODE; // solhint-disable-next-line no-inline-assembly assembly { let codeLength := mload(code) // `code` is composed of length and data. We've already stored its length in `codeLength`, so we simply // replace it with the deployer creation code (which is exactly 32 bytes long). mstore(code, deployerCreationCode) // At this point, `code` now points to the deployer creation code immediately followed by `code`'s data // contents. This is exactly what the deployer expects to receive when created. destination := create(0, code, add(codeLength, 32)) // Finally, we restore the original length in order to not mutate `code`. mstore(code, codeLength) } // The create opcode returns the zero address when contract creation fails, so we revert if this happens. _require(destination != address(0), Errors.CODE_DEPLOYMENT_FAILED); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol"; import "@balancer-labs/v2-pool-utils/contracts/factories/BasePoolSplitCodeFactory.sol"; import "@balancer-labs/v2-pool-utils/contracts/factories/FactoryWidePauseWindow.sol"; import "./WeightedPool.sol"; contract WeightedPoolFactory is BasePoolSplitCodeFactory, FactoryWidePauseWindow { constructor(IVault vault) BasePoolSplitCodeFactory(vault, type(WeightedPool).creationCode) { // solhint-disable-previous-line no-empty-blocks } /** * @dev Deploys a new `WeightedPool`. */ function create( string memory name, string memory symbol, IERC20[] memory tokens, uint256[] memory weights, address[] memory assetManagers, uint256 swapFeePercentage, address owner ) external returns (address) { (uint256 pauseWindowDuration, uint256 bufferPeriodDuration) = getPauseConfiguration(); return _create( abi.encode( getVault(), name, symbol, tokens, weights, assetManagers, swapFeePercentage, pauseWindowDuration, bufferPeriodDuration, owner ) ); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/math/FixedPoint.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/InputHelpers.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/LogCompression.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/TemporarilyPausable.sol"; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ERC20.sol"; import "@balancer-labs/v2-vault/contracts/interfaces/IMinimalSwapInfoPool.sol"; import "@balancer-labs/v2-pool-utils/contracts/BasePoolAuthorization.sol"; import "@balancer-labs/v2-pool-utils/contracts/BalancerPoolToken.sol"; import "@balancer-labs/v2-pool-utils/contracts/oracle/PoolPriceOracle.sol"; import "@balancer-labs/v2-pool-utils/contracts/oracle/Buffer.sol"; import "./WeightedMath.sol"; import "./WeightedOracleMath.sol"; import "./WeightedPoolUserDataHelpers.sol"; import "./WeightedPool2TokensMiscData.sol"; contract WeightedPool2Tokens is IMinimalSwapInfoPool, BasePoolAuthorization, BalancerPoolToken, TemporarilyPausable, PoolPriceOracle, WeightedMath, WeightedOracleMath { using FixedPoint for uint256; using WeightedPoolUserDataHelpers for bytes; using WeightedPool2TokensMiscData for bytes32; uint256 private constant _MINIMUM_BPT = 1e6; // 1e18 corresponds to 1.0, or a 100% fee uint256 private constant _MIN_SWAP_FEE_PERCENTAGE = 1e12; // 0.0001% uint256 private constant _MAX_SWAP_FEE_PERCENTAGE = 1e17; // 10% // The swap fee is internally stored using 64 bits, which is enough to represent _MAX_SWAP_FEE_PERCENTAGE. bytes32 internal _miscData; uint256 private _lastInvariant; IVault private immutable _vault; bytes32 private immutable _poolId; IERC20 internal immutable _token0; IERC20 internal immutable _token1; uint256 private immutable _normalizedWeight0; uint256 private immutable _normalizedWeight1; // The protocol fees will always be charged using the token associated with the max weight in the pool. // Since these Pools will register tokens only once, we can assume this index will be constant. uint256 private immutable _maxWeightTokenIndex; // All token balances are normalized to behave as if the token had 18 decimals. We assume a token's decimals will // not change throughout its lifetime, and store the corresponding scaling factor for each at construction time. // These factors are always greater than or equal to one: tokens with more than 18 decimals are not supported. uint256 internal immutable _scalingFactor0; uint256 internal immutable _scalingFactor1; event OracleEnabledChanged(bool enabled); event SwapFeePercentageChanged(uint256 swapFeePercentage); modifier onlyVault(bytes32 poolId) { _require(msg.sender == address(getVault()), Errors.CALLER_NOT_VAULT); _require(poolId == getPoolId(), Errors.INVALID_POOL_ID); _; } struct NewPoolParams { IVault vault; string name; string symbol; IERC20 token0; IERC20 token1; uint256 normalizedWeight0; uint256 normalizedWeight1; uint256 swapFeePercentage; uint256 pauseWindowDuration; uint256 bufferPeriodDuration; bool oracleEnabled; address owner; } constructor(NewPoolParams memory params) // Base Pools are expected to be deployed using factories. By using the factory address as the action // disambiguator, we make all Pools deployed by the same factory share action identifiers. This allows for // simpler management of permissions (such as being able to manage granting the 'set fee percentage' action in // any Pool created by the same factory), while still making action identifiers unique among different factories // if the selectors match, preventing accidental errors. Authentication(bytes32(uint256(msg.sender))) BalancerPoolToken(params.name, params.symbol) BasePoolAuthorization(params.owner) TemporarilyPausable(params.pauseWindowDuration, params.bufferPeriodDuration) { _setOracleEnabled(params.oracleEnabled); _setSwapFeePercentage(params.swapFeePercentage); bytes32 poolId = params.vault.registerPool(IVault.PoolSpecialization.TWO_TOKEN); // Pass in zero addresses for Asset Managers IERC20[] memory tokens = new IERC20[](2); tokens[0] = params.token0; tokens[1] = params.token1; params.vault.registerTokens(poolId, tokens, new address[](2)); // Set immutable state variables - these cannot be read from during construction _vault = params.vault; _poolId = poolId; _token0 = params.token0; _token1 = params.token1; _scalingFactor0 = _computeScalingFactor(params.token0); _scalingFactor1 = _computeScalingFactor(params.token1); // Ensure each normalized weight is above them minimum and find the token index of the maximum weight _require(params.normalizedWeight0 >= _MIN_WEIGHT, Errors.MIN_WEIGHT); _require(params.normalizedWeight1 >= _MIN_WEIGHT, Errors.MIN_WEIGHT); // Ensure that the normalized weights sum to ONE uint256 normalizedSum = params.normalizedWeight0.add(params.normalizedWeight1); _require(normalizedSum == FixedPoint.ONE, Errors.NORMALIZED_WEIGHT_INVARIANT); _normalizedWeight0 = params.normalizedWeight0; _normalizedWeight1 = params.normalizedWeight1; _maxWeightTokenIndex = params.normalizedWeight0 >= params.normalizedWeight1 ? 0 : 1; } // Getters / Setters function getVault() public view returns (IVault) { return _vault; } function getPoolId() public view override returns (bytes32) { return _poolId; } function getMiscData() external view returns ( int256 logInvariant, int256 logTotalSupply, uint256 oracleSampleCreationTimestamp, uint256 oracleIndex, bool oracleEnabled, uint256 swapFeePercentage ) { bytes32 miscData = _miscData; logInvariant = miscData.logInvariant(); logTotalSupply = miscData.logTotalSupply(); oracleSampleCreationTimestamp = miscData.oracleSampleCreationTimestamp(); oracleIndex = miscData.oracleIndex(); oracleEnabled = miscData.oracleEnabled(); swapFeePercentage = miscData.swapFeePercentage(); } function getSwapFeePercentage() public view returns (uint256) { return _miscData.swapFeePercentage(); } // Caller must be approved by the Vault's Authorizer function setSwapFeePercentage(uint256 swapFeePercentage) public virtual authenticate whenNotPaused { _setSwapFeePercentage(swapFeePercentage); } function _setSwapFeePercentage(uint256 swapFeePercentage) private { _require(swapFeePercentage >= _MIN_SWAP_FEE_PERCENTAGE, Errors.MIN_SWAP_FEE_PERCENTAGE); _require(swapFeePercentage <= _MAX_SWAP_FEE_PERCENTAGE, Errors.MAX_SWAP_FEE_PERCENTAGE); _miscData = _miscData.setSwapFeePercentage(swapFeePercentage); emit SwapFeePercentageChanged(swapFeePercentage); } function _isOwnerOnlyAction(bytes32 actionId) internal view virtual override returns (bool) { return (actionId == getActionId(BasePool.setSwapFeePercentage.selector)) || (actionId == getActionId(BasePool.setAssetManagerPoolConfig.selector)); } /** * @dev Balancer Governance can always enable the Oracle, even if it was originally not enabled. This allows for * Pools that unexpectedly drive much more volume and liquidity than expected to serve as Price Oracles. * * Note that the Oracle can only be enabled - it can never be disabled. */ function enableOracle() external whenNotPaused authenticate { _setOracleEnabled(true); // Cache log invariant and supply only if the pool was initialized if (totalSupply() > 0) { _cacheInvariantAndSupply(); } } function _setOracleEnabled(bool enabled) internal { _miscData = _miscData.setOracleEnabled(enabled); emit OracleEnabledChanged(enabled); } // Caller must be approved by the Vault's Authorizer function setPaused(bool paused) external authenticate { _setPaused(paused); } function getNormalizedWeights() external view returns (uint256[] memory) { return _normalizedWeights(); } function _normalizedWeights() internal view virtual returns (uint256[] memory) { uint256[] memory normalizedWeights = new uint256[](2); normalizedWeights[0] = _normalizedWeights(true); normalizedWeights[1] = _normalizedWeights(false); return normalizedWeights; } function _normalizedWeights(bool token0) internal view virtual returns (uint256) { return token0 ? _normalizedWeight0 : _normalizedWeight1; } function getLastInvariant() external view returns (uint256) { return _lastInvariant; } /** * @dev Returns the current value of the invariant. */ function getInvariant() public view returns (uint256) { (, uint256[] memory balances, ) = getVault().getPoolTokens(getPoolId()); // Since the Pool hooks always work with upscaled balances, we manually // upscale here for consistency _upscaleArray(balances); uint256[] memory normalizedWeights = _normalizedWeights(); return WeightedMath._calculateInvariant(normalizedWeights, balances); } // Swap Hooks function onSwap( SwapRequest memory request, uint256 balanceTokenIn, uint256 balanceTokenOut ) public virtual override whenNotPaused onlyVault(request.poolId) returns (uint256) { bool tokenInIsToken0 = request.tokenIn == _token0; uint256 scalingFactorTokenIn = _scalingFactor(tokenInIsToken0); uint256 scalingFactorTokenOut = _scalingFactor(!tokenInIsToken0); uint256 normalizedWeightIn = _normalizedWeights(tokenInIsToken0); uint256 normalizedWeightOut = _normalizedWeights(!tokenInIsToken0); // All token amounts are upscaled. balanceTokenIn = _upscale(balanceTokenIn, scalingFactorTokenIn); balanceTokenOut = _upscale(balanceTokenOut, scalingFactorTokenOut); // Update price oracle with the pre-swap balances _updateOracle( request.lastChangeBlock, tokenInIsToken0 ? balanceTokenIn : balanceTokenOut, tokenInIsToken0 ? balanceTokenOut : balanceTokenIn ); if (request.kind == IVault.SwapKind.GIVEN_IN) { // Fees are subtracted before scaling, to reduce the complexity of the rounding direction analysis. // This is amount - fee amount, so we round up (favoring a higher fee amount). uint256 feeAmount = request.amount.mulUp(getSwapFeePercentage()); request.amount = _upscale(request.amount.sub(feeAmount), scalingFactorTokenIn); uint256 amountOut = _onSwapGivenIn( request, balanceTokenIn, balanceTokenOut, normalizedWeightIn, normalizedWeightOut ); // amountOut tokens are exiting the Pool, so we round down. return _downscaleDown(amountOut, scalingFactorTokenOut); } else { request.amount = _upscale(request.amount, scalingFactorTokenOut); uint256 amountIn = _onSwapGivenOut( request, balanceTokenIn, balanceTokenOut, normalizedWeightIn, normalizedWeightOut ); // amountIn tokens are entering the Pool, so we round up. amountIn = _downscaleUp(amountIn, scalingFactorTokenIn); // Fees are added after scaling happens, to reduce the complexity of the rounding direction analysis. // This is amount + fee amount, so we round up (favoring a higher fee amount). return amountIn.divUp(getSwapFeePercentage().complement()); } } function _onSwapGivenIn( SwapRequest memory swapRequest, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut, uint256 normalizedWeightIn, uint256 normalizedWeightOut ) private pure returns (uint256) { // Swaps are disabled while the contract is paused. return WeightedMath._calcOutGivenIn( currentBalanceTokenIn, normalizedWeightIn, currentBalanceTokenOut, normalizedWeightOut, swapRequest.amount ); } function _onSwapGivenOut( SwapRequest memory swapRequest, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut, uint256 normalizedWeightIn, uint256 normalizedWeightOut ) private pure returns (uint256) { // Swaps are disabled while the contract is paused. return WeightedMath._calcInGivenOut( currentBalanceTokenIn, normalizedWeightIn, currentBalanceTokenOut, normalizedWeightOut, swapRequest.amount ); } // Join Hook function onJoinPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) public virtual override onlyVault(poolId) whenNotPaused returns (uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts) { // All joins, including initializations, are disabled while the contract is paused. uint256 bptAmountOut; if (totalSupply() == 0) { (bptAmountOut, amountsIn) = _onInitializePool(poolId, sender, recipient, userData); // On initialization, we lock _MINIMUM_BPT by minting it for the zero address. This BPT acts as a minimum // as it will never be burned, which reduces potential issues with rounding, and also prevents the Pool from // ever being fully drained. _require(bptAmountOut >= _MINIMUM_BPT, Errors.MINIMUM_BPT); _mintPoolTokens(address(0), _MINIMUM_BPT); _mintPoolTokens(recipient, bptAmountOut - _MINIMUM_BPT); // amountsIn are amounts entering the Pool, so we round up. _downscaleUpArray(amountsIn); // There are no due protocol fee amounts during initialization dueProtocolFeeAmounts = new uint256[](2); } else { _upscaleArray(balances); // Update price oracle with the pre-join balances _updateOracle(lastChangeBlock, balances[0], balances[1]); (bptAmountOut, amountsIn, dueProtocolFeeAmounts) = _onJoinPool( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData ); // Note we no longer use `balances` after calling `_onJoinPool`, which may mutate it. _mintPoolTokens(recipient, bptAmountOut); // amountsIn are amounts entering the Pool, so we round up. _downscaleUpArray(amountsIn); // dueProtocolFeeAmounts are amounts exiting the Pool, so we round down. _downscaleDownArray(dueProtocolFeeAmounts); } // Update cached total supply and invariant using the results after the join that will be used for future // oracle updates. _cacheInvariantAndSupply(); } /** * @dev Called when the Pool is joined for the first time; that is, when the BPT total supply is zero. * * Returns the amount of BPT to mint, and the token amounts the Pool will receive in return. * * Minted BPT will be sent to `recipient`, except for _MINIMUM_BPT, which will be deducted from this amount and sent * to the zero address instead. This will cause that BPT to remain forever locked there, preventing total BTP from * ever dropping below that value, and ensuring `_onInitializePool` can only be called once in the entire Pool's * lifetime. * * The tokens granted to the Pool will be transferred from `sender`. These amounts are considered upscaled and will * be downscaled (rounding up) before being returned to the Vault. */ function _onInitializePool( bytes32, address, address, bytes memory userData ) private returns (uint256, uint256[] memory) { BaseWeightedPool.JoinKind kind = userData.joinKind(); _require(kind == BaseWeightedPool.JoinKind.INIT, Errors.UNINITIALIZED); uint256[] memory amountsIn = userData.initialAmountsIn(); InputHelpers.ensureInputLengthMatch(amountsIn.length, 2); _upscaleArray(amountsIn); uint256[] memory normalizedWeights = _normalizedWeights(); uint256 invariantAfterJoin = WeightedMath._calculateInvariant(normalizedWeights, amountsIn); // Set the initial BPT to the value of the invariant times the number of tokens. This makes BPT supply more // consistent in Pools with similar compositions but different number of tokens. uint256 bptAmountOut = Math.mul(invariantAfterJoin, 2); _lastInvariant = invariantAfterJoin; return (bptAmountOut, amountsIn); } /** * @dev Called whenever the Pool is joined after the first initialization join (see `_onInitializePool`). * * Returns the amount of BPT to mint, the token amounts that the Pool will receive in return, and the number of * tokens to pay in protocol swap fees. * * Implementations of this function might choose to mutate the `balances` array to save gas (e.g. when * performing intermediate calculations, such as subtraction of due protocol fees). This can be done safely. * * Minted BPT will be sent to `recipient`. * * The tokens granted to the Pool will be transferred from `sender`. These amounts are considered upscaled and will * be downscaled (rounding up) before being returned to the Vault. * * Due protocol swap fees will be taken from the Pool's balance in the Vault (see `IBasePool.onJoinPool`). These * amounts are considered upscaled and will be downscaled (rounding down) before being returned to the Vault. */ function _onJoinPool( bytes32, address, address, uint256[] memory balances, uint256, uint256 protocolSwapFeePercentage, bytes memory userData ) private returns ( uint256, uint256[] memory, uint256[] memory ) { uint256[] memory normalizedWeights = _normalizedWeights(); // Due protocol swap fee amounts are computed by measuring the growth of the invariant between the previous join // or exit event and now - the invariant's growth is due exclusively to swap fees. This avoids spending gas // computing them on each individual swap uint256 invariantBeforeJoin = WeightedMath._calculateInvariant(normalizedWeights, balances); uint256[] memory dueProtocolFeeAmounts = _getDueProtocolFeeAmounts( balances, normalizedWeights, _lastInvariant, invariantBeforeJoin, protocolSwapFeePercentage ); // Update current balances by subtracting the protocol fee amounts _mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub); (uint256 bptAmountOut, uint256[] memory amountsIn) = _doJoin(balances, normalizedWeights, userData); // Update the invariant with the balances the Pool will have after the join, in order to compute the // protocol swap fee amounts due in future joins and exits. _mutateAmounts(balances, amountsIn, FixedPoint.add); _lastInvariant = WeightedMath._calculateInvariant(normalizedWeights, balances); return (bptAmountOut, amountsIn, dueProtocolFeeAmounts); } function _doJoin( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { BaseWeightedPool.JoinKind kind = userData.joinKind(); if (kind == BaseWeightedPool.JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT) { return _joinExactTokensInForBPTOut(balances, normalizedWeights, userData); } else if (kind == BaseWeightedPool.JoinKind.TOKEN_IN_FOR_EXACT_BPT_OUT) { return _joinTokenInForExactBPTOut(balances, normalizedWeights, userData); } else if (kind == BaseWeightedPool.JoinKind.ALL_TOKENS_IN_FOR_EXACT_BPT_OUT) { return _joinAllTokensInForExactBPTOut(balances, userData); } else { _revert(Errors.UNHANDLED_JOIN_KIND); } } function _joinExactTokensInForBPTOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { (uint256[] memory amountsIn, uint256 minBPTAmountOut) = userData.exactTokensInForBptOut(); InputHelpers.ensureInputLengthMatch(amountsIn.length, 2); _upscaleArray(amountsIn); (uint256 bptAmountOut, ) = WeightedMath._calcBptOutGivenExactTokensIn( balances, normalizedWeights, amountsIn, totalSupply(), getSwapFeePercentage() ); _require(bptAmountOut >= minBPTAmountOut, Errors.BPT_OUT_MIN_AMOUNT); return (bptAmountOut, amountsIn); } function _joinTokenInForExactBPTOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { (uint256 bptAmountOut, uint256 tokenIndex) = userData.tokenInForExactBptOut(); // Note that there is no maximum amountIn parameter: this is handled by `IVault.joinPool`. _require(tokenIndex < 2, Errors.OUT_OF_BOUNDS); uint256[] memory amountsIn = new uint256[](2); (amountsIn[tokenIndex], ) = WeightedMath._calcTokenInGivenExactBptOut( balances[tokenIndex], normalizedWeights[tokenIndex], bptAmountOut, totalSupply(), getSwapFeePercentage() ); return (bptAmountOut, amountsIn); } function _joinAllTokensInForExactBPTOut(uint256[] memory balances, bytes memory userData) private view returns (uint256, uint256[] memory) { uint256 bptAmountOut = userData.allTokensInForExactBptOut(); // Note that there is no maximum amountsIn parameter: this is handled by `IVault.joinPool`. uint256[] memory amountsIn = WeightedMath._calcAllTokensInGivenExactBptOut( balances, bptAmountOut, totalSupply() ); return (bptAmountOut, amountsIn); } // Exit Hook function onExitPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) public virtual override onlyVault(poolId) returns (uint256[] memory, uint256[] memory) { _upscaleArray(balances); (uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts) = _onExitPool( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData ); // Note we no longer use `balances` after calling `_onExitPool`, which may mutate it. _burnPoolTokens(sender, bptAmountIn); // Both amountsOut and dueProtocolFeeAmounts are amounts exiting the Pool, so we round down. _downscaleDownArray(amountsOut); _downscaleDownArray(dueProtocolFeeAmounts); // Update cached total supply and invariant using the results after the exit that will be used for future // oracle updates, only if the pool was not paused (to minimize code paths taken while paused). if (_isNotPaused()) { _cacheInvariantAndSupply(); } return (amountsOut, dueProtocolFeeAmounts); } /** * @dev Called whenever the Pool is exited. * * Returns the amount of BPT to burn, the token amounts for each Pool token that the Pool will grant in return, and * the number of tokens to pay in protocol swap fees. * * Implementations of this function might choose to mutate the `balances` array to save gas (e.g. when * performing intermediate calculations, such as subtraction of due protocol fees). This can be done safely. * * BPT will be burnt from `sender`. * * The Pool will grant tokens to `recipient`. These amounts are considered upscaled and will be downscaled * (rounding down) before being returned to the Vault. * * Due protocol swap fees will be taken from the Pool's balance in the Vault (see `IBasePool.onExitPool`). These * amounts are considered upscaled and will be downscaled (rounding down) before being returned to the Vault. */ function _onExitPool( bytes32, address, address, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) private returns ( uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts ) { // Exits are not completely disabled while the contract is paused: proportional exits (exact BPT in for tokens // out) remain functional. uint256[] memory normalizedWeights = _normalizedWeights(); if (_isNotPaused()) { // Update price oracle with the pre-exit balances _updateOracle(lastChangeBlock, balances[0], balances[1]); // Due protocol swap fee amounts are computed by measuring the growth of the invariant between the previous // join or exit event and now - the invariant's growth is due exclusively to swap fees. This avoids // spending gas calculating the fees on each individual swap. uint256 invariantBeforeExit = WeightedMath._calculateInvariant(normalizedWeights, balances); dueProtocolFeeAmounts = _getDueProtocolFeeAmounts( balances, normalizedWeights, _lastInvariant, invariantBeforeExit, protocolSwapFeePercentage ); // Update current balances by subtracting the protocol fee amounts _mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub); } else { // If the contract is paused, swap protocol fee amounts are not charged and the oracle is not updated // to avoid extra calculations and reduce the potential for errors. dueProtocolFeeAmounts = new uint256[](2); } (bptAmountIn, amountsOut) = _doExit(balances, normalizedWeights, userData); // Update the invariant with the balances the Pool will have after the exit, in order to compute the // protocol swap fees due in future joins and exits. _mutateAmounts(balances, amountsOut, FixedPoint.sub); _lastInvariant = WeightedMath._calculateInvariant(normalizedWeights, balances); return (bptAmountIn, amountsOut, dueProtocolFeeAmounts); } function _doExit( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { BaseWeightedPool.ExitKind kind = userData.exitKind(); if (kind == BaseWeightedPool.ExitKind.EXACT_BPT_IN_FOR_ONE_TOKEN_OUT) { return _exitExactBPTInForTokenOut(balances, normalizedWeights, userData); } else if (kind == BaseWeightedPool.ExitKind.EXACT_BPT_IN_FOR_TOKENS_OUT) { return _exitExactBPTInForTokensOut(balances, userData); } else if (kind == BaseWeightedPool.ExitKind.BPT_IN_FOR_EXACT_TOKENS_OUT) { return _exitBPTInForExactTokensOut(balances, normalizedWeights, userData); } else { _revert(Errors.UNHANDLED_EXIT_KIND); } } function _exitExactBPTInForTokenOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view whenNotPaused returns (uint256, uint256[] memory) { // This exit function is disabled if the contract is paused. (uint256 bptAmountIn, uint256 tokenIndex) = userData.exactBptInForTokenOut(); // Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`. _require(tokenIndex < 2, Errors.OUT_OF_BOUNDS); // We exit in a single token, so we initialize amountsOut with zeros uint256[] memory amountsOut = new uint256[](2); // And then assign the result to the selected token (amountsOut[tokenIndex], ) = WeightedMath._calcTokenOutGivenExactBptIn( balances[tokenIndex], normalizedWeights[tokenIndex], bptAmountIn, totalSupply(), getSwapFeePercentage() ); return (bptAmountIn, amountsOut); } function _exitExactBPTInForTokensOut(uint256[] memory balances, bytes memory userData) private view returns (uint256, uint256[] memory) { // This exit function is the only one that is not disabled if the contract is paused: it remains unrestricted // in an attempt to provide users with a mechanism to retrieve their tokens in case of an emergency. // This particular exit function is the only one that remains available because it is the simplest one, and // therefore the one with the lowest likelihood of errors. uint256 bptAmountIn = userData.exactBptInForTokensOut(); // Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`. uint256[] memory amountsOut = WeightedMath._calcTokensOutGivenExactBptIn(balances, bptAmountIn, totalSupply()); return (bptAmountIn, amountsOut); } function _exitBPTInForExactTokensOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view whenNotPaused returns (uint256, uint256[] memory) { // This exit function is disabled if the contract is paused. (uint256[] memory amountsOut, uint256 maxBPTAmountIn) = userData.bptInForExactTokensOut(); InputHelpers.ensureInputLengthMatch(amountsOut.length, 2); _upscaleArray(amountsOut); (uint256 bptAmountIn, ) = WeightedMath._calcBptInGivenExactTokensOut( balances, normalizedWeights, amountsOut, totalSupply(), getSwapFeePercentage() ); _require(bptAmountIn <= maxBPTAmountIn, Errors.BPT_IN_MAX_AMOUNT); return (bptAmountIn, amountsOut); } // Oracle functions /** * @dev Updates the Price Oracle based on the Pool's current state (balances, BPT supply and invariant). Must be * called on *all* state-changing functions with the balances *before* the state change happens, and with * `lastChangeBlock` as the number of the block in which any of the balances last changed. */ function _updateOracle( uint256 lastChangeBlock, uint256 balanceToken0, uint256 balanceToken1 ) internal { bytes32 miscData = _miscData; if (miscData.oracleEnabled() && block.number > lastChangeBlock) { int256 logSpotPrice = WeightedOracleMath._calcLogSpotPrice( _normalizedWeight0, balanceToken0, _normalizedWeight1, balanceToken1 ); int256 logBPTPrice = WeightedOracleMath._calcLogBPTPrice( _normalizedWeight0, balanceToken0, miscData.logTotalSupply() ); uint256 oracleCurrentIndex = miscData.oracleIndex(); uint256 oracleCurrentSampleInitialTimestamp = miscData.oracleSampleCreationTimestamp(); uint256 oracleUpdatedIndex = _processPriceData( oracleCurrentSampleInitialTimestamp, oracleCurrentIndex, logSpotPrice, logBPTPrice, miscData.logInvariant() ); if (oracleCurrentIndex != oracleUpdatedIndex) { // solhint-disable not-rely-on-time miscData = miscData.setOracleIndex(oracleUpdatedIndex); miscData = miscData.setOracleSampleCreationTimestamp(block.timestamp); _miscData = miscData; } } } /** * @dev Stores the logarithm of the invariant and BPT total supply, to be later used in each oracle update. Because * it is stored in miscData, which is read in all operations (including swaps), this saves gas by not requiring to * compute or read these values when updating the oracle. * * This function must be called by all actions that update the invariant and BPT supply (joins and exits). Swaps * also alter the invariant due to collected swap fees, but this growth is considered negligible and not accounted * for. */ function _cacheInvariantAndSupply() internal { bytes32 miscData = _miscData; if (miscData.oracleEnabled()) { miscData = miscData.setLogInvariant(LogCompression.toLowResLog(_lastInvariant)); miscData = miscData.setLogTotalSupply(LogCompression.toLowResLog(totalSupply())); _miscData = miscData; } } function _getOracleIndex() internal view override returns (uint256) { return _miscData.oracleIndex(); } // Query functions /** * @dev Returns the amount of BPT that would be granted to `recipient` if the `onJoinPool` hook were called by the * Vault with the same arguments, along with the number of tokens `sender` would have to supply. * * This function is not meant to be called directly, but rather from a helper contract that fetches current Vault * data, such as the protocol swap fee percentage and Pool balances. * * Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must * explicitly use eth_call instead of eth_sendTransaction. */ function queryJoin( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256 bptOut, uint256[] memory amountsIn) { InputHelpers.ensureInputLengthMatch(balances.length, 2); _queryAction( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData, _onJoinPool, _downscaleUpArray ); // The `return` opcode is executed directly inside `_queryAction`, so execution never reaches this statement, // and we don't need to return anything here - it just silences compiler warnings. return (bptOut, amountsIn); } /** * @dev Returns the amount of BPT that would be burned from `sender` if the `onExitPool` hook were called by the * Vault with the same arguments, along with the number of tokens `recipient` would receive. * * This function is not meant to be called directly, but rather from a helper contract that fetches current Vault * data, such as the protocol swap fee percentage and Pool balances. * * Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must * explicitly use eth_call instead of eth_sendTransaction. */ function queryExit( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256 bptIn, uint256[] memory amountsOut) { InputHelpers.ensureInputLengthMatch(balances.length, 2); _queryAction( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData, _onExitPool, _downscaleDownArray ); // The `return` opcode is executed directly inside `_queryAction`, so execution never reaches this statement, // and we don't need to return anything here - it just silences compiler warnings. return (bptIn, amountsOut); } // Helpers function _getDueProtocolFeeAmounts( uint256[] memory balances, uint256[] memory normalizedWeights, uint256 previousInvariant, uint256 currentInvariant, uint256 protocolSwapFeePercentage ) private view returns (uint256[] memory) { // Initialize with zeros uint256[] memory dueProtocolFeeAmounts = new uint256[](2); // Early return if the protocol swap fee percentage is zero, saving gas. if (protocolSwapFeePercentage == 0) { return dueProtocolFeeAmounts; } // The protocol swap fees are always paid using the token with the largest weight in the Pool. As this is the // token that is expected to have the largest balance, using it to pay fees should not unbalance the Pool. dueProtocolFeeAmounts[_maxWeightTokenIndex] = WeightedMath._calcDueTokenProtocolSwapFeeAmount( balances[_maxWeightTokenIndex], normalizedWeights[_maxWeightTokenIndex], previousInvariant, currentInvariant, protocolSwapFeePercentage ); return dueProtocolFeeAmounts; } /** * @dev Mutates `amounts` by applying `mutation` with each entry in `arguments`. * * Equivalent to `amounts = amounts.map(mutation)`. */ function _mutateAmounts( uint256[] memory toMutate, uint256[] memory arguments, function(uint256, uint256) pure returns (uint256) mutation ) private pure { toMutate[0] = mutation(toMutate[0], arguments[0]); toMutate[1] = mutation(toMutate[1], arguments[1]); } /** * @dev This function returns the appreciation of one BPT relative to the * underlying tokens. This starts at 1 when the pool is created and grows over time */ function getRate() public view returns (uint256) { // The initial BPT supply is equal to the invariant times the number of tokens. return Math.mul(getInvariant(), 2).divDown(totalSupply()); } // Scaling /** * @dev Returns a scaling factor that, when multiplied to a token amount for `token`, normalizes its balance as if * it had 18 decimals. */ function _computeScalingFactor(IERC20 token) private view returns (uint256) { // Tokens that don't implement the `decimals` method are not supported. uint256 tokenDecimals = ERC20(address(token)).decimals(); // Tokens with more than 18 decimals are not supported. uint256 decimalsDifference = Math.sub(18, tokenDecimals); return 10**decimalsDifference; } /** * @dev Returns the scaling factor for one of the Pool's tokens. Reverts if `token` is not a token registered by the * Pool. */ function _scalingFactor(bool token0) internal view returns (uint256) { return token0 ? _scalingFactor0 : _scalingFactor1; } /** * @dev Applies `scalingFactor` to `amount`, resulting in a larger or equal value depending on whether it needed * scaling or not. */ function _upscale(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { return Math.mul(amount, scalingFactor); } /** * @dev Same as `_upscale`, but for an entire array (of two elements). This function does not return anything, but * instead *mutates* the `amounts` array. */ function _upscaleArray(uint256[] memory amounts) internal view { amounts[0] = Math.mul(amounts[0], _scalingFactor(true)); amounts[1] = Math.mul(amounts[1], _scalingFactor(false)); } /** * @dev Reverses the `scalingFactor` applied to `amount`, resulting in a smaller or equal value depending on * whether it needed scaling or not. The result is rounded down. */ function _downscaleDown(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { return Math.divDown(amount, scalingFactor); } /** * @dev Same as `_downscaleDown`, but for an entire array (of two elements). This function does not return anything, * but instead *mutates* the `amounts` array. */ function _downscaleDownArray(uint256[] memory amounts) internal view { amounts[0] = Math.divDown(amounts[0], _scalingFactor(true)); amounts[1] = Math.divDown(amounts[1], _scalingFactor(false)); } /** * @dev Reverses the `scalingFactor` applied to `amount`, resulting in a smaller or equal value depending on * whether it needed scaling or not. The result is rounded up. */ function _downscaleUp(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { return Math.divUp(amount, scalingFactor); } /** * @dev Same as `_downscaleUp`, but for an entire array (of two elements). This function does not return anything, * but instead *mutates* the `amounts` array. */ function _downscaleUpArray(uint256[] memory amounts) internal view { amounts[0] = Math.divUp(amounts[0], _scalingFactor(true)); amounts[1] = Math.divUp(amounts[1], _scalingFactor(false)); } function _getAuthorizer() internal view override returns (IAuthorizer) { // Access control management is delegated to the Vault's Authorizer. This lets Balancer Governance manage which // accounts can call permissioned functions: for example, to perform emergency pauses. // If the owner is delegated, then *all* permissioned functions, including `setSwapFeePercentage`, will be under // Governance control. return getVault().getAuthorizer(); } function _queryAction( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData, function(bytes32, address, address, uint256[] memory, uint256, uint256, bytes memory) internal returns (uint256, uint256[] memory, uint256[] memory) _action, function(uint256[] memory) internal view _downscaleArray ) private { // This uses the same technique used by the Vault in queryBatchSwap. Refer to that function for a detailed // explanation. if (msg.sender != address(this)) { // We perform an external call to ourselves, forwarding the same calldata. In this call, the else clause of // the preceding if statement will be executed instead. // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(msg.data); // solhint-disable-next-line no-inline-assembly assembly { // This call should always revert to decode the bpt and token amounts from the revert reason switch success case 0 { // Note we are manually writing the memory slot 0. We can safely overwrite whatever is // stored there as we take full control of the execution and then immediately return. // We copy the first 4 bytes to check if it matches with the expected signature, otherwise // there was another revert reason and we should forward it. returndatacopy(0, 0, 0x04) let error := and(mload(0), 0xffffffff00000000000000000000000000000000000000000000000000000000) // If the first 4 bytes don't match with the expected signature, we forward the revert reason. if eq(eq(error, 0x43adbafb00000000000000000000000000000000000000000000000000000000), 0) { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } // The returndata contains the signature, followed by the raw memory representation of the // `bptAmount` and `tokenAmounts` (array: length + data). We need to return an ABI-encoded // representation of these. // An ABI-encoded response will include one additional field to indicate the starting offset of // the `tokenAmounts` array. The `bptAmount` will be laid out in the first word of the // returndata. // // In returndata: // [ signature ][ bptAmount ][ tokenAmounts length ][ tokenAmounts values ] // [ 4 bytes ][ 32 bytes ][ 32 bytes ][ (32 * length) bytes ] // // We now need to return (ABI-encoded values): // [ bptAmount ][ tokeAmounts offset ][ tokenAmounts length ][ tokenAmounts values ] // [ 32 bytes ][ 32 bytes ][ 32 bytes ][ (32 * length) bytes ] // We copy 32 bytes for the `bptAmount` from returndata into memory. // Note that we skip the first 4 bytes for the error signature returndatacopy(0, 0x04, 32) // The offsets are 32-bytes long, so the array of `tokenAmounts` will start after // the initial 64 bytes. mstore(0x20, 64) // We now copy the raw memory array for the `tokenAmounts` from returndata into memory. // Since bpt amount and offset take up 64 bytes, we start copying at address 0x40. We also // skip the first 36 bytes from returndata, which correspond to the signature plus bpt amount. returndatacopy(0x40, 0x24, sub(returndatasize(), 36)) // We finally return the ABI-encoded uint256 and the array, which has a total length equal to // the size of returndata, plus the 32 bytes of the offset but without the 4 bytes of the // error signature. return(0, add(returndatasize(), 28)) } default { // This call should always revert, but we fail nonetheless if that didn't happen invalid() } } } else { _upscaleArray(balances); (uint256 bptAmount, uint256[] memory tokenAmounts, ) = _action( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData ); _downscaleArray(tokenAmounts); // solhint-disable-next-line no-inline-assembly assembly { // We will return a raw representation of `bptAmount` and `tokenAmounts` in memory, which is composed of // a 32-byte uint256, followed by a 32-byte for the array length, and finally the 32-byte uint256 values // Because revert expects a size in bytes, we multiply the array length (stored at `tokenAmounts`) by 32 let size := mul(mload(tokenAmounts), 32) // We store the `bptAmount` in the previous slot to the `tokenAmounts` array. We can make sure there // will be at least one available slot due to how the memory scratch space works. // We can safely overwrite whatever is stored in this slot as we will revert immediately after that. let start := sub(tokenAmounts, 0x20) mstore(start, bptAmount) // We send one extra value for the error signature "QueryError(uint256,uint256[])" which is 0x43adbafb // We use the previous slot to `bptAmount`. mstore(sub(start, 0x20), 0x0000000000000000000000000000000000000000000000000000000043adbafb) start := sub(start, 0x04) // When copying from `tokenAmounts` into returndata, we copy the additional 68 bytes to also return // the `bptAmount`, the array length, and the error signature. revert(start, add(size, 68)) } } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../math/LogExpMath.sol"; /** * @dev Library for encoding and decoding values stored inside a 256 bit word. Typically used to pack multiple values in * a single storage slot, saving gas by performing less storage accesses. * * Each value is defined by its size and the least significant bit in the word, also known as offset. For example, two * 128 bit values may be encoded in a word by assigning one an offset of 0, and the other an offset of 128. */ library LogCompression { int256 private constant _LOG_COMPRESSION_FACTOR = 1e14; int256 private constant _HALF_LOG_COMPRESSION_FACTOR = 0.5e14; /** * @dev Returns the natural logarithm of `value`, dropping most of the decimal places to arrive at a value that, * when passed to `fromLowResLog`, will have a maximum relative error of ~0.05% compared to `value`. * * Values returned from this function should not be mixed with other fixed-point values (as they have a different * number of digits), but can be added or subtracted. Use `fromLowResLog` to undo this process and return to an * 18 decimal places fixed point value. * * Because so much precision is lost, the logarithmic values can be stored using much fewer bits than the original * value required. */ function toLowResLog(uint256 value) internal pure returns (int256) { int256 ln = LogExpMath.ln(int256(value)); // Rounding division for signed numerator int256 lnWithError = (ln > 0 ? ln + _HALF_LOG_COMPRESSION_FACTOR : ln - _HALF_LOG_COMPRESSION_FACTOR); return lnWithError / _LOG_COMPRESSION_FACTOR; } /** * @dev Restores `value` from logarithmic space. `value` is expected to be the result of a call to `toLowResLog`, * any other function that returns 4 decimals fixed point logarithms, or the sum of such values. */ function fromLowResLog(int256 value) internal pure returns (uint256) { return uint256(LogExpMath.exp(value * _LOG_COMPRESSION_FACTOR)); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/helpers/BalancerErrors.sol"; import "../interfaces/IPriceOracle.sol"; import "../interfaces/IPoolPriceOracle.sol"; import "./Buffer.sol"; import "./Samples.sol"; import "./QueryProcessor.sol"; /** * @dev This module allows Pools to access historical pricing information. * * It uses a 1024 long circular buffer to store past data, where the data within each sample is the result of * accumulating live data for no more than two minutes. Therefore, assuming the worst case scenario where new data is * updated in every single block, the oldest samples in the buffer (and therefore largest queryable period) will * be slightly over 34 hours old. * * Usage of this module requires the caller to keep track of two variables: the latest circular buffer index, and the * timestamp when the index last changed. Aditionally, access to the latest circular buffer index must be exposed by * implementing `_getOracleIndex`. * * This contract relies on the `QueryProcessor` linked library to reduce bytecode size. */ abstract contract PoolPriceOracle is IPoolPriceOracle, IPriceOracle { using Buffer for uint256; using Samples for bytes32; // Each sample in the buffer accumulates information for up to 2 minutes. This is simply to reduce the size of the // buffer: small time deviations will not have any significant effect. // solhint-disable not-rely-on-time uint256 private constant _MAX_SAMPLE_DURATION = 2 minutes; // We use a mapping to simulate an array: the buffer won't grow or shrink, and since we will always use valid // indexes using a mapping saves gas by skipping the bounds checks. mapping(uint256 => bytes32) internal _samples; // IPoolPriceOracle function getSample(uint256 index) external view override returns ( int256 logPairPrice, int256 accLogPairPrice, int256 logBptPrice, int256 accLogBptPrice, int256 logInvariant, int256 accLogInvariant, uint256 timestamp ) { _require(index < Buffer.SIZE, Errors.ORACLE_INVALID_INDEX); bytes32 sample = _getSample(index); return sample.unpack(); } function getTotalSamples() external pure override returns (uint256) { return Buffer.SIZE; } /** * @dev Manually dirty oracle sample storage slots with dummy data, to reduce the gas cost of the future swaps * that will initialize them. This function is only useful before the oracle has been fully initialized. * * `endIndex` is non-inclusive. */ function dirtyUninitializedOracleSamples(uint256 startIndex, uint256 endIndex) external { _require(startIndex < endIndex && endIndex <= Buffer.SIZE, Errors.OUT_OF_BOUNDS); // Uninitialized samples are identified by a zero timestamp -- all other fields are ignored, // so any non-zero value with a zero timestamp suffices. bytes32 initSample = Samples.pack(1, 0, 0, 0, 0, 0, 0); for (uint256 i = startIndex; i < endIndex; i++) { if (_samples[i].timestamp() == 0) { _samples[i] = initSample; } } } // IPriceOracle function getLargestSafeQueryWindow() external pure override returns (uint256) { return 34 hours; } function getLatest(Variable variable) external view override returns (uint256) { return QueryProcessor.getInstantValue(_samples, variable, _getOracleIndex()); } function getTimeWeightedAverage(OracleAverageQuery[] memory queries) external view override returns (uint256[] memory results) { results = new uint256[](queries.length); uint256 latestIndex = _getOracleIndex(); for (uint256 i = 0; i < queries.length; ++i) { results[i] = QueryProcessor.getTimeWeightedAverage(_samples, queries[i], latestIndex); } } function getPastAccumulators(OracleAccumulatorQuery[] memory queries) external view override returns (int256[] memory results) { results = new int256[](queries.length); uint256 latestIndex = _getOracleIndex(); OracleAccumulatorQuery memory query; for (uint256 i = 0; i < queries.length; ++i) { query = queries[i]; results[i] = _getPastAccumulator(query.variable, latestIndex, query.ago); } } // Internal functions /** * @dev Processes new price and invariant data, updating the latest sample or creating a new one. * * Receives the new logarithms of values to store: `logPairPrice`, `logBptPrice` and `logInvariant`, as well the * index of the latest sample and the timestamp of its creation. * * Returns the index of the latest sample. If different from `latestIndex`, the caller should also store the * timestamp, and pass it on future calls to this function. */ function _processPriceData( uint256 latestSampleCreationTimestamp, uint256 latestIndex, int256 logPairPrice, int256 logBptPrice, int256 logInvariant ) internal returns (uint256) { // Read latest sample, and compute the next one by updating it with the newly received data. bytes32 sample = _getSample(latestIndex).update(logPairPrice, logBptPrice, logInvariant, block.timestamp); // We create a new sample if more than _MAX_SAMPLE_DURATION seconds have elapsed since the creation of the // latest one. In other words, no sample accumulates data over a period larger than _MAX_SAMPLE_DURATION. bool newSample = block.timestamp - latestSampleCreationTimestamp >= _MAX_SAMPLE_DURATION; latestIndex = newSample ? latestIndex.next() : latestIndex; // Store the updated or new sample. _samples[latestIndex] = sample; return latestIndex; } function _getPastAccumulator( IPriceOracle.Variable variable, uint256 latestIndex, uint256 ago ) internal view returns (int256) { return QueryProcessor.getPastAccumulator(_samples, variable, latestIndex, ago); } function _findNearestSample( uint256 lookUpDate, uint256 offset, uint256 length ) internal view returns (bytes32 prev, bytes32 next) { return QueryProcessor.findNearestSample(_samples, lookUpDate, offset, length); } /** * @dev Returns the sample that corresponds to a given `index`. * * Using this function instead of accessing storage directly results in denser bytecode (since the storage slot is * only computed here). */ function _getSample(uint256 index) internal view returns (bytes32) { return _samples[index]; } /** * @dev Virtual function to be implemented by derived contracts. Must return the current index of the oracle * circular buffer. */ function _getOracleIndex() internal view virtual returns (uint256); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; library Buffer { // The buffer is a circular storage structure with 1024 slots. // solhint-disable-next-line private-vars-leading-underscore uint256 internal constant SIZE = 1024; /** * @dev Returns the index of the element before the one pointed by `index`. */ function prev(uint256 index) internal pure returns (uint256) { return sub(index, 1); } /** * @dev Returns the index of the element after the one pointed by `index`. */ function next(uint256 index) internal pure returns (uint256) { return add(index, 1); } /** * @dev Returns the index of an element `offset` slots after the one pointed by `index`. */ function add(uint256 index, uint256 offset) internal pure returns (uint256) { return (index + offset) % SIZE; } /** * @dev Returns the index of an element `offset` slots before the one pointed by `index`. */ function sub(uint256 index, uint256 offset) internal pure returns (uint256) { return (index + SIZE - offset) % SIZE; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/math/FixedPoint.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/LogCompression.sol"; contract WeightedOracleMath { using FixedPoint for uint256; /** * @dev Calculates the logarithm of the spot price of token B in token A. * * The return value is a 4 decimal fixed-point number: use `LogCompression.fromLowResLog` * to recover the original value. */ function _calcLogSpotPrice( uint256 normalizedWeightA, uint256 balanceA, uint256 normalizedWeightB, uint256 balanceB ) internal pure returns (int256) { // Max balances are 2^112 and min weights are 0.01, so the division never overflows. // The rounding direction is irrelevant as we're about to introduce a much larger error when converting to log // space. We use `divUp` as it prevents the result from being zero, which would make the logarithm revert. A // result of zero is therefore only possible with zero balances, which are prevented via other means. uint256 spotPrice = balanceA.divUp(normalizedWeightA).divUp(balanceB.divUp(normalizedWeightB)); return LogCompression.toLowResLog(spotPrice); } /** * @dev Calculates the price of BPT in a token. `logBptTotalSupply` should be the result of calling `toLowResLog` * with the current BPT supply. * * The return value is a 4 decimal fixed-point number: use `LogCompression.fromLowResLog` * to recover the original value. */ function _calcLogBPTPrice( uint256 normalizedWeight, uint256 balance, int256 logBptTotalSupply ) internal pure returns (int256) { // BPT price = (balance / weight) / total supply // Since we already have ln(total supply) and want to compute ln(BPT price), we perform the computation in log // space directly: ln(BPT price) = ln(balance / weight) - ln(total supply) // The rounding direction is irrelevant as we're about to introduce a much larger error when converting to log // space. We use `divUp` as it prevents the result from being zero, which would make the logarithm revert. A // result of zero is therefore only possible with zero balances, which are prevented via other means. uint256 balanceOverWeight = balance.divUp(normalizedWeight); int256 logBalanceOverWeight = LogCompression.toLowResLog(balanceOverWeight); // Because we're subtracting two values in log space, this value has a larger error (+-0.0001 instead of // +-0.00005), which results in a final larger relative error of around 0.1%. return logBalanceOverWeight - logBptTotalSupply; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/helpers/WordCodec.sol"; /** * @dev This module provides an interface to store seemingly unrelated pieces of information, in particular used by * pools with a price oracle. * * These pieces of information are all kept together in a single storage slot to reduce the number of storage reads. In * particular, we not only store configuration values (such as the swap fee percentage), but also cache * reduced-precision versions of the total BPT supply and invariant, which lets us not access nor compute these values * when producing oracle updates during a swap. * * Data is stored with the following structure: * * [ swap fee pct | oracle enabled | oracle index | oracle sample initial timestamp | log supply | log invariant ] * [ uint64 | bool | uint10 | uint31 | int22 | int22 ] * * Note that we are not using the most-significant 106 bits. */ library WeightedPool2TokensMiscData { using WordCodec for bytes32; using WordCodec for uint256; uint256 private constant _LOG_INVARIANT_OFFSET = 0; uint256 private constant _LOG_TOTAL_SUPPLY_OFFSET = 22; uint256 private constant _ORACLE_SAMPLE_CREATION_TIMESTAMP_OFFSET = 44; uint256 private constant _ORACLE_INDEX_OFFSET = 75; uint256 private constant _ORACLE_ENABLED_OFFSET = 85; uint256 private constant _SWAP_FEE_PERCENTAGE_OFFSET = 86; /** * @dev Returns the cached logarithm of the invariant. */ function logInvariant(bytes32 data) internal pure returns (int256) { return data.decodeInt22(_LOG_INVARIANT_OFFSET); } /** * @dev Returns the cached logarithm of the total supply. */ function logTotalSupply(bytes32 data) internal pure returns (int256) { return data.decodeInt22(_LOG_TOTAL_SUPPLY_OFFSET); } /** * @dev Returns the timestamp of the creation of the oracle's latest sample. */ function oracleSampleCreationTimestamp(bytes32 data) internal pure returns (uint256) { return data.decodeUint31(_ORACLE_SAMPLE_CREATION_TIMESTAMP_OFFSET); } /** * @dev Returns the index of the oracle's latest sample. */ function oracleIndex(bytes32 data) internal pure returns (uint256) { return data.decodeUint10(_ORACLE_INDEX_OFFSET); } /** * @dev Returns true if the oracle is enabled. */ function oracleEnabled(bytes32 data) internal pure returns (bool) { return data.decodeBool(_ORACLE_ENABLED_OFFSET); } /** * @dev Returns the swap fee percentage. */ function swapFeePercentage(bytes32 data) internal pure returns (uint256) { return data.decodeUint64(_SWAP_FEE_PERCENTAGE_OFFSET); } /** * @dev Sets the logarithm of the invariant in `data`, returning the updated value. */ function setLogInvariant(bytes32 data, int256 _logInvariant) internal pure returns (bytes32) { return data.insertInt22(_logInvariant, _LOG_INVARIANT_OFFSET); } /** * @dev Sets the logarithm of the total supply in `data`, returning the updated value. */ function setLogTotalSupply(bytes32 data, int256 _logTotalSupply) internal pure returns (bytes32) { return data.insertInt22(_logTotalSupply, _LOG_TOTAL_SUPPLY_OFFSET); } /** * @dev Sets the timestamp of the creation of the oracle's latest sample in `data`, returning the updated value. */ function setOracleSampleCreationTimestamp(bytes32 data, uint256 _initialTimestamp) internal pure returns (bytes32) { return data.insertUint31(_initialTimestamp, _ORACLE_SAMPLE_CREATION_TIMESTAMP_OFFSET); } /** * @dev Sets the index of the oracle's latest sample in `data`, returning the updated value. */ function setOracleIndex(bytes32 data, uint256 _oracleIndex) internal pure returns (bytes32) { return data.insertUint10(_oracleIndex, _ORACLE_INDEX_OFFSET); } /** * @dev Enables or disables the oracle in `data`, returning the updated value. */ function setOracleEnabled(bytes32 data, bool _oracleEnabled) internal pure returns (bytes32) { return data.insertBool(_oracleEnabled, _ORACLE_ENABLED_OFFSET); } /** * @dev Sets the swap fee percentage in `data`, returning the updated value. */ function setSwapFeePercentage(bytes32 data, uint256 _swapFeePercentage) internal pure returns (bytes32) { return data.insertUint64(_swapFeePercentage, _SWAP_FEE_PERCENTAGE_OFFSET); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; /** * @dev Interface for querying historical data from a Pool that can be used as a Price Oracle. * * This lets third parties retrieve average prices of tokens held by a Pool over a given period of time, as well as the * price of the Pool share token (BPT) and invariant. Since the invariant is a sensible measure of Pool liquidity, it * can be used to compare two different price sources, and choose the most liquid one. * * Once the oracle is fully initialized, all queries are guaranteed to succeed as long as they require no data that * is not older than the largest safe query window. */ interface IPriceOracle { // The three values that can be queried: // // - PAIR_PRICE: the price of the tokens in the Pool, expressed as the price of the second token in units of the // first token. For example, if token A is worth $2, and token B is worth $4, the pair price will be 2.0. // Note that the price is computed *including* the tokens decimals. This means that the pair price of a Pool with // DAI and USDC will be close to 1.0, despite DAI having 18 decimals and USDC 6. // // - BPT_PRICE: the price of the Pool share token (BPT), in units of the first token. // Note that the price is computed *including* the tokens decimals. This means that the BPT price of a Pool with // USDC in which BPT is worth $5 will be 5.0, despite the BPT having 18 decimals and USDC 6. // // - INVARIANT: the value of the Pool's invariant, which serves as a measure of its liquidity. enum Variable { PAIR_PRICE, BPT_PRICE, INVARIANT } /** * @dev Returns the time average weighted price corresponding to each of `queries`. Prices are represented as 18 * decimal fixed point values. */ function getTimeWeightedAverage(OracleAverageQuery[] memory queries) external view returns (uint256[] memory results); /** * @dev Returns latest sample of `variable`. Prices are represented as 18 decimal fixed point values. */ function getLatest(Variable variable) external view returns (uint256); /** * @dev Information for a Time Weighted Average query. * * Each query computes the average over a window of duration `secs` seconds that ended `ago` seconds ago. For * example, the average over the past 30 minutes is computed by settings secs to 1800 and ago to 0. If secs is 1800 * and ago is 1800 as well, the average between 60 and 30 minutes ago is computed instead. */ struct OracleAverageQuery { Variable variable; uint256 secs; uint256 ago; } /** * @dev Returns largest time window that can be safely queried, where 'safely' means the Oracle is guaranteed to be * able to produce a result and not revert. * * If a query has a non-zero `ago` value, then `secs + ago` (the oldest point in time) must be smaller than this * value for 'safe' queries. */ function getLargestSafeQueryWindow() external view returns (uint256); /** * @dev Returns the accumulators corresponding to each of `queries`. */ function getPastAccumulators(OracleAccumulatorQuery[] memory queries) external view returns (int256[] memory results); /** * @dev Information for an Accumulator query. * * Each query estimates the accumulator at a time `ago` seconds ago. */ struct OracleAccumulatorQuery { Variable variable; uint256 ago; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; interface IPoolPriceOracle { /** * @dev Returns the raw data of the sample at `index`. */ function getSample(uint256 index) external view returns ( int256 logPairPrice, int256 accLogPairPrice, int256 logBptPrice, int256 accLogBptPrice, int256 logInvariant, int256 accLogInvariant, uint256 timestamp ); /** * @dev Returns the total number of samples. */ function getTotalSamples() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/helpers/WordCodec.sol"; import "../interfaces/IPriceOracle.sol"; /** * @dev This library provides functions to help manipulating samples for Pool Price Oracles. It handles updates, * encoding, and decoding of samples. * * Each sample holds the timestamp of its last update, plus information about three pieces of data: the price pair, the * price of BPT (the associated Pool token), and the invariant. * * Prices and invariant are not stored directly: instead, we store their logarithm. These are known as the 'instant' * values: the exact value at that timestamp. * * Additionally, for each value we keep an accumulator with the sum of all past values, each weighted by the time * elapsed since the previous update. This lets us later subtract accumulators at different points in time and divide by * the time elapsed between them, arriving at the geometric mean of the values (also known as log-average). * * All samples are stored in a single 256 bit word with the following structure: * * [ log pair price | bpt price | invariant | timestamp ] * [ instant | accumulator | instant | accumulator | instant | accumulator | ] * [ int22 | int53 | int22 | int53 | int22 | int53 | uint31 ] * MSB LSB * * Assuming the timestamp doesn't overflow (which holds until the year 2038), the largest elapsed time is 2^31, which * means the largest possible accumulator value is 2^21 * 2^31, which can be represented using a signed 53 bit integer. */ library Samples { using WordCodec for int256; using WordCodec for uint256; using WordCodec for bytes32; uint256 internal constant _TIMESTAMP_OFFSET = 0; uint256 internal constant _ACC_LOG_INVARIANT_OFFSET = 31; uint256 internal constant _INST_LOG_INVARIANT_OFFSET = 84; uint256 internal constant _ACC_LOG_BPT_PRICE_OFFSET = 106; uint256 internal constant _INST_LOG_BPT_PRICE_OFFSET = 159; uint256 internal constant _ACC_LOG_PAIR_PRICE_OFFSET = 181; uint256 internal constant _INST_LOG_PAIR_PRICE_OFFSET = 234; /** * @dev Updates a sample, accumulating the new data based on the elapsed time since the previous update. Returns the * updated sample. * * IMPORTANT: This function does not perform any arithmetic checks. In particular, it assumes the caller will never * pass values that cannot be represented as 22 bit signed integers. Additionally, it also assumes * `currentTimestamp` is greater than `sample`'s timestamp. */ function update( bytes32 sample, int256 instLogPairPrice, int256 instLogBptPrice, int256 instLogInvariant, uint256 currentTimestamp ) internal pure returns (bytes32) { // Because elapsed can be represented as a 31 bit unsigned integer, and the received values can be represented // as 22 bit signed integers, we don't need to perform checked arithmetic. int256 elapsed = int256(currentTimestamp - timestamp(sample)); int256 accLogPairPrice = _accLogPairPrice(sample) + instLogPairPrice * elapsed; int256 accLogBptPrice = _accLogBptPrice(sample) + instLogBptPrice * elapsed; int256 accLogInvariant = _accLogInvariant(sample) + instLogInvariant * elapsed; return pack( instLogPairPrice, accLogPairPrice, instLogBptPrice, accLogBptPrice, instLogInvariant, accLogInvariant, currentTimestamp ); } /** * @dev Returns the instant value stored in `sample` for `variable`. */ function instant(bytes32 sample, IPriceOracle.Variable variable) internal pure returns (int256) { if (variable == IPriceOracle.Variable.PAIR_PRICE) { return _instLogPairPrice(sample); } else if (variable == IPriceOracle.Variable.BPT_PRICE) { return _instLogBptPrice(sample); } else { // variable == IPriceOracle.Variable.INVARIANT return _instLogInvariant(sample); } } /** * @dev Returns the accumulator value stored in `sample` for `variable`. */ function accumulator(bytes32 sample, IPriceOracle.Variable variable) internal pure returns (int256) { if (variable == IPriceOracle.Variable.PAIR_PRICE) { return _accLogPairPrice(sample); } else if (variable == IPriceOracle.Variable.BPT_PRICE) { return _accLogBptPrice(sample); } else { // variable == IPriceOracle.Variable.INVARIANT return _accLogInvariant(sample); } } /** * @dev Returns `sample`'s timestamp. */ function timestamp(bytes32 sample) internal pure returns (uint256) { return sample.decodeUint31(_TIMESTAMP_OFFSET); } /** * @dev Returns `sample`'s instant value for the logarithm of the pair price. */ function _instLogPairPrice(bytes32 sample) private pure returns (int256) { return sample.decodeInt22(_INST_LOG_PAIR_PRICE_OFFSET); } /** * @dev Returns `sample`'s accumulator of the logarithm of the pair price. */ function _accLogPairPrice(bytes32 sample) private pure returns (int256) { return sample.decodeInt53(_ACC_LOG_PAIR_PRICE_OFFSET); } /** * @dev Returns `sample`'s instant value for the logarithm of the BPT price. */ function _instLogBptPrice(bytes32 sample) private pure returns (int256) { return sample.decodeInt22(_INST_LOG_BPT_PRICE_OFFSET); } /** * @dev Returns `sample`'s accumulator of the logarithm of the BPT price. */ function _accLogBptPrice(bytes32 sample) private pure returns (int256) { return sample.decodeInt53(_ACC_LOG_BPT_PRICE_OFFSET); } /** * @dev Returns `sample`'s instant value for the logarithm of the invariant. */ function _instLogInvariant(bytes32 sample) private pure returns (int256) { return sample.decodeInt22(_INST_LOG_INVARIANT_OFFSET); } /** * @dev Returns `sample`'s accumulator of the logarithm of the invariant. */ function _accLogInvariant(bytes32 sample) private pure returns (int256) { return sample.decodeInt53(_ACC_LOG_INVARIANT_OFFSET); } /** * @dev Returns a sample created by packing together its components. */ function pack( int256 instLogPairPrice, int256 accLogPairPrice, int256 instLogBptPrice, int256 accLogBptPrice, int256 instLogInvariant, int256 accLogInvariant, uint256 _timestamp ) internal pure returns (bytes32) { return instLogPairPrice.encodeInt22(_INST_LOG_PAIR_PRICE_OFFSET) | accLogPairPrice.encodeInt53(_ACC_LOG_PAIR_PRICE_OFFSET) | instLogBptPrice.encodeInt22(_INST_LOG_BPT_PRICE_OFFSET) | accLogBptPrice.encodeInt53(_ACC_LOG_BPT_PRICE_OFFSET) | instLogInvariant.encodeInt22(_INST_LOG_INVARIANT_OFFSET) | accLogInvariant.encodeInt53(_ACC_LOG_INVARIANT_OFFSET) | _timestamp.encodeUint(_TIMESTAMP_OFFSET); // Using 31 bits } /** * @dev Unpacks a sample into its components. */ function unpack(bytes32 sample) internal pure returns ( int256 logPairPrice, int256 accLogPairPrice, int256 logBptPrice, int256 accLogBptPrice, int256 logInvariant, int256 accLogInvariant, uint256 _timestamp ) { logPairPrice = _instLogPairPrice(sample); accLogPairPrice = _accLogPairPrice(sample); logBptPrice = _instLogBptPrice(sample); accLogBptPrice = _accLogBptPrice(sample); logInvariant = _instLogInvariant(sample); accLogInvariant = _accLogInvariant(sample); _timestamp = timestamp(sample); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/helpers/BalancerErrors.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/LogCompression.sol"; import "../interfaces/IPriceOracle.sol"; import "./Buffer.sol"; import "./Samples.sol"; /** * @dev Auxiliary library for PoolPriceOracle, offloading most of the query code to reduce bytecode size by using this * as a linked library. The downside is an extra DELEGATECALL is added (2600 gas as of the Berlin hardfork), but the * bytecode size gains are so big (specially of the oracle contract does not use `LogCompression.fromLowResLog`) that * it is worth it. */ library QueryProcessor { using Buffer for uint256; using Samples for bytes32; using LogCompression for int256; /** * @dev Returns the value for `variable` at the indexed sample. */ function getInstantValue( mapping(uint256 => bytes32) storage samples, IPriceOracle.Variable variable, uint256 index ) external view returns (uint256) { bytes32 sample = samples[index]; _require(sample.timestamp() > 0, Errors.ORACLE_NOT_INITIALIZED); int256 rawInstantValue = sample.instant(variable); return LogCompression.fromLowResLog(rawInstantValue); } /** * @dev Returns the time average weighted price corresponding to `query`. */ function getTimeWeightedAverage( mapping(uint256 => bytes32) storage samples, IPriceOracle.OracleAverageQuery memory query, uint256 latestIndex ) external view returns (uint256) { _require(query.secs != 0, Errors.ORACLE_BAD_SECS); int256 beginAccumulator = getPastAccumulator(samples, query.variable, latestIndex, query.ago + query.secs); int256 endAccumulator = getPastAccumulator(samples, query.variable, latestIndex, query.ago); return LogCompression.fromLowResLog((endAccumulator - beginAccumulator) / int256(query.secs)); } /** * @dev Returns the value of the accumulator for `variable` `ago` seconds ago. `latestIndex` must be the index of * the latest sample in the buffer. * * Reverts under the following conditions: * - if the buffer is empty. * - if querying past information and the buffer has not been fully initialized. * - if querying older information than available in the buffer. Note that a full buffer guarantees queries for the * past 34 hours will not revert. * * If requesting information for a timestamp later than the latest one, it is extrapolated using the latest * available data. * * When no exact information is available for the requested past timestamp (as usually happens, since at most one * timestamp is stored every two minutes), it is estimated by performing linear interpolation using the closest * values. This process is guaranteed to complete performing at most 10 storage reads. */ function getPastAccumulator( mapping(uint256 => bytes32) storage samples, IPriceOracle.Variable variable, uint256 latestIndex, uint256 ago ) public view returns (int256) { // solhint-disable not-rely-on-time // `ago` must not be before the epoch. _require(block.timestamp >= ago, Errors.ORACLE_INVALID_SECONDS_QUERY); uint256 lookUpTime = block.timestamp - ago; bytes32 latestSample = samples[latestIndex]; uint256 latestTimestamp = latestSample.timestamp(); // The latest sample only has a non-zero timestamp if no data was ever processed and stored in the buffer. _require(latestTimestamp > 0, Errors.ORACLE_NOT_INITIALIZED); if (latestTimestamp <= lookUpTime) { // The accumulator at times ahead of the latest one are computed by extrapolating the latest data. This is // equivalent to the instant value not changing between the last timestamp and the look up time. // We can use unchecked arithmetic since the accumulator can be represented in 53 bits, timestamps in 31 // bits, and the instant value in 22 bits. uint256 elapsed = lookUpTime - latestTimestamp; return latestSample.accumulator(variable) + (latestSample.instant(variable) * int256(elapsed)); } else { // The look up time is before the latest sample, but we need to make sure that it is not before the oldest // sample as well. // Since we use a circular buffer, the oldest sample is simply the next one. uint256 bufferLength; uint256 oldestIndex = latestIndex.next(); { // Local scope used to prevent stack-too-deep errors. bytes32 oldestSample = samples[oldestIndex]; uint256 oldestTimestamp = oldestSample.timestamp(); if (oldestTimestamp > 0) { // If the oldest timestamp is not zero, it means the buffer was fully initialized. bufferLength = Buffer.SIZE; } else { // If the buffer was not fully initialized, we haven't wrapped around it yet, // and can treat it as a regular array where the oldest index is the first one, // and the length the number of samples. bufferLength = oldestIndex; // Equal to latestIndex.next() oldestIndex = 0; oldestTimestamp = samples[0].timestamp(); } // Finally check that the look up time is not previous to the oldest timestamp. _require(oldestTimestamp <= lookUpTime, Errors.ORACLE_QUERY_TOO_OLD); } // Perform binary search to find nearest samples to the desired timestamp. (bytes32 prev, bytes32 next) = findNearestSample(samples, lookUpTime, oldestIndex, bufferLength); // `next`'s timestamp is guaranteed to be larger than `prev`'s, so we can skip checked arithmetic. uint256 samplesTimeDiff = next.timestamp() - prev.timestamp(); if (samplesTimeDiff > 0) { // We estimate the accumulator at the requested look up time by interpolating linearly between the // previous and next accumulators. // We can use unchecked arithmetic since the accumulators can be represented in 53 bits, and timestamps // in 31 bits. int256 samplesAccDiff = next.accumulator(variable) - prev.accumulator(variable); uint256 elapsed = lookUpTime - prev.timestamp(); return prev.accumulator(variable) + ((samplesAccDiff * int256(elapsed)) / int256(samplesTimeDiff)); } else { // Rarely, one of the samples will have the exact requested look up time, which is indicated by `prev` // and `next` being the same. In this case, we simply return the accumulator at that point in time. return prev.accumulator(variable); } } } /** * @dev Finds the two samples with timestamps before and after `lookUpDate`. If one of the samples matches exactly, * both `prev` and `next` will be it. `offset` is the index of the oldest sample in the buffer. `length` is the size * of the samples list. * * Assumes `lookUpDate` is greater or equal than the timestamp of the oldest sample, and less or equal than the * timestamp of the latest sample. */ function findNearestSample( mapping(uint256 => bytes32) storage samples, uint256 lookUpDate, uint256 offset, uint256 length ) public view returns (bytes32 prev, bytes32 next) { // We're going to perform a binary search in the circular buffer, which requires it to be sorted. To achieve // this, we offset all buffer accesses by `offset`, making the first element the oldest one. // Auxiliary variables in a typical binary search: we will look at some value `mid` between `low` and `high`, // periodically increasing `low` or decreasing `high` until we either find a match or determine the element is // not in the array. uint256 low = 0; uint256 high = length - 1; uint256 mid; // If the search fails and no sample has a timestamp of `lookUpDate` (as is the most common scenario), `sample` // will be either the sample with the largest timestamp smaller than `lookUpDate`, or the one with the smallest // timestamp larger than `lookUpDate`. bytes32 sample; uint256 sampleTimestamp; while (low <= high) { // Mid is the floor of the average. uint256 midWithoutOffset = (high + low) / 2; // Recall that the buffer is not actually sorted: we need to apply the offset to access it in a sorted way. mid = midWithoutOffset.add(offset); sample = samples[mid]; sampleTimestamp = sample.timestamp(); if (sampleTimestamp < lookUpDate) { // If the mid sample is bellow the look up date, then increase the low index to start from there. low = midWithoutOffset + 1; } else if (sampleTimestamp > lookUpDate) { // If the mid sample is above the look up date, then decrease the high index to start from there. // We can skip checked arithmetic: it is impossible for `high` to ever be 0, as a scenario where `low` // equals 0 and `high` equals 1 would result in `low` increasing to 1 in the previous `if` clause. high = midWithoutOffset - 1; } else { // sampleTimestamp == lookUpDate // If we have an exact match, return the sample as both `prev` and `next`. return (sample, sample); } } // In case we reach here, it means we didn't find exactly the sample we where looking for. return sampleTimestamp < lookUpDate ? (sample, samples[mid.next()]) : (samples[mid.prev()], sample); } } // SPDX-License-Identifier: MIT // Based on the ReentrancyGuard library from OpenZeppelin Contracts, altered to reduce bytecode size. // Modifier code is inlined by the compiler, which causes its code to appear multiple times in the codebase. By using // private functions, we achieve the same end result with slightly higher runtime gas costs, but reduced bytecode size. pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract 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 make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _enterNonReentrant(); _; _exitNonReentrant(); } function _enterNonReentrant() private { // On the first call to nonReentrant, _status will be _NOT_ENTERED _require(_status != _ENTERED, Errors.REENTRANCY); // Any calls to nonReentrant after this point will fail _status = _ENTERED; } function _exitNonReentrant() private { // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ReentrancyGuard.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/WordCodec.sol"; import "@balancer-labs/v2-solidity-utils/contracts/math/Math.sol"; import "../BaseWeightedPool.sol"; import "./WeightCompression.sol"; /** * @dev Weighted Pool with mutable weights, designed to support V2 Liquidity Bootstrapping */ contract LiquidityBootstrappingPool is BaseWeightedPool, ReentrancyGuard { // The Pause Window and Buffer Period are timestamp-based: they should not be relied upon for sub-minute accuracy. // solhint-disable not-rely-on-time using FixedPoint for uint256; using WordCodec for bytes32; using WeightCompression for uint256; // LBPs often involve only two tokens - we support up to four since we're able to pack the entire config in a single // storage slot. uint256 private constant _MAX_LBP_TOKENS = 4; // State variables uint256 private immutable _totalTokens; IERC20 internal immutable _token0; IERC20 internal immutable _token1; IERC20 internal immutable _token2; IERC20 internal immutable _token3; // All token balances are normalized to behave as if the token had 18 decimals. We assume a token's decimals will // not change throughout its lifetime, and store the corresponding scaling factor for each at construction time. // These factors are always greater than or equal to one: tokens with more than 18 decimals are not supported. uint256 internal immutable _scalingFactor0; uint256 internal immutable _scalingFactor1; uint256 internal immutable _scalingFactor2; uint256 internal immutable _scalingFactor3; // For gas optimization, store start/end weights and timestamps in one bytes32 // Start weights need to be high precision, since restarting the update resets them to "spot" // values. Target end weights do not need as much precision. // [ 32 bits | 32 bits | 64 bits | 124 bits | 3 bits | 1 bit ] // [ end timestamp | start timestamp | 4x16 end weights | 4x31 start weights | not used | swap enabled ] // |MSB LSB| bytes32 private _poolState; // Offsets for data elements in _poolState uint256 private constant _SWAP_ENABLED_OFFSET = 0; uint256 private constant _START_WEIGHT_OFFSET = 4; uint256 private constant _END_WEIGHT_OFFSET = 128; uint256 private constant _START_TIME_OFFSET = 192; uint256 private constant _END_TIME_OFFSET = 224; // Event declarations event SwapEnabledSet(bool swapEnabled); event GradualWeightUpdateScheduled( uint256 startTime, uint256 endTime, uint256[] startWeights, uint256[] endWeights ); constructor( IVault vault, string memory name, string memory symbol, IERC20[] memory tokens, uint256[] memory normalizedWeights, uint256 swapFeePercentage, uint256 pauseWindowDuration, uint256 bufferPeriodDuration, address owner, bool swapEnabledOnStart ) BaseWeightedPool( vault, name, symbol, tokens, new address[](tokens.length), // Pass the zero address: LBPs can't have asset managers swapFeePercentage, pauseWindowDuration, bufferPeriodDuration, owner ) { uint256 totalTokens = tokens.length; InputHelpers.ensureInputLengthMatch(totalTokens, normalizedWeights.length); _totalTokens = totalTokens; // Immutable variables cannot be initialized inside an if statement, so we must do conditional assignments _token0 = tokens[0]; _token1 = tokens[1]; _token2 = totalTokens > 2 ? tokens[2] : IERC20(0); _token3 = totalTokens > 3 ? tokens[3] : IERC20(0); _scalingFactor0 = _computeScalingFactor(tokens[0]); _scalingFactor1 = _computeScalingFactor(tokens[1]); _scalingFactor2 = totalTokens > 2 ? _computeScalingFactor(tokens[2]) : 0; _scalingFactor3 = totalTokens > 3 ? _computeScalingFactor(tokens[3]) : 0; uint256 currentTime = block.timestamp; _startGradualWeightChange(currentTime, currentTime, normalizedWeights, normalizedWeights); // If false, the pool will start in the disabled state (prevents front-running the enable swaps transaction) _setSwapEnabled(swapEnabledOnStart); } // External functions /** * @dev Tells whether swaps are enabled or not for the given pool. */ function getSwapEnabled() public view returns (bool) { return _poolState.decodeBool(_SWAP_ENABLED_OFFSET); } /** * @dev Return start time, end time, and endWeights as an array. * Current weights should be retrieved via `getNormalizedWeights()`. */ function getGradualWeightUpdateParams() external view returns ( uint256 startTime, uint256 endTime, uint256[] memory endWeights ) { // Load current pool state from storage bytes32 poolState = _poolState; startTime = poolState.decodeUint32(_START_TIME_OFFSET); endTime = poolState.decodeUint32(_END_TIME_OFFSET); uint256 totalTokens = _getTotalTokens(); endWeights = new uint256[](totalTokens); for (uint256 i = 0; i < totalTokens; i++) { endWeights[i] = poolState.decodeUint16(_END_WEIGHT_OFFSET + i * 16).uncompress16(); } } /** * @dev Can pause/unpause trading */ function setSwapEnabled(bool swapEnabled) external authenticate whenNotPaused nonReentrant { _setSwapEnabled(swapEnabled); } /** * @dev Schedule a gradual weight change, from the current weights to the given endWeights, * over startTime to endTime */ function updateWeightsGradually( uint256 startTime, uint256 endTime, uint256[] memory endWeights ) external authenticate whenNotPaused nonReentrant { InputHelpers.ensureInputLengthMatch(_getTotalTokens(), endWeights.length); // If the start time is in the past, "fast forward" to start now // This avoids discontinuities in the weight curve. Otherwise, if you set the start/end times with // only 10% of the period in the future, the weights would immediately jump 90% uint256 currentTime = block.timestamp; startTime = Math.max(currentTime, startTime); _require(startTime <= endTime, Errors.GRADUAL_UPDATE_TIME_TRAVEL); _startGradualWeightChange(startTime, endTime, _getNormalizedWeights(), endWeights); } // Internal functions function _getNormalizedWeight(IERC20 token) internal view override returns (uint256) { uint256 i; // First, convert token address to a token index // prettier-ignore if (token == _token0) { i = 0; } else if (token == _token1) { i = 1; } else if (token == _token2) { i = 2; } else if (token == _token3) { i = 3; } else { _revert(Errors.INVALID_TOKEN); } return _getNormalizedWeightByIndex(i, _poolState); } function _getNormalizedWeightByIndex(uint256 i, bytes32 poolState) internal view returns (uint256) { uint256 startWeight = poolState.decodeUint31(_START_WEIGHT_OFFSET + i * 31).uncompress31(); uint256 endWeight = poolState.decodeUint16(_END_WEIGHT_OFFSET + i * 16).uncompress16(); uint256 pctProgress = _calculateWeightChangeProgress(poolState); return _interpolateWeight(startWeight, endWeight, pctProgress); } function _getNormalizedWeights() internal view override returns (uint256[] memory) { uint256 totalTokens = _getTotalTokens(); uint256[] memory normalizedWeights = new uint256[](totalTokens); bytes32 poolState = _poolState; // prettier-ignore { normalizedWeights[0] = _getNormalizedWeightByIndex(0, poolState); normalizedWeights[1] = _getNormalizedWeightByIndex(1, poolState); if (totalTokens == 2) return normalizedWeights; normalizedWeights[2] = _getNormalizedWeightByIndex(2, poolState); if (totalTokens == 3) return normalizedWeights; normalizedWeights[3] = _getNormalizedWeightByIndex(3, poolState); } return normalizedWeights; } function _getNormalizedWeightsAndMaxWeightIndex() internal view override returns (uint256[] memory normalizedWeights, uint256 maxWeightTokenIndex) { normalizedWeights = _getNormalizedWeights(); maxWeightTokenIndex = 0; uint256 maxNormalizedWeight = normalizedWeights[0]; for (uint256 i = 1; i < normalizedWeights.length; i++) { if (normalizedWeights[i] > maxNormalizedWeight) { maxWeightTokenIndex = i; maxNormalizedWeight = normalizedWeights[i]; } } } // Pool callback functions // Prevent any account other than the owner from joining the pool function _onInitializePool( bytes32 poolId, address sender, address recipient, uint256[] memory scalingFactors, bytes memory userData ) internal override returns (uint256, uint256[] memory) { // Only the owner can initialize the pool _require(sender == getOwner(), Errors.CALLER_IS_NOT_LBP_OWNER); return super._onInitializePool(poolId, sender, recipient, scalingFactors, userData); } function _onJoinPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, uint256[] memory scalingFactors, bytes memory userData ) internal override returns ( uint256, uint256[] memory, uint256[] memory ) { // Only the owner can add liquidity; block public LPs _require(sender == getOwner(), Errors.CALLER_IS_NOT_LBP_OWNER); return super._onJoinPool( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, scalingFactors, userData ); } // Swap overrides - revert unless swaps are enabled function _onSwapGivenIn( SwapRequest memory swapRequest, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut ) internal view override returns (uint256) { _require(getSwapEnabled(), Errors.SWAPS_DISABLED); return super._onSwapGivenIn(swapRequest, currentBalanceTokenIn, currentBalanceTokenOut); } function _onSwapGivenOut( SwapRequest memory swapRequest, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut ) internal view override returns (uint256) { _require(getSwapEnabled(), Errors.SWAPS_DISABLED); return super._onSwapGivenOut(swapRequest, currentBalanceTokenIn, currentBalanceTokenOut); } /** * @dev Extend ownerOnly functions to include the LBP control functions */ function _isOwnerOnlyAction(bytes32 actionId) internal view override returns (bool) { return (actionId == getActionId(LiquidityBootstrappingPool.setSwapEnabled.selector)) || (actionId == getActionId(LiquidityBootstrappingPool.updateWeightsGradually.selector)) || super._isOwnerOnlyAction(actionId); } // Private functions /** * @dev Returns a fixed-point number representing how far along the current weight change is, where 0 means the * change has not yet started, and FixedPoint.ONE means it has fully completed. */ function _calculateWeightChangeProgress(bytes32 poolState) private view returns (uint256) { uint256 currentTime = block.timestamp; uint256 startTime = poolState.decodeUint32(_START_TIME_OFFSET); uint256 endTime = poolState.decodeUint32(_END_TIME_OFFSET); if (currentTime > endTime) { return FixedPoint.ONE; } else if (currentTime < startTime) { return 0; } // No need for SafeMath as it was checked right above: endTime >= currentTime >= startTime uint256 totalSeconds = endTime - startTime; uint256 secondsElapsed = currentTime - startTime; // In the degenerate case of a zero duration change, consider it completed (and avoid division by zero) return totalSeconds == 0 ? FixedPoint.ONE : secondsElapsed.divDown(totalSeconds); } /** * @dev When calling updateWeightsGradually again during an update, reset the start weights to the current weights, * if necessary. */ function _startGradualWeightChange( uint256 startTime, uint256 endTime, uint256[] memory startWeights, uint256[] memory endWeights ) internal virtual { bytes32 newPoolState = _poolState; uint256 normalizedSum = 0; for (uint256 i = 0; i < endWeights.length; i++) { uint256 endWeight = endWeights[i]; _require(endWeight >= _MIN_WEIGHT, Errors.MIN_WEIGHT); newPoolState = newPoolState .insertUint31(startWeights[i].compress31(), _START_WEIGHT_OFFSET + i * 31) .insertUint16(endWeight.compress16(), _END_WEIGHT_OFFSET + i * 16); normalizedSum = normalizedSum.add(endWeight); } // Ensure that the normalized weights sum to ONE _require(normalizedSum == FixedPoint.ONE, Errors.NORMALIZED_WEIGHT_INVARIANT); _poolState = newPoolState.insertUint32(startTime, _START_TIME_OFFSET).insertUint32(endTime, _END_TIME_OFFSET); emit GradualWeightUpdateScheduled(startTime, endTime, startWeights, endWeights); } function _interpolateWeight( uint256 startWeight, uint256 endWeight, uint256 pctProgress ) private pure returns (uint256) { if (pctProgress == 0 || startWeight == endWeight) return startWeight; if (pctProgress >= FixedPoint.ONE) return endWeight; if (startWeight > endWeight) { uint256 weightDelta = pctProgress.mulDown(startWeight - endWeight); return startWeight.sub(weightDelta); } else { uint256 weightDelta = pctProgress.mulDown(endWeight - startWeight); return startWeight.add(weightDelta); } } function _setSwapEnabled(bool swapEnabled) private { _poolState = _poolState.insertBool(swapEnabled, _SWAP_ENABLED_OFFSET); emit SwapEnabledSet(swapEnabled); } function _getMaxTokens() internal pure override returns (uint256) { return _MAX_LBP_TOKENS; } function _getTotalTokens() internal view virtual override returns (uint256) { return _totalTokens; } function _scalingFactor(IERC20 token) internal view virtual override returns (uint256) { // prettier-ignore if (token == _token0) { return _scalingFactor0; } else if (token == _token1) { return _scalingFactor1; } else if (token == _token2) { return _scalingFactor2; } else if (token == _token3) { return _scalingFactor3; } else { _revert(Errors.INVALID_TOKEN); } } function _scalingFactors() internal view virtual override returns (uint256[] memory) { uint256 totalTokens = _getTotalTokens(); uint256[] memory scalingFactors = new uint256[](totalTokens); // prettier-ignore { if (totalTokens > 0) { scalingFactors[0] = _scalingFactor0; } else { return scalingFactors; } if (totalTokens > 1) { scalingFactors[1] = _scalingFactor1; } else { return scalingFactors; } if (totalTokens > 2) { scalingFactors[2] = _scalingFactor2; } else { return scalingFactors; } if (totalTokens > 3) { scalingFactors[3] = _scalingFactor3; } else { return scalingFactors; } } return scalingFactors; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/math/FixedPoint.sol"; /** * @dev Library for compressing and uncompresing numbers by using smaller types. * All values are 18 decimal fixed-point numbers in the [0.0, 1.0] range, * so heavier compression (fewer bits) results in fewer decimals. */ library WeightCompression { uint256 private constant _UINT31_MAX = 2**(31) - 1; using FixedPoint for uint256; /** * @dev Convert a 16-bit value to full FixedPoint */ function uncompress16(uint256 value) internal pure returns (uint256) { return value.mulUp(FixedPoint.ONE).divUp(type(uint16).max); } /** * @dev Compress a FixedPoint value to 16 bits */ function compress16(uint256 value) internal pure returns (uint256) { return value.mulUp(type(uint16).max).divUp(FixedPoint.ONE); } /** * @dev Convert a 31-bit value to full FixedPoint */ function uncompress31(uint256 value) internal pure returns (uint256) { return value.mulUp(FixedPoint.ONE).divUp(_UINT31_MAX); } /** * @dev Compress a FixedPoint value to 31 bits */ function compress31(uint256 value) internal pure returns (uint256) { return value.mulUp(_UINT31_MAX).divUp(FixedPoint.ONE); } /** * @dev Convert a 32-bit value to full FixedPoint */ function uncompress32(uint256 value) internal pure returns (uint256) { return value.mulUp(FixedPoint.ONE).divUp(type(uint32).max); } /** * @dev Compress a FixedPoint value to 32 bits */ function compress32(uint256 value) internal pure returns (uint256) { return value.mulUp(type(uint32).max).divUp(FixedPoint.ONE); } /** * @dev Convert a 64-bit value to full FixedPoint */ function uncompress64(uint256 value) internal pure returns (uint256) { return value.mulUp(FixedPoint.ONE).divUp(type(uint64).max); } /** * @dev Compress a FixedPoint value to 64 bits */ function compress64(uint256 value) internal pure returns (uint256) { return value.mulUp(type(uint64).max).divUp(FixedPoint.ONE); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol"; import "@balancer-labs/v2-pool-utils/contracts/factories/BasePoolSplitCodeFactory.sol"; import "@balancer-labs/v2-pool-utils/contracts/factories/FactoryWidePauseWindow.sol"; import "./LiquidityBootstrappingPool.sol"; contract LiquidityBootstrappingPoolFactory is BasePoolSplitCodeFactory, FactoryWidePauseWindow { constructor(IVault vault) BasePoolSplitCodeFactory(vault, type(LiquidityBootstrappingPool).creationCode) { // solhint-disable-previous-line no-empty-blocks } /** * @dev Deploys a new `LiquidityBootstrappingPool`. */ function create( string memory name, string memory symbol, IERC20[] memory tokens, uint256[] memory weights, uint256 swapFeePercentage, address owner, bool swapEnabledOnStart ) external returns (address) { (uint256 pauseWindowDuration, uint256 bufferPeriodDuration) = getPauseConfiguration(); return _create( abi.encode( getVault(), name, symbol, tokens, weights, swapFeePercentage, pauseWindowDuration, bufferPeriodDuration, owner, swapEnabledOnStart ) ); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol"; import "@balancer-labs/v2-pool-utils/contracts/factories/BasePoolSplitCodeFactory.sol"; import "@balancer-labs/v2-pool-utils/contracts/factories/FactoryWidePauseWindow.sol"; import "./InvestmentPool.sol"; contract InvestmentPoolFactory is BasePoolSplitCodeFactory, FactoryWidePauseWindow { constructor(IVault vault) BasePoolSplitCodeFactory(vault, type(InvestmentPool).creationCode) { // solhint-disable-previous-line no-empty-blocks } /** * @dev Deploys a new `InvestmentPool`. */ function create( string memory name, string memory symbol, IERC20[] memory tokens, uint256[] memory weights, uint256 swapFeePercentage, address owner, bool swapEnabledOnStart, uint256 managementSwapFeePercentage ) external returns (address) { (uint256 pauseWindowDuration, uint256 bufferPeriodDuration) = getPauseConfiguration(); return _create( abi.encode( InvestmentPool.NewPoolParams({ vault: getVault(), name: name, symbol: symbol, tokens: tokens, normalizedWeights: weights, assetManagers: new address[](tokens.length), swapFeePercentage: swapFeePercentage, pauseWindowDuration: pauseWindowDuration, bufferPeriodDuration: bufferPeriodDuration, owner: owner, swapEnabledOnStart: swapEnabledOnStart, managementSwapFeePercentage: managementSwapFeePercentage }) ) ); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/EnumerableMap.sol"; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ReentrancyGuard.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/ERC20Helpers.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/WordCodec.sol"; import "../BaseWeightedPool.sol"; import "../WeightedPoolUserDataHelpers.sol"; import "./WeightCompression.sol"; /** * @dev Weighted Pool with mutable weights, designed to support investment use cases: large token counts, * rebalancing through gradual weight updates. */ contract InvestmentPool is BaseWeightedPool, ReentrancyGuard { // solhint-disable not-rely-on-time using FixedPoint for uint256; using WordCodec for bytes32; using WeightCompression for uint256; using WeightedPoolUserDataHelpers for bytes; using EnumerableMap for EnumerableMap.IERC20ToUint256Map; // State variables // The upper bound is WeightedMath.MAX_WEIGHTED_TOKENS, but this is constrained by other factors, such as Pool // creation gas consumption (which is linear). uint256 private constant _MAX_INVESTMENT_TOKENS = 50; // Percentage of swap fees that are allocated to the Pool owner. uint256 private immutable _managementSwapFeePercentage; uint256 private constant _MAX_MANAGEMENT_SWAP_FEE_PERCENTAGE = 1e18; // 100% // Use the _miscData slot in BasePool // First 64 bits are reserved for the swap fee // // Store non-token-based values: // Start/end timestamps for gradual weight update // Cache total tokens // [ 64 bits | 120 bits | 32 bits | 32 bits | 7 bits | 1 bit ] // [ reserved | unused | end time | start time | total tokens | swap flag ] // |MSB LSB| uint256 private constant _SWAP_ENABLED_OFFSET = 0; uint256 private constant _TOTAL_TOKENS_OFFSET = 1; uint256 private constant _START_TIME_OFFSET = 8; uint256 private constant _END_TIME_OFFSET = 40; // 7 bits is enough for the token count, since _MAX_INVESTMENT_TOKENS is 50 // Store scaling factor and start/end weights for each token // Mapping should be more efficient than trying to compress it further // [ 155 bits| 5 bits | 32 bits | 64 bits | // [ unused | decimals | end weight | start weight | // |MSB LSB| mapping(IERC20 => bytes32) private _tokenState; EnumerableMap.IERC20ToUint256Map private _tokenCollectedManagementFees; uint256 private constant _START_WEIGHT_OFFSET = 0; uint256 private constant _END_WEIGHT_OFFSET = 64; uint256 private constant _DECIMAL_DIFF_OFFSET = 96; uint256 private constant _MINIMUM_WEIGHT_CHANGE_DURATION = 1 days; // Event declarations event GradualWeightUpdateScheduled( uint256 startTime, uint256 endTime, uint256[] startWeights, uint256[] endWeights ); event SwapEnabledSet(bool swapEnabled); event ManagementFeePercentageChanged(uint256 managementFeePercentage); event ManagementFeesCollected(IERC20[] tokens, uint256[] amounts); struct NewPoolParams { IVault vault; string name; string symbol; IERC20[] tokens; uint256[] normalizedWeights; address[] assetManagers; uint256 swapFeePercentage; uint256 pauseWindowDuration; uint256 bufferPeriodDuration; address owner; bool swapEnabledOnStart; uint256 managementSwapFeePercentage; } constructor(NewPoolParams memory params) BaseWeightedPool( params.vault, params.name, params.symbol, params.tokens, params.assetManagers, params.swapFeePercentage, params.pauseWindowDuration, params.bufferPeriodDuration, params.owner ) { uint256 totalTokens = params.tokens.length; InputHelpers.ensureInputLengthMatch(totalTokens, params.normalizedWeights.length, params.assetManagers.length); _setMiscData(_getMiscData().insertUint7(totalTokens, _TOTAL_TOKENS_OFFSET)); // Double check it fits in 7 bits _require(_getTotalTokens() == totalTokens, Errors.MAX_TOKENS); uint256 currentTime = block.timestamp; _startGradualWeightChange( currentTime, currentTime, params.normalizedWeights, params.normalizedWeights, params.tokens ); // Initialize the accrued management fees map with the Pool's tokens and zero collected fees. for (uint256 i = 0; i < totalTokens; ++i) { _tokenCollectedManagementFees.set(params.tokens[i], 0); } // If false, the pool will start in the disabled state (prevents front-running the enable swaps transaction) _setSwapEnabled(params.swapEnabledOnStart); // This must be inlined in the constructor as we're setting an immutable variable. _require( params.managementSwapFeePercentage <= _MAX_MANAGEMENT_SWAP_FEE_PERCENTAGE, Errors.MAX_MANAGEMENT_SWAP_FEE_PERCENTAGE ); _managementSwapFeePercentage = params.managementSwapFeePercentage; emit ManagementFeePercentageChanged(params.managementSwapFeePercentage); } /** * @dev Returns true if swaps are enabled. */ function getSwapEnabled() public view returns (bool) { return _getMiscData().decodeBool(_SWAP_ENABLED_OFFSET); } /** * @dev Returns the management swap fee percentage as a 18-decimals fixed point number. */ function getManagementSwapFeePercentage() public view returns (uint256) { return _managementSwapFeePercentage; } /** * @dev Returns the mimimum duration of a gradual weight change */ function getMinimumWeightChangeDuration() external pure returns (uint256) { return _MINIMUM_WEIGHT_CHANGE_DURATION; } /** * @dev Return start time, end time, and endWeights as an array. * Current weights should be retrieved via `getNormalizedWeights()`. */ function getGradualWeightUpdateParams() external view returns ( uint256 startTime, uint256 endTime, uint256[] memory endWeights ) { // Load current pool state from storage bytes32 poolState = _getMiscData(); startTime = poolState.decodeUint32(_START_TIME_OFFSET); endTime = poolState.decodeUint32(_END_TIME_OFFSET); (IERC20[] memory tokens, , ) = getVault().getPoolTokens(getPoolId()); uint256 totalTokens = tokens.length; endWeights = new uint256[](totalTokens); for (uint256 i = 0; i < totalTokens; i++) { endWeights[i] = _tokenState[tokens[i]].decodeUint32(_END_WEIGHT_OFFSET).uncompress32(); } } function _getMaxTokens() internal pure virtual override returns (uint256) { return _MAX_INVESTMENT_TOKENS; } function _getTotalTokens() internal view virtual override returns (uint256) { return _getMiscData().decodeUint7(_TOTAL_TOKENS_OFFSET); } /** * @dev Schedule a gradual weight change, from the current weights to the given endWeights, * over startTime to endTime. */ function updateWeightsGradually( uint256 startTime, uint256 endTime, uint256[] memory endWeights ) external authenticate whenNotPaused nonReentrant { InputHelpers.ensureInputLengthMatch(_getTotalTokens(), endWeights.length); // If the start time is in the past, "fast forward" to start now // This avoids discontinuities in the weight curve. Otherwise, if you set the start/end times with // only 10% of the period in the future, the weights would immediately jump 90% uint256 currentTime = block.timestamp; startTime = Math.max(currentTime, startTime); _require(startTime <= endTime, Errors.GRADUAL_UPDATE_TIME_TRAVEL); _require(endTime - startTime >= _MINIMUM_WEIGHT_CHANGE_DURATION, Errors.WEIGHT_CHANGE_TOO_FAST); (IERC20[] memory tokens, , ) = getVault().getPoolTokens(getPoolId()); _startGradualWeightChange(startTime, endTime, _getNormalizedWeights(), endWeights, tokens); } function getCollectedManagementFees() public view returns (IERC20[] memory tokens, uint256[] memory collectedFees) { tokens = new IERC20[](_getTotalTokens()); collectedFees = new uint256[](_getTotalTokens()); for (uint256 i = 0; i < _getTotalTokens(); ++i) { // We can use unchecked getters as we know the map has the same size (and order!) as the Pool's tokens. (IERC20 token, uint256 fees) = _tokenCollectedManagementFees.unchecked_at(i); tokens[i] = token; collectedFees[i] = fees; } _downscaleDownArray(collectedFees, _scalingFactors()); } function withdrawCollectedManagementFees(address recipient) external authenticate whenNotPaused nonReentrant { (IERC20[] memory tokens, uint256[] memory collectedFees) = getCollectedManagementFees(); getVault().exitPool( getPoolId(), address(this), payable(recipient), IVault.ExitPoolRequest({ assets: _asIAsset(tokens), minAmountsOut: collectedFees, userData: abi.encode(BaseWeightedPool.ExitKind.MANAGEMENT_FEE_TOKENS_OUT), toInternalBalance: false }) ); // Technically collectedFees is the minimum amount, not the actual amount. However, since no fees will be // collected during the exit, it will also be the actual amount. emit ManagementFeesCollected(tokens, collectedFees); } /* * @dev Can enable/disable trading */ function setSwapEnabled(bool swapEnabled) external authenticate whenNotPaused nonReentrant { _setSwapEnabled(swapEnabled); } function _setSwapEnabled(bool swapEnabled) private { _setMiscData(_getMiscData().insertBool(swapEnabled, _SWAP_ENABLED_OFFSET)); emit SwapEnabledSet(swapEnabled); } function _scalingFactor(IERC20 token) internal view virtual override returns (uint256) { return _readScalingFactor(_getTokenData(token)); } function _scalingFactors() internal view virtual override returns (uint256[] memory scalingFactors) { (IERC20[] memory tokens, , ) = getVault().getPoolTokens(getPoolId()); uint256 numTokens = tokens.length; scalingFactors = new uint256[](numTokens); for (uint256 i = 0; i < numTokens; i++) { scalingFactors[i] = _readScalingFactor(_tokenState[tokens[i]]); } } function _getNormalizedWeight(IERC20 token) internal view override returns (uint256) { uint256 pctProgress = _calculateWeightChangeProgress(); bytes32 tokenData = _getTokenData(token); return _interpolateWeight(tokenData, pctProgress); } function _getNormalizedWeights() internal view override returns (uint256[] memory normalizedWeights) { (IERC20[] memory tokens, , ) = getVault().getPoolTokens(getPoolId()); uint256 numTokens = tokens.length; normalizedWeights = new uint256[](numTokens); uint256 pctProgress = _calculateWeightChangeProgress(); for (uint256 i = 0; i < numTokens; i++) { bytes32 tokenData = _tokenState[tokens[i]]; normalizedWeights[i] = _interpolateWeight(tokenData, pctProgress); } } function _getNormalizedWeightsAndMaxWeightIndex() internal view override returns (uint256[] memory normalizedWeights, uint256 maxWeightTokenIndex) { normalizedWeights = _getNormalizedWeights(); maxWeightTokenIndex = 0; uint256 maxNormalizedWeight = normalizedWeights[0]; for (uint256 i = 1; i < normalizedWeights.length; i++) { if (normalizedWeights[i] > maxNormalizedWeight) { maxWeightTokenIndex = i; maxNormalizedWeight = normalizedWeights[i]; } } } // Swap overrides - revert unless swaps are enabled function _onSwapGivenIn( SwapRequest memory swapRequest, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut ) internal view override returns (uint256) { _require(getSwapEnabled(), Errors.SWAPS_DISABLED); return super._onSwapGivenIn(swapRequest, currentBalanceTokenIn, currentBalanceTokenOut); } function _onSwapGivenOut( SwapRequest memory swapRequest, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut ) internal view override returns (uint256) { _require(getSwapEnabled(), Errors.SWAPS_DISABLED); return super._onSwapGivenOut(swapRequest, currentBalanceTokenIn, currentBalanceTokenOut); } /** * @dev Used to adjust balances by subtracting all collected fees from them, as if they had been withdrawn from the * Vault. */ function _subtractCollectedFees(uint256[] memory balances) private view { for (uint256 i = 0; i < _getTotalTokens(); ++i) { // We can use unchecked getters as we know the map has the same size (and order!) as the Pool's tokens. balances[i] = balances[i].sub(_tokenCollectedManagementFees.unchecked_valueAt(i)); } } // We override _onJoinPool and _onExitPool as we need to not compute the current invariant and calculate protocol // fees, since that mechanism does not work for Pools in which the weights change over time. Instead, this Pool // always pays zero protocol fees. // Additionally, we also check that only non-swap join and exit kinds are allowed while swaps are disabled. function getLastInvariant() public pure override returns (uint256) { _revert(Errors.UNHANDLED_BY_INVESTMENT_POOL); } function _onJoinPool( bytes32, address, address, uint256[] memory balances, uint256, uint256, uint256[] memory scalingFactors, bytes memory userData ) internal virtual override whenNotPaused // All joins are disabled while the contract is paused. returns ( uint256 bptAmountOut, uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts ) { _subtractCollectedFees(balances); // If swaps are disabled, the only join kind that is allowed is the proportional one, as all others involve // implicit swaps and alter token prices. _require( getSwapEnabled() || userData.joinKind() == JoinKind.ALL_TOKENS_IN_FOR_EXACT_BPT_OUT, Errors.INVALID_JOIN_EXIT_KIND_WHILE_SWAPS_DISABLED ); (bptAmountOut, amountsIn) = _doJoin(balances, _getNormalizedWeights(), scalingFactors, userData); dueProtocolFeeAmounts = new uint256[](_getTotalTokens()); } function _onExitPool( bytes32, address sender, address, uint256[] memory balances, uint256, uint256, uint256[] memory scalingFactors, bytes memory userData ) internal virtual override returns ( uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts ) { _subtractCollectedFees(balances); // Exits are not completely disabled while the contract is paused: proportional exits (exact BPT in for tokens // out) remain functional. // If swaps are disabled, the only exit kind that is allowed is the proportional one (as all others involve // implicit swaps and alter token prices) and management fee collection (as there's no point in restricting // that). ExitKind kind = userData.exitKind(); _require( getSwapEnabled() || kind == ExitKind.EXACT_BPT_IN_FOR_TOKENS_OUT || kind == ExitKind.MANAGEMENT_FEE_TOKENS_OUT, Errors.INVALID_JOIN_EXIT_KIND_WHILE_SWAPS_DISABLED ); (bptAmountIn, amountsOut) = _doInvestmentPoolExit( sender, balances, _getNormalizedWeights(), scalingFactors, userData ); dueProtocolFeeAmounts = new uint256[](_getTotalTokens()); } function _doInvestmentPoolExit( address sender, uint256[] memory balances, uint256[] memory normalizedWeights, uint256[] memory scalingFactors, bytes memory userData ) internal returns (uint256, uint256[] memory) { ExitKind kind = userData.exitKind(); if (kind == ExitKind.MANAGEMENT_FEE_TOKENS_OUT) { return _exitManagerFeeTokensOut(sender); } else { return _doExit(balances, normalizedWeights, scalingFactors, userData); } } function _exitManagerFeeTokensOut(address sender) private whenNotPaused returns (uint256 bptAmountIn, uint256[] memory amountsOut) { // This exit function is disabled if the contract is paused. // This exit function can only be called by the Pool itself - the authorization logic that governs when that // call can be made resides in withdrawCollectedManagementFees. _require(sender == address(this), Errors.UNAUTHORIZED_EXIT); // Since what we're doing is sending out collected management fees, we don't require any BPT in exchange: we // simply send those funds over. bptAmountIn = 0; amountsOut = new uint256[](_getTotalTokens()); for (uint256 i = 0; i < _getTotalTokens(); ++i) { // We can use unchecked getters and setters as we know the map has the same size (and order!) as the Pool's // tokens. amountsOut[i] = _tokenCollectedManagementFees.unchecked_valueAt(i); _tokenCollectedManagementFees.unchecked_setAt(i, 0); } } function _tokenAddressToIndex(IERC20 token) internal view override returns (uint256) { return _tokenCollectedManagementFees.indexOf(token, Errors.INVALID_TOKEN); } function _processSwapFeeAmount(uint256 index, uint256 amount) internal virtual override { if (amount > 0) { uint256 managementFeeAmount = amount.mulDown(_managementSwapFeePercentage); uint256 previousCollectedFees = _tokenCollectedManagementFees.unchecked_valueAt(index); _tokenCollectedManagementFees.unchecked_setAt(index, previousCollectedFees.add(managementFeeAmount)); } super._processSwapFeeAmount(index, amount); } // Pool swap hook override - subtract collected fees from all token amounts. We do this here as the original // `onSwap` does quite a bit of work, including computing swap fees, so we need to intercept that. function onSwap( SwapRequest memory swapRequest, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut ) public override returns (uint256) { uint256 tokenInUpscaledCollectedFees = _tokenCollectedManagementFees.get( swapRequest.tokenIn, Errors.INVALID_TOKEN ); uint256 adjustedBalanceTokenIn = currentBalanceTokenIn.sub( _downscaleDown(tokenInUpscaledCollectedFees, _scalingFactor(swapRequest.tokenIn)) ); uint256 tokenOutUpscaledCollectedFees = _tokenCollectedManagementFees.get( swapRequest.tokenOut, Errors.INVALID_TOKEN ); uint256 adjustedBalanceTokenOut = currentBalanceTokenOut.sub( _downscaleDown(tokenOutUpscaledCollectedFees, _scalingFactor(swapRequest.tokenOut)) ); return super.onSwap(swapRequest, adjustedBalanceTokenIn, adjustedBalanceTokenOut); } /** * @dev When calling updateWeightsGradually again during an update, reset the start weights to the current weights, * if necessary. Time travel elements commented out. */ function _startGradualWeightChange( uint256 startTime, uint256 endTime, uint256[] memory startWeights, uint256[] memory endWeights, IERC20[] memory tokens ) internal virtual { uint256 normalizedSum = 0; bytes32 tokenState; for (uint256 i = 0; i < endWeights.length; i++) { uint256 endWeight = endWeights[i]; _require(endWeight >= _MIN_WEIGHT, Errors.MIN_WEIGHT); IERC20 token = tokens[i]; // Tokens with more than 18 decimals are not supported // Scaling calculations must be exact/lossless // Store decimal difference instead of actual scaling factor _tokenState[token] = tokenState .insertUint64(startWeights[i].compress64(), _START_WEIGHT_OFFSET) .insertUint32(endWeight.compress32(), _END_WEIGHT_OFFSET) .insertUint5(uint256(18).sub(ERC20(address(token)).decimals()), _DECIMAL_DIFF_OFFSET); normalizedSum = normalizedSum.add(endWeight); } // Ensure that the normalized weights sum to ONE _require(normalizedSum == FixedPoint.ONE, Errors.NORMALIZED_WEIGHT_INVARIANT); _setMiscData( _getMiscData().insertUint32(startTime, _START_TIME_OFFSET).insertUint32(endTime, _END_TIME_OFFSET) ); emit GradualWeightUpdateScheduled(startTime, endTime, startWeights, endWeights); } function _readScalingFactor(bytes32 tokenState) private pure returns (uint256) { uint256 decimalsDifference = tokenState.decodeUint5(_DECIMAL_DIFF_OFFSET); return FixedPoint.ONE * 10**decimalsDifference; } /** * @dev Extend ownerOnly functions to include the Investment Pool control functions. */ function _isOwnerOnlyAction(bytes32 actionId) internal view override returns (bool) { return (actionId == getActionId(InvestmentPool.updateWeightsGradually.selector)) || (actionId == getActionId(InvestmentPool.setSwapEnabled.selector)) || (actionId == getActionId(InvestmentPool.withdrawCollectedManagementFees.selector)) || super._isOwnerOnlyAction(actionId); } /** * @dev Returns a fixed-point number representing how far along the current weight change is, where 0 means the * change has not yet started, and FixedPoint.ONE means it has fully completed. */ function _calculateWeightChangeProgress() private view returns (uint256) { uint256 currentTime = block.timestamp; bytes32 poolState = _getMiscData(); uint256 startTime = poolState.decodeUint32(_START_TIME_OFFSET); uint256 endTime = poolState.decodeUint32(_END_TIME_OFFSET); if (currentTime >= endTime) { return FixedPoint.ONE; } else if (currentTime <= startTime) { return 0; } uint256 totalSeconds = endTime - startTime; uint256 secondsElapsed = currentTime - startTime; // In the degenerate case of a zero duration change, consider it completed (and avoid division by zero) return secondsElapsed.divDown(totalSeconds); } function _interpolateWeight(bytes32 tokenData, uint256 pctProgress) private pure returns (uint256 finalWeight) { uint256 startWeight = tokenData.decodeUint64(_START_WEIGHT_OFFSET).uncompress64(); uint256 endWeight = tokenData.decodeUint32(_END_WEIGHT_OFFSET).uncompress32(); if (pctProgress == 0 || startWeight == endWeight) return startWeight; if (pctProgress >= FixedPoint.ONE) return endWeight; if (startWeight > endWeight) { uint256 weightDelta = pctProgress.mulDown(startWeight - endWeight); return startWeight - weightDelta; } else { uint256 weightDelta = pctProgress.mulDown(endWeight - startWeight); return startWeight + weightDelta; } } function _getTokenData(IERC20 token) private view returns (bytes32 tokenData) { tokenData = _tokenState[token]; // A valid token can't be zero (must have non-zero weights) _require(tokenData != 0, Errors.INVALID_TOKEN); } } // SPDX-License-Identifier: MIT // Based on the EnumerableMap library from OpenZeppelin Contracts, altered to include the following: // * a map from IERC20 to bytes32 // * entries are stored in mappings instead of arrays, reducing implicit storage reads for out-of-bounds checks // * unchecked_at and unchecked_valueAt, which allow for more gas efficient data reads in some scenarios // * indexOf, unchecked_indexOf and unchecked_setAt, which allow for more gas efficient data writes in some scenarios // // Additionally, the base private functions that work on bytes32 were removed and replaced with a native implementation // for IERC20 keys, to reduce bytecode size and runtime costs. pragma solidity ^0.7.0; import "./IERC20.sol"; import "../helpers/BalancerErrors.sol"; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` */ library EnumerableMap { // The original OpenZeppelin implementation uses a generic Map type with bytes32 keys: this was replaced with // IERC20ToBytes32Map and IERC20ToUint256Map, resulting in more dense bytecode (as long as each contract only uses // one of these - there'll otherwise be duplicated code). // IERC20ToBytes32Map struct IERC20ToBytes32MapEntry { IERC20 _key; bytes32 _value; } struct IERC20ToBytes32Map { // Number of entries in the map uint256 _length; // Storage of map keys and values mapping(uint256 => IERC20ToBytes32MapEntry) _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping(IERC20 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set( IERC20ToBytes32Map storage map, IERC20 key, bytes32 value ) internal returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; // Equivalent to !contains(map, key) if (keyIndex == 0) { uint256 previousLength = map._length; map._entries[previousLength] = IERC20ToBytes32MapEntry({ _key: key, _value: value }); map._length = previousLength + 1; // The entry is stored at previousLength, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = previousLength + 1; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Updates the value for an entry, given its key's index. The key index can be retrieved via * {unchecked_indexOf}, and it should be noted that key indices may change when calling {set} or {remove}. O(1). * * This function performs one less storage read than {set}, but it should only be used when `index` is known to be * within bounds. */ function unchecked_setAt( IERC20ToBytes32Map storage map, uint256 index, bytes32 value ) internal { map._entries[index]._value = value; } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(IERC20ToBytes32Map storage map, IERC20 key) internal returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; // Equivalent to contains(map, key) if (keyIndex != 0) { // To delete a key-value pair from the _entries pseudo-array in O(1), we swap the entry to delete with the // one at the highest index, and then remove this last entry (sometimes called as 'swap and pop'). // This modifies the order of the pseudo-array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._length - 1; // The swap is only necessary if we're not removing the last element if (toDeleteIndex != lastIndex) { IERC20ToBytes32MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based } // Delete the slot where the moved entry was stored delete map._entries[lastIndex]; map._length = lastIndex; // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function contains(IERC20ToBytes32Map storage map, IERC20 key) internal view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function length(IERC20ToBytes32Map storage map) internal view returns (uint256) { return map._length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(IERC20ToBytes32Map storage map, uint256 index) internal view returns (IERC20, bytes32) { _require(map._length > index, Errors.OUT_OF_BOUNDS); return unchecked_at(map, index); } /** * @dev Same as {at}, except this doesn't revert if `index` it outside of the map (i.e. if it is equal or larger * than {length}). O(1). * * This function performs one less storage read than {at}, but should only be used when `index` is known to be * within bounds. */ function unchecked_at(IERC20ToBytes32Map storage map, uint256 index) internal view returns (IERC20, bytes32) { IERC20ToBytes32MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Same as {unchecked_At}, except it only returns the value and not the key (performing one less storage * read). O(1). */ function unchecked_valueAt(IERC20ToBytes32Map storage map, uint256 index) internal view returns (bytes32) { return map._entries[index]._value; } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. Reverts with `errorCode` otherwise. */ function get( IERC20ToBytes32Map storage map, IERC20 key, uint256 errorCode ) internal view returns (bytes32) { uint256 index = map._indexes[key]; _require(index > 0, errorCode); return unchecked_valueAt(map, index - 1); } /** * @dev Returns the index for `key`. * * Requirements: * * - `key` must be in the map. */ function indexOf( IERC20ToBytes32Map storage map, IERC20 key, uint256 errorCode ) internal view returns (uint256) { uint256 uncheckedIndex = unchecked_indexOf(map, key); _require(uncheckedIndex != 0, errorCode); return uncheckedIndex - 1; } /** * @dev Returns the index for `key` **plus one**. Does not revert if the key is not in the map, and returns 0 * instead. */ function unchecked_indexOf(IERC20ToBytes32Map storage map, IERC20 key) internal view returns (uint256) { return map._indexes[key]; } // IERC20ToUint256Map struct IERC20ToUint256MapEntry { IERC20 _key; uint256 _value; } struct IERC20ToUint256Map { // Number of entries in the map uint256 _length; // Storage of map keys and values mapping(uint256 => IERC20ToUint256MapEntry) _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping(IERC20 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set( IERC20ToUint256Map storage map, IERC20 key, uint256 value ) internal returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; // Equivalent to !contains(map, key) if (keyIndex == 0) { uint256 previousLength = map._length; map._entries[previousLength] = IERC20ToUint256MapEntry({ _key: key, _value: value }); map._length = previousLength + 1; // The entry is stored at previousLength, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = previousLength + 1; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Updates the value for an entry, given its key's index. The key index can be retrieved via * {unchecked_indexOf}, and it should be noted that key indices may change when calling {set} or {remove}. O(1). * * This function performs one less storage read than {set}, but it should only be used when `index` is known to be * within bounds. */ function unchecked_setAt( IERC20ToUint256Map storage map, uint256 index, uint256 value ) internal { map._entries[index]._value = value; } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(IERC20ToUint256Map storage map, IERC20 key) internal returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; // Equivalent to contains(map, key) if (keyIndex != 0) { // To delete a key-value pair from the _entries pseudo-array in O(1), we swap the entry to delete with the // one at the highest index, and then remove this last entry (sometimes called as 'swap and pop'). // This modifies the order of the pseudo-array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._length - 1; // The swap is only necessary if we're not removing the last element if (toDeleteIndex != lastIndex) { IERC20ToUint256MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based } // Delete the slot where the moved entry was stored delete map._entries[lastIndex]; map._length = lastIndex; // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function contains(IERC20ToUint256Map storage map, IERC20 key) internal view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function length(IERC20ToUint256Map storage map) internal view returns (uint256) { return map._length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(IERC20ToUint256Map storage map, uint256 index) internal view returns (IERC20, uint256) { _require(map._length > index, Errors.OUT_OF_BOUNDS); return unchecked_at(map, index); } /** * @dev Same as {at}, except this doesn't revert if `index` it outside of the map (i.e. if it is equal or larger * than {length}). O(1). * * This function performs one less storage read than {at}, but should only be used when `index` is known to be * within bounds. */ function unchecked_at(IERC20ToUint256Map storage map, uint256 index) internal view returns (IERC20, uint256) { IERC20ToUint256MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Same as {unchecked_At}, except it only returns the value and not the key (performing one less storage * read). O(1). */ function unchecked_valueAt(IERC20ToUint256Map storage map, uint256 index) internal view returns (uint256) { return map._entries[index]._value; } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. Reverts with `errorCode` otherwise. */ function get( IERC20ToUint256Map storage map, IERC20 key, uint256 errorCode ) internal view returns (uint256) { uint256 index = map._indexes[key]; _require(index > 0, errorCode); return unchecked_valueAt(map, index - 1); } /** * @dev Returns the index for `key`. * * Requirements: * * - `key` must be in the map. */ function indexOf( IERC20ToUint256Map storage map, IERC20 key, uint256 errorCode ) internal view returns (uint256) { uint256 uncheckedIndex = unchecked_indexOf(map, key); _require(uncheckedIndex != 0, errorCode); return uncheckedIndex - 1; } /** * @dev Returns the index for `key` **plus one**. Does not revert if the key is not in the map, and returns 0 * instead. */ function unchecked_indexOf(IERC20ToUint256Map storage map, IERC20 key) internal view returns (uint256) { return map._indexes[key]; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-vault/contracts/interfaces/IAsset.sol"; import "../openzeppelin/IERC20.sol"; // solhint-disable function _asIAsset(IERC20[] memory tokens) pure returns (IAsset[] memory assets) { // solhint-disable-next-line no-inline-assembly assembly { assets := tokens } } function _sortTokens( IERC20 tokenA, IERC20 tokenB, IERC20 tokenC ) pure returns (IERC20[] memory tokens) { (uint256 indexTokenA, uint256 indexTokenB, uint256 indexTokenC) = _getSortedTokenIndexes(tokenA, tokenB, tokenC); tokens = new IERC20[](3); tokens[indexTokenA] = tokenA; tokens[indexTokenB] = tokenB; tokens[indexTokenC] = tokenC; } function _getSortedTokenIndexes( IERC20 tokenA, IERC20 tokenB, IERC20 tokenC ) pure returns ( uint256 indexTokenA, uint256 indexTokenB, uint256 indexTokenC ) { if (tokenA < tokenB) { if (tokenB < tokenC) { // (tokenA, tokenB, tokenC) return (0, 1, 2); } else if (tokenA < tokenC) { // (tokenA, tokenC, tokenB) return (0, 2, 1); } else { // (tokenC, tokenA, tokenB) return (1, 2, 0); } } else { // tokenB < tokenA if (tokenC < tokenB) { // (tokenC, tokenB, tokenA) return (2, 1, 0); } else if (tokenC < tokenA) { // (tokenB, tokenC, tokenA) return (2, 0, 1); } else { // (tokenB, tokenA, tokenC) return (1, 0, 2); } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../helpers/LogCompression.sol"; contract MockLogCompression { function toLowResLog(uint256 value) external pure returns (int256) { return LogCompression.toLowResLog(value); } function fromLowResLog(int256 value) external pure returns (uint256) { return LogCompression.fromLowResLog(value); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/test/MockLogCompression.sol"; import "../WeightedOracleMath.sol"; contract MockWeightedOracleMath is WeightedOracleMath, MockLogCompression { function calcLogSpotPrice( uint256 normalizedWeightA, uint256 balanceA, uint256 normalizedWeightB, uint256 balanceB ) external pure returns (int256) { return WeightedOracleMath._calcLogSpotPrice(normalizedWeightA, balanceA, normalizedWeightB, balanceB); } function calcLogBPTPrice( uint256 normalizedWeight, uint256 balance, int256 bptTotalSupplyLn ) external pure returns (int256) { return WeightedOracleMath._calcLogBPTPrice(normalizedWeight, balance, bptTotalSupplyLn); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./MockWeightedOracleMath.sol"; import "../WeightedPool2Tokens.sol"; contract MockWeightedPool2Tokens is WeightedPool2Tokens, MockWeightedOracleMath { using WeightedPool2TokensMiscData for bytes32; struct MiscData { int256 logInvariant; int256 logTotalSupply; uint256 oracleSampleCreationTimestamp; uint256 oracleIndex; bool oracleEnabled; uint256 swapFeePercentage; } constructor(NewPoolParams memory params) WeightedPool2Tokens(params) {} function mockOracleDisabled() external { _setOracleEnabled(false); } function mockOracleIndex(uint256 index) external { _miscData = _miscData.setOracleIndex(index); } function mockMiscData(MiscData memory miscData) external { _miscData = encode(miscData); } /** * @dev Encodes a misc data object into a bytes32 */ function encode(MiscData memory _data) private pure returns (bytes32 data) { data = data.setSwapFeePercentage(_data.swapFeePercentage); data = data.setOracleEnabled(_data.oracleEnabled); data = data.setOracleIndex(_data.oracleIndex); data = data.setOracleSampleCreationTimestamp(_data.oracleSampleCreationTimestamp); data = data.setLogTotalSupply(_data.logTotalSupply); data = data.setLogInvariant(_data.logInvariant); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../WeightedMath.sol"; contract MockWeightedMath is WeightedMath { function invariant(uint256[] memory normalizedWeights, uint256[] memory balances) external pure returns (uint256) { return _calculateInvariant(normalizedWeights, balances); } function outGivenIn( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 tokenAmountIn ) external pure returns (uint256) { return _calcOutGivenIn(tokenBalanceIn, tokenWeightIn, tokenBalanceOut, tokenWeightOut, tokenAmountIn); } function inGivenOut( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 tokenAmountOut ) external pure returns (uint256) { return _calcInGivenOut(tokenBalanceIn, tokenWeightIn, tokenBalanceOut, tokenWeightOut, tokenAmountOut); } function exactTokensInForBPTOut( uint256[] memory balances, uint256[] memory normalizedWeights, uint256[] memory amountsIn, uint256 bptTotalSupply, uint256 swapFee ) external pure returns (uint256) { (uint256 bptOut, ) = _calcBptOutGivenExactTokensIn( balances, normalizedWeights, amountsIn, bptTotalSupply, swapFee ); return bptOut; } function tokenInForExactBPTOut( uint256 tokenBalance, uint256 tokenNormalizedWeight, uint256 bptAmountOut, uint256 bptTotalSupply, uint256 swapFee ) external pure returns (uint256) { (uint256 amountIn, ) = _calcTokenInGivenExactBptOut( tokenBalance, tokenNormalizedWeight, bptAmountOut, bptTotalSupply, swapFee ); return amountIn; } function exactBPTInForTokenOut( uint256 tokenBalance, uint256 tokenNormalizedWeight, uint256 bptAmountIn, uint256 bptTotalSupply, uint256 swapFee ) external pure returns (uint256) { (uint256 amountOut, ) = _calcTokenOutGivenExactBptIn( tokenBalance, tokenNormalizedWeight, bptAmountIn, bptTotalSupply, swapFee ); return amountOut; } function exactBPTInForTokensOut( uint256[] memory currentBalances, uint256 bptAmountIn, uint256 totalBPT ) external pure returns (uint256[] memory) { return _calcTokensOutGivenExactBptIn(currentBalances, bptAmountIn, totalBPT); } function bptInForExactTokensOut( uint256[] memory balances, uint256[] memory normalizedWeights, uint256[] memory amountsOut, uint256 bptTotalSupply, uint256 swapFee ) external pure returns (uint256) { (uint256 bptIn, ) = _calcBptInGivenExactTokensOut( balances, normalizedWeights, amountsOut, bptTotalSupply, swapFee ); return bptIn; } function calculateDueTokenProtocolSwapFeeAmount( uint256 balance, uint256 normalizedWeight, uint256 previousInvariant, uint256 currentInvariant, uint256 protocolSwapFeePercentage ) external pure returns (uint256) { return _calcDueTokenProtocolSwapFeeAmount( balance, normalizedWeight, previousInvariant, currentInvariant, protocolSwapFeePercentage ); } }
This exit function is disabled if the contract is paused. Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`. We exit in a single token, so we initialize amountsOut with zeros And then assign the result to the selected token
function _exitExactBPTInForTokenOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view whenNotPaused returns (uint256, uint256[] memory) { (uint256 bptAmountIn, uint256 tokenIndex) = userData.exactBptInForTokenOut(); _require(tokenIndex < 2, Errors.OUT_OF_BOUNDS); uint256[] memory amountsOut = new uint256[](2); (amountsOut[tokenIndex], ) = WeightedMath._calcTokenOutGivenExactBptIn( balances[tokenIndex], normalizedWeights[tokenIndex], bptAmountIn, totalSupply(), getSwapFeePercentage() ); return (bptAmountIn, amountsOut); }
10,205,657
./partial_match/42/0xAf28207B8266B79665cf38AF6d8376AF981dAd0d/sources/CyclopsBank.sol
owner withdraw ether (wei) sendTo.transfer(amount); end
function ownerWithdrawEther(address payable to_wallet, uint256 amount) external onlyOwner { require(address(this).balance >= amount, "13"); bool success = false; require(success, "15"); }
3,313,082
pragma solidity ^0.4.23; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ /* * Safe Math Smart Contract. * https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ /** * Math operations with safety checks */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(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; } } /** * ERC223 Receiving token Fallback Contract */ contract ERC223ReceivingContract { /** * @dev Standard ERC223 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint256 _value, bytes _data); } /** * ERC223 standard interface */ contract ERC223Interface { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value) public returns (bool success); function transfer(address to, uint256 value, bytes data) public returns (bool success); 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 Transfer(address indexed from, address indexed to, uint256 value, bytes data); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * Implementation of the ERC223 standard token. */ contract ERC223Token is ERC223Interface { using SafeMath for uint256; mapping(address => uint256) balances; // List of user balances mapping (address => mapping (address => uint256)) internal allowed; string public name = "COOPAY COIN TEST"; string public symbol = "COOTEST"; uint8 public decimals = 18; uint256 public totalSupply = 265200000 * (10**18); function ERC223Token() { balances[msg.sender] = totalSupply; } // Function to access name of token . function name() constant returns (string _name) { return name; } // Function to access symbol of token . function symbol() constant returns (string _symbol) { return symbol; } // Function to access decimals of token . function decimals() constant returns (uint8 _decimals) { return decimals; } // Function to access total supply of tokens . function totalSupply() constant returns (uint256 _totalSupply) { return totalSupply; } /** * @dev Transfer the specified amount of tokens to the specified address. * Invokes the `tokenFallback` function if the recipient is a contract. * The token transfer fails if the recipient is a contract * but does not implement the `tokenFallback` function * or the fallback function to receive funds. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _data Transaction metadata. */ function transfer(address _to, uint256 _value, bytes _data) returns (bool success) { require(_value > 0); require(_to != 0x0); require(balances[msg.sender] > 0); uint256 codeLength; assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(_to) } balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); if(codeLength>0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); } emit Transfer(msg.sender, _to, _value, _data); return true; } /** * @dev Transfer the specified amount of tokens to the specified address. * This function works the same with the previous one * but doesn't contain `_data` param. * Added due to backwards compatibility reasons. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. */ function transfer(address _to, uint256 _value) returns (bool success) { require(_value > 0); require(_to != 0x0); require(balances[msg.sender] > 0); uint256 codeLength; bytes memory empty; assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(_to) } balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); if(codeLength>0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, empty); } emit Transfer(msg.sender, _to, _value, empty); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); bytes memory empty; 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,empty); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Returns balance of the `_owner`. * * @param _owner The address whose balance will be returned. * @return balance Balance of the `_owner`. */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } }
Function to access name of token .
function name() constant returns (string _name) { return name; }
353,309
./full_match/5/0x7538aC19E2Ba991c7B2179050618B5732c050760/sources/contracts/RaiseFundContract.sol
function for owner to withdraw funds
function withdraw(address payable _owner) external { require(_owner == msg.sender, "Only owner can withdraw the funds."); uint256 campaignIndex; for (uint256 i = 0; i < numberOfCampaigns; i++) { if (campaigns[i].owner == _owner) { campaignIndex = i; break; } } require(campaignIndex < numberOfCampaigns, "Invalid campaign ID"); campaigns[campaignIndex].amountRaised; emit FundWithdrawn( campaignIndex, campaigns[campaignIndex].name, campaigns[campaignIndex].amountRaised ); campaigns[campaignIndex].amountRaised = 0; }
1,892,930
./partial_match/1/0x17CE9F141745cC9E9769FC5454AF34b33fBc62ba/sources/PoolFactory.sol
Deploys a new pool and LP token. Decimals is an argument as not all ERC20 tokens implement the ERC20Detailed interface. An implementation where `getUnderlying()` returns the zero address is for ETH pools. underlying Address of the pool's underlying. poolArgs Arguments to initialize the pool. lpTokenArgs Arguments to create the LP token for the pool. vaultArgs Arguments to create the vault. implementationNames Name of the implementations to use. return addrs Address of the deployed pool, address of the pool's deployed LP token./ ETH pool solhint-disable-next-line no-inline-assembly
function deployPool( address underlying, PoolArgs calldata poolArgs, LpTokenArgs calldata lpTokenArgs, VaultArgs calldata vaultArgs, ImplementationNames calldata implementationNames ) external override onlyGovernance returns (Addresses memory addrs) { DeployPoolVars memory vars; vars.poolImplementation = implementations[_POOL_KEY][implementationNames.pool]; require(vars.poolImplementation != address(0), Error.INVALID_POOL_IMPLEMENTATION); vars.lpTokenImplementation = implementations[_LP_TOKEN_KEY][implementationNames.lpToken]; require(vars.lpTokenImplementation != address(0), Error.INVALID_LP_TOKEN_IMPLEMENTATION); vars.vaultImplementation = implementations[_VAULT_KEY][implementationNames.vault]; require(vars.vaultImplementation != address(0), Error.INVALID_VAULT_IMPLEMENTATION); vars.stakerVaultImplementation = implementations[_STAKER_VAULT_KEY][ implementationNames.stakerVault ]; require( vars.stakerVaultImplementation != address(0), Error.INVALID_STAKER_VAULT_IMPLEMENTATION ); addrs.pool = Clones.clone(vars.poolImplementation); addrs.vault = Clones.clone(vars.vaultImplementation); if (underlying == address(0)) { require( ILiquidityPool(vars.poolImplementation).getUnderlying() == address(0), Error.INVALID_POOL_IMPLEMENTATION ); require(lpTokenArgs.decimals == 18, Error.INVALID_DECIMALS); IEthPool(addrs.pool).initialize( poolArgs.name, addrs.vault, poolArgs.maxWithdrawalFee, poolArgs.minWithdrawalFee ); IErc20Pool(addrs.pool).initialize( poolArgs.name, underlying, addrs.vault, poolArgs.maxWithdrawalFee, poolArgs.minWithdrawalFee ); } address lpTokenAddress; bytes memory lptokenCreationCode = bytes.concat( lpTokensInitCode[vars.lpTokenImplementation], vars.lpTokenImplementation.code ); assembly { lpTokenAddress := create(0, add(lptokenCreationCode, 32), mload(lptokenCreationCode)) } addrs.lpToken = lpTokenAddress; ILpToken(addrs.lpToken).initialize( lpTokenArgs.name, lpTokenArgs.symbol, lpTokenArgs.decimals, addrs.pool ); addrs.stakerVault = Clones.clone(vars.stakerVaultImplementation); IStakerVault(addrs.stakerVault).initialize(addrs.lpToken); controller.addStakerVault(addrs.stakerVault); ILiquidityPool(addrs.pool).setLpToken(addrs.lpToken); ILiquidityPool(addrs.pool).setStaker(); IVault(addrs.vault).initialize( addrs.pool, vaultArgs.debtLimit, vaultArgs.targetAllocation, vaultArgs.bound ); addressProvider.addPool(addrs.pool); emit NewPool(addrs.pool, addrs.vault, addrs.lpToken, addrs.stakerVault); return addrs; }
4,325,514
pragma solidity 0.4.21; // File: contracts/ExchangeHandler.sol /// @title Interface for all exchange handler contracts interface ExchangeHandler { /// @dev Get the available amount left to fill for an order /// @param orderAddresses Array of address values needed for this DEX order /// @param orderValues Array of uint values needed for this DEX order /// @param exchangeFee Value indicating the fee for this DEX order /// @param v ECDSA signature parameter v /// @param r ECDSA signature parameter r /// @param s ECDSA signature parameter s /// @return Available amount left to fill for this order function getAvailableAmount( address[8] orderAddresses, uint256[6] orderValues, uint256 exchangeFee, uint8 v, bytes32 r, bytes32 s ) external returns (uint256); /// @dev Perform a buy order at the exchange /// @param orderAddresses Array of address values needed for each DEX order /// @param orderValues Array of uint values needed for each DEX order /// @param exchangeFee Value indicating the fee for this DEX order /// @param amountToFill Amount to fill in this order /// @param v ECDSA signature parameter v /// @param r ECDSA signature parameter r /// @param s ECDSA signature parameter s /// @return Amount filled in this order function performBuy( address[8] orderAddresses, uint256[6] orderValues, uint256 exchangeFee, uint256 amountToFill, uint8 v, bytes32 r, bytes32 s ) external payable returns (uint256); /// @dev Perform a sell order at the exchange /// @param orderAddresses Array of address values needed for each DEX order /// @param orderValues Array of uint values needed for each DEX order /// @param exchangeFee Value indicating the fee for this DEX order /// @param amountToFill Amount to fill in this order /// @param v ECDSA signature parameter v /// @param r ECDSA signature parameter r /// @param s ECDSA signature parameter s /// @return Amount filled in this order function performSell( address[8] orderAddresses, uint256[6] orderValues, uint256 exchangeFee, uint256 amountToFill, uint8 v, bytes32 r, bytes32 s ) external returns (uint256); } // File: contracts/WETH9.sol // Copyright (C) 2015, 2016, 2017 Dapphub // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. contract WETH9 { string public name = "Wrapped Ether"; string public symbol = "WETH"; uint8 public decimals = 18; event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); event Deposit(address indexed dst, uint wad); event Withdrawal(address indexed src, uint wad); mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; function() public payable { deposit(); } function deposit() public payable { balanceOf[msg.sender] += msg.value; Deposit(msg.sender, msg.value); } function withdraw(uint wad) public { require(balanceOf[msg.sender] >= wad); balanceOf[msg.sender] -= wad; msg.sender.transfer(wad); Withdrawal(msg.sender, wad); } function totalSupply() public view returns (uint) { return this.balance; } function approve(address guy, uint wad) public returns (bool) { allowance[msg.sender][guy] = wad; Approval(msg.sender, guy, wad); return true; } function transfer(address dst, uint wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom(address src, address dst, uint wad) public returns (bool) { require(balanceOf[src] >= wad); if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) { require(allowance[src][msg.sender] >= wad); allowance[src][msg.sender] -= wad; } balanceOf[src] -= wad; balanceOf[dst] += wad; Transfer(src, dst, wad); return true; } } // 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 OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() 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 transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev 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/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: contracts/AirSwapHandler.sol /** * @title AirSwap interface. */ interface AirSwapInterface { /// @dev Mapping of order hash to bool (true = already filled). function fills( bytes32 hash ) external view returns (bool); /// @dev Fills an order by transferring tokens between (maker or escrow) and taker. /// Maker is given tokenA to taker. function fill( address makerAddress, uint makerAmount, address makerToken, address takerAddress, uint takerAmount, address takerToken, uint256 expiration, uint256 nonce, uint8 v, bytes32 r, bytes32 s ) external payable; } /** * @title AirSwap wrapper contract. * @dev Assumes makers and takers have approved this contract to access their balances. */ contract AirSwapHandler is ExchangeHandler, Ownable { /// @dev AirSwap exhange address AirSwapInterface public airSwap; WETH9 public weth; address public totle; uint256 constant MAX_UINT = 2**256 - 1; modifier onlyTotle() { require(msg.sender == totle); _; } /// @dev Constructor function AirSwapHandler( address _airSwap, address _wethAddress, address _totle ) public { require(_airSwap != address(0x0)); require(_wethAddress != address(0x0)); require(_totle != address(0x0)); airSwap = AirSwapInterface(_airSwap); weth = WETH9(_wethAddress); totle = _totle; } /// @dev Get the available amount left to fill for an order /// @param orderValues Array of uint values needed for this DEX order /// @return Available amount left to fill for this order function getAvailableAmount( address[8], uint256[6] orderValues, uint256, uint8, bytes32, bytes32 ) external returns (uint256) { return orderValues[1]; } /// @dev Perform a buy order at the exchange /// @param orderAddresses Array of address values needed for each DEX order /// @param orderValues Array of uint values needed for each DEX order /// @param amountToFill Amount to fill in this order /// @param v ECDSA signature parameter v /// @param r ECDSA signature parameter r /// @param s ECDSA signature parameter s /// @return Amount filled in this order function performBuy( address[8] orderAddresses, uint256[6] orderValues, uint256, uint256 amountToFill, uint8 v, bytes32 r, bytes32 s ) external onlyTotle payable returns (uint256) { return fillBuy(orderAddresses, orderValues, v, r, s); } /// @dev Perform a sell order at the exchange /// @param orderAddresses Array of address values needed for each DEX order /// @param orderValues Array of uint values needed for each DEX order /// @param amountToFill Amount to fill in this order /// @param v ECDSA signature parameter v /// @param r ECDSA signature parameter r /// @param s ECDSA signature parameter s /// @return Amount filled in this order function performSell( address[8] orderAddresses, uint256[6] orderValues, uint256, uint256 amountToFill, uint8 v, bytes32 r, bytes32 s ) external onlyTotle returns (uint256) { return fillSell(orderAddresses, orderValues, v, r, s); } function setTotle(address _totle) external onlyOwner { require(_totle != address(0)); totle = _totle; } /// @dev The contract is not designed to hold and/or manage tokens. /// Withdraws token in the case of emergency. Only an owner is allowed to call this. function withdrawToken(address _token, uint _amount) external onlyOwner returns (bool) { return ERC20(_token).transfer(owner, _amount); } /// @dev The contract is not designed to hold ETH. /// Withdraws ETH in the case of emergency. Only an owner is allowed to call this. function withdrawETH(uint _amount) external onlyOwner returns (bool) { owner.transfer(_amount); } function approveToken(address _token, uint amount) external onlyOwner { require(ERC20(_token).approve(address(airSwap), amount)); } function() public payable { } /** Validates order arguments for fill() and cancel() functions. */ function validateOrder( address makerAddress, uint makerAmount, address makerToken, address takerAddress, uint takerAmount, address takerToken, uint256 expiration, uint256 nonce) public view returns (bool) { // Hash arguments to identify the order. bytes32 hashV = keccak256(makerAddress, makerAmount, makerToken, takerAddress, takerAmount, takerToken, expiration, nonce); return airSwap.fills(hashV); } /// orderAddresses[0] == makerAddress /// orderAddresses[1] == makerToken /// orderAddresses[2] == takerAddress /// orderAddresses[3] == takerToken /// orderValues[0] = makerAmount /// orderValues[1] = takerAmount /// orderValues[2] = expiration /// orderValues[3] = nonce function fillBuy( address[8] orderAddresses, uint256[6] orderValues, uint8 v, bytes32 r, bytes32 s ) private returns (uint) { airSwap.fill.value(msg.value)(orderAddresses[0], orderValues[0], orderAddresses[1], address(this), orderValues[1], orderAddresses[3], orderValues[2], orderValues[3], v, r, s); require(validateOrder(orderAddresses[0], orderValues[0], orderAddresses[1], address(this), orderValues[1], orderAddresses[3], orderValues[2], orderValues[3])); require(ERC20(orderAddresses[1]).transfer(orderAddresses[2], orderValues[0])); return orderValues[0]; } /// orderAddresses[0] == makerAddress /// orderAddresses[1] == makerToken /// orderAddresses[2] == takerAddress /// orderAddresses[3] == takerToken /// orderValues[0] = makerAmount /// orderValues[1] = takerAmount /// orderValues[2] = expiration /// orderValues[3] = nonce function fillSell( address[8] orderAddresses, uint256[6] orderValues, uint8 v, bytes32 r, bytes32 s ) private returns (uint) { assert(msg.sender == totle); require(orderAddresses[1] == address(weth)); uint takerAmount = orderValues[1]; if(ERC20(orderAddresses[3]).allowance(address(this), address(airSwap)) == 0) { require(ERC20(orderAddresses[3]).approve(address(airSwap), MAX_UINT)); } airSwap.fill(orderAddresses[0], orderValues[0], orderAddresses[1], address(this), takerAmount, orderAddresses[3], orderValues[2], orderValues[3], v, r, s); require(validateOrder(orderAddresses[0], orderValues[0], orderAddresses[1], address(this), takerAmount, orderAddresses[3], orderValues[2], orderValues[3])); weth.withdraw(orderValues[0]); msg.sender.transfer(orderValues[0]); return orderValues[0]; } }
The contract is not designed to hold and/or manage tokens. Withdraws token in the case of emergency. Only an owner is allowed to call this.
function withdrawToken(address _token, uint _amount) external onlyOwner returns (bool) { return ERC20(_token).transfer(owner, _amount); }
6,532,136
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.13; /// @title A library used to construct ERC721 token URIs and SVG images /********************************* * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * * ░░░░░░█████████░░█████████░░░ * * ░░░░░░██░░░████░░██░░░████░░░ * * ░░██████░░░████████░░░████░░░ * * ░░██░░██░░░████░░██░░░████░░░ * * ░░██░░██░░░████░░██░░░████░░░ * * ░░░░░░█████████░░█████████░░░ * * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * *********************************/ import { Base64 } from "base64-sol/base64.sol"; import { MultiPartRLEToSVG } from "./MultiPartRLEToSVG.sol"; library NFTDescriptor { struct TokenURIParams { string name; string description; bytes[] parts; string background; } /** * @notice Construct an ERC721 token URI. */ function constructTokenURI( TokenURIParams memory params, mapping(uint8 => string[]) storage palettes ) public view returns (string memory) { string memory image = generateSVGImage( MultiPartRLEToSVG.SVGParams({ parts: params.parts, background: params.background }), palettes ); // prettier-ignore return string( abi.encodePacked( 'data:application/json;base64,', Base64.encode( bytes( abi.encodePacked('{"name":"', params.name, '", "description":"', params.description, '", "image": "', 'data:image/svg+xml;base64,', image, '"}') ) ) ) ); } /** * @notice Generate an SVG image for use in the ERC721 token URI. */ function generateSVGImage( MultiPartRLEToSVG.SVGParams memory params, mapping(uint8 => string[]) storage palettes ) public view returns (string memory svg) { return Base64.encode(bytes(MultiPartRLEToSVG.generateSVG(params, palettes))); } }
Construct an ERC721 token URI./
function constructTokenURI( TokenURIParams memory params, mapping(uint8 => string[]) storage palettes ) public view returns (string memory) { string memory image = generateSVGImage( MultiPartRLEToSVG.SVGParams({ parts: params.parts, background: params.background }), palettes ); abi.encodePacked( 'data:application/json;base64,', Base64.encode( bytes( ) ) ) ); }
7,327,764
./partial_match/1/0xc4bd005c40d4Ec27Fb1085E5aEdd083843B8a3E0/sources/AHunterReturns.sol
once enabled, can never be turned off
function enableTrade() external onlyOwner { swappingsEnabled = true; tradingsStarted = true; lastLpBurnTime = block.timestamp; }
15,725,850
pragma solidity 0.4.24; pragma experimental "v0.5.0"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "../token/ITokenContract.sol"; /** * @dev Supports ERC20 tokens * The escrow smart contract for the open bazaar trades in Ethereum * The smart contract is desgined keeping in mind the current wallet interface of the OB-core * https://github.com/OpenBazaar/wallet-interface/blob/master/wallet.go * Current wallet interface strictly adheres to UTXO(bitcoin) model */ contract Escrow_v1_0 { using SafeMath for uint256; enum Status {FUNDED, RELEASED} enum TransactionType {ETHER, TOKEN} event Executed(bytes32 scriptHash, address[] destinations, uint256[] amounts); event FundAdded(bytes32 scriptHash, address indexed from, uint256 valueAdded); event Funded(bytes32 scriptHash, address indexed from, uint256 value); struct Transaction { bytes32 scriptHash;//This is unique indentifier for a transaction address buyer; address seller; address[] moderators; uint256 value; Status status; string ipfsHash; uint256 lastFunded;//Time at which transaction was last funded uint32 timeoutHours; uint8 threshold; mapping(address=>bool) isOwner;//to keep track of owners/signers. mapping(address=>bool) voted;//to keep track of who all voted TransactionType transactionType; address tokenAddress;// Token address in case of token transfer } mapping(bytes32 => Transaction) public transactions; uint256 public transactionCount = 0; mapping(address => bytes32[])public partyVsTransaction;//Contains mapping between each party and all of his transactions modifier transactionExists(bytes32 scriptHash) { require(transactions[scriptHash].value != 0, "Transaction does not exists"); _; } modifier transactionDoesNotExists (bytes32 scriptHash) { require(transactions[scriptHash].value == 0, "Transaction exists"); _; } modifier inFundedState(bytes32 scriptHash) { require(transactions[scriptHash].status == Status.FUNDED, "Transaction is either in dispute or released state"); _; } modifier nonZeroAddress(address _address) { require(_address != address(0), "Zero address passed"); _; } modifier checkTransactionType(bytes32 scriptHash, TransactionType transactionType) { require(transactions[scriptHash].transactionType == transactionType, "Transaction type does not match"); _; } modifier onlyBuyer(bytes32 scriptHash) { require(msg.sender == transactions[scriptHash].buyer, "The initiator of the transaction is not buyer"); _; } /** *@dev Add new transaction in the contract *@param _buyer The buyer of the transaction *@param _seller The seller of the listing associated with the transaction *@param _moderators List of moderators for this transaction. For now only single moderator *@param scriptHash keccak256 hash of the redeem script *@param threshold Minimum number of singatures required to released funds *@param timeoutHours Hours after which seller can release funds into his favour by signing transaction *Redeem Script format will be following <uniqueId: 20><threshold:1><timeoutHours:4><buyer:20><seller:20><moderator:20><multisigAddress:20> * scripthash-> keccak256(uniqueId, threshold, timeoutHours, buyer, seller, moderator) *Pass amount of the ethers to be put in escrow *Please keep in mind you will have to add moderators fees also in the value */ function addTransaction(address _buyer, address _seller, address[] _moderators, uint8 threshold, uint32 timeoutHours, bytes32 scriptHash) public payable transactionDoesNotExists(scriptHash) nonZeroAddress(_buyer) nonZeroAddress(_seller){ addTransactionInternal(_buyer, _seller, _moderators, threshold, timeoutHours, scriptHash, msg.value, TransactionType.ETHER, address(0)); } /** *@dev Add new transaction in the contract *@param _buyer The buyer of the transaction *@param _seller The seller of the listing associated with the transaction *@param _moderators List of moderators for this transaction. For now only single moderator *@param scriptHash keccak256 hash of the redeem script *@param threshold Minimum number of singatures required to released funds *@param timeoutHours Hours after which seller can release funds into his favour by signing transaction *@param value Amount of tokens to be put in escrow *@param _tokenAddress Address of the token to be used *Redeem Script format will be following <uniqueId: 20><threshold:1><timeoutHours:4><buyer:20><seller:20><moderator:20><multisigAddress:20><tokenAddress:20> * scripthash-> keccak256(uniqueId, threshold, timeoutHours, buyer, seller, moderator, tokenAddress) *approve escrow contract to spend amount of token on your behalf *Please keep in mind you will have to add moderators fees also in the value */ function addTokenTransaction(address _buyer, address _seller, address[] _moderators, uint8 threshold, uint32 timeoutHours, bytes32 scriptHash, uint256 value, address _tokenAddress)public transactionDoesNotExists(scriptHash) nonZeroAddress(_buyer) nonZeroAddress(_seller) nonZeroAddress(_tokenAddress){ ITokenContract token = ITokenContract(_tokenAddress); require(token.transferFrom(msg.sender, this, value), "Token transfer failed, maybe you did not approve escrow contract to spend on behalf of buyer"); addTransactionInternal(_buyer, _seller, _moderators, threshold, timeoutHours, scriptHash, value, TransactionType.TOKEN, _tokenAddress); } /** * Internal method to add transaction to reduce code redundancy */ function addTransactionInternal(address _buyer, address _seller, address[] _moderators, uint8 threshold, uint32 timeoutHours, bytes32 scriptHash, uint256 value, TransactionType _transactionType, address _tokenAddress)internal { uint256 _value = value; require(_buyer != _seller, "Buyer and seller are same"); //value passed should be greater than 0 require(_value>0, "Value passed is 0"); // For now allowing 0 moderators to support 1-2 multisig wallet //require(_moderators.length>0,"There should be atleast 1 moderator");//TODO- What to do in case of 1-2 multi sig transaction require(threshold <= _moderators.length + 2, "Threshold is greater than total owners"); require(threshold > 0, "Threshold can't be 0"); transactions[scriptHash] = Transaction({ buyer: _buyer, seller: _seller, moderators: _moderators, value: _value, status: Status.FUNDED, ipfsHash: "", lastFunded: block.timestamp, scriptHash: scriptHash, threshold: threshold, timeoutHours: timeoutHours, transactionType:_transactionType, tokenAddress:_tokenAddress }); transactions[scriptHash].isOwner[_seller] = true; transactions[scriptHash].isOwner[_buyer] = true; for(uint8 i=0;i<_moderators.length; i++){ require(_moderators[i] != address(0), "Zero address passed"); require(!transactions[scriptHash].isOwner[_moderators[i]], "Moderator is beign repeated");//Check if same moderator is not passed twice in the list transactions[scriptHash].isOwner[_moderators[i]] = true; } transactionCount++; partyVsTransaction[_buyer].push(scriptHash); partyVsTransaction[_seller].push(scriptHash); emit Funded(scriptHash, msg.sender, _value); } /** *@dev Allows buyer of the transaction to add more funds(ether) in the transaction. This will help to cater scenarios wherein initially buyer missed to fund transaction as required *@param scriptHash script hash of the transaction * Only buyer of the transaction can invoke this method */ function addFundsToTransaction(bytes32 scriptHash)public transactionExists(scriptHash) inFundedState(scriptHash) checkTransactionType(scriptHash, TransactionType.ETHER) onlyBuyer(scriptHash) payable{ uint256 _value = msg.value; require(_value > 0); transactions[scriptHash].value = transactions[scriptHash].value.add(_value); transactions[scriptHash].lastFunded = block.timestamp; emit FundAdded(scriptHash, msg.sender, _value); } /** *@dev Allows buyer of the transaction to add more funds(Tokens) in the transaction. This will help to cater scenarios wherein initially buyer missed to fund transaction as required *@param scriptHash script hash of the transaction */ function addTokensToTransaction(bytes32 scriptHash, uint256 value)public transactionExists(scriptHash) inFundedState(scriptHash) checkTransactionType(scriptHash, TransactionType.TOKEN) onlyBuyer(scriptHash)payable{ uint256 _value = value; require(_value > 0); ITokenContract token = ITokenContract(transactions[scriptHash].tokenAddress); require(token.transferFrom(transactions[scriptHash].buyer, this, value), "Token transfer failed, maybe you did not approve escrow contract to spend on behalf of buyer"); transactions[scriptHash].value = transactions[scriptHash].value.add(_value); transactions[scriptHash].lastFunded = block.timestamp; emit FundAdded(scriptHash, msg.sender, _value); } /** *@dev Allows one of the moderator to collect all the signature to solve dispute and submit it to this method. * If all the required signatures are collected and consensus has been reached than funds will be released to the voted party *@param sigV Array containing V component of all the signatures(signed by each moderator) *@param sigR Array containing R component of all the signatures(signed by each moderator) *@param signS Array containing S component of all the signature(signed by each moderator) *@param scriptHash script hash of the transaction *@param uniqueId bytes20 unique id for the transaction, generated by ETH wallet *@param destinations address of the destination in whose favour dispute resolution is taking place. In case of split payments it will be address of the split payments contract *@param amounts value to send to each destination */ function execute(uint8[] sigV, bytes32[] sigR, bytes32[] sigS, bytes32 scriptHash, bytes20 uniqueId, address[] destinations, uint256[] amounts) public transactionExists(scriptHash) inFundedState(scriptHash){ require(destinations.length>0 && destinations.length == amounts.length); Transaction storage t = transactions[scriptHash]; bytes32 calculatedScriptHash = calculateRdeemScriptHash(scriptHash, uniqueId); require(scriptHash == calculatedScriptHash, "Calculated script hash does not match passed script hash"); address lastRecovered = verifySignatures(sigV, sigR, sigS, scriptHash, destinations, amounts); bool timeLockExpired = isTimeLockExpired(t.timeoutHours, t.lastFunded); //assumin threshold will always be greater than 1, else its not multisig if(sigV.length < t.threshold && !timeLockExpired){ revert(); }else if(sigV.length == 1 && timeLockExpired && lastRecovered != t.seller){ revert(); }else if(sigV.length < t.threshold){ revert(); } transactions[scriptHash].status = Status.RELEASED; uint256 totalValue = transferFunds(scriptHash, destinations, amounts); require(totalValue <= transactions[scriptHash].value, "Total value to be sent is greater than the transaction value"); emit Executed(scriptHash, destinations, amounts); } /** *@dev Internal method to transfer funds to the destination addresses on the basis of transaction type */ function transferFunds(bytes32 scriptHash, address[]destinations, uint256[]amounts)internal returns(uint256 valueTransferred) { Transaction storage t = transactions[scriptHash]; if(t.transactionType == TransactionType.ETHER){ for(uint8 i = 0; i<destinations.length; i++) { require(destinations[i] != address(0) && t.isOwner[destinations[i]], "Not a valid destination"); require(amounts[i] > 0, "Amount to be sent should be greater than 0"); valueTransferred = valueTransferred.add(amounts[i]); destinations[i].transfer(amounts[i]);//shall we use send instead of transfer to stop malicious actors from blocking funds? } }else if(t.transactionType == TransactionType.TOKEN){ ITokenContract token = ITokenContract(t.tokenAddress); for(uint8 i = 0; i<destinations.length; i++) { require(destinations[i] != address(0) && t.isOwner[destinations[i]], "Not a valid destination"); require(amounts[i] > 0, "Amount to be sent should be greater than 0"); valueTransferred = valueTransferred.add(amounts[i]); require(token.transfer(destinations[i], amounts[i])); } }else{ //transaction type is not supported. Ideally this state should never be reached revert(); } } /** *@dev Internal method for calculating script hash. Calculation will depend upon the type of transaction * ETHER Type transaction-: * Script Hash- keccak256(uniqueId, threshold, timeoutHours, buyer, seller, moderator) * TOKEN Type transaction * Script Hash- keccak256(uniqueId, threshold, timeoutHours, buyer, seller, moderator, tokenAddress) */ function calculateRdeemScriptHash(bytes32 scriptHash, bytes20 uniqueId)internal view returns (bytes32 hash){ Transaction storage t = transactions[scriptHash]; if(t.transactionType == TransactionType.ETHER){ hash = keccak256(abi.encodePacked(uniqueId, t.threshold, t.timeoutHours, t.buyer, t.seller, t.moderators[0], this)); } else if(t.transactionType == TransactionType.TOKEN){ hash = keccak256(abi.encodePacked(uniqueId, t.threshold, t.timeoutHours, t.buyer, t.seller, t.moderators[0], this, t.tokenAddress)); } } //to check whether the signature are valid or not and if consensus was reached //returns the last address recovered, in case of timeout this must be the sender's address function verifySignatures(uint8[] sigV, bytes32[] sigR, bytes32[] sigS, bytes32 scriptHash, address[] destinations, uint256[]amounts) private returns (address lastAddress){ require(sigR.length == sigS.length && sigR.length == sigV.length); // Follows ERC191 signature scheme: https://github.com/ethereum/EIPs/issues/191 bytes32 txHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", keccak256(abi.encodePacked(byte(0x19), byte(0), this, destinations, amounts, scriptHash)))); for (uint i = 0; i < sigR.length; i++) { address recovered = ecrecover(txHash, sigV[i], sigR[i], sigS[i]); require(transactions[scriptHash].isOwner[recovered], "Invalid signature"); require(!transactions[scriptHash].voted[recovered], "Same signature sent twice"); transactions[scriptHash].voted[recovered] = true; lastAddress = recovered; } } /** *@dev Returns all transaction ids for a party *@param _partyAddress Address of the party */ function getAllTransactionsForParty(address _partyAddress)public view returns(bytes32[] scriptHashes) { return partyVsTransaction[_partyAddress]; } function isTimeLockExpired(uint32 timeoutHours, uint256 lastFunded)internal view returns(bool expired){ uint256 timeSince = now.sub(lastFunded); expired = timeoutHours == 0?false:timeSince > uint256(timeoutHours).mul(3600); } }
scripthash-> keccak256(uniqueId, threshold, timeoutHours, buyer, seller, moderator)Pass amount of the ethers to be put in escrowPlease keep in mind you will have to add moderators fees also in the value/
function addTransaction(address _buyer, address _seller, address[] _moderators, uint8 threshold, uint32 timeoutHours, bytes32 scriptHash) public payable transactionDoesNotExists(scriptHash) nonZeroAddress(_buyer) nonZeroAddress(_seller){ addTransactionInternal(_buyer, _seller, _moderators, threshold, timeoutHours, scriptHash, msg.value, TransactionType.ETHER, address(0)); }
6,411,365
./partial_match/1/0x6637f59689C70eBCb0F01EC2D0b8D0567aD6171B/sources/contracts/OSM/SetPackable.sol
Returns the number of tokens in `owner`'s account./
function balanceOf(PackableData storage self, address owner) public view returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return self._packedAddressData[owner] & _BITMASK_ADDRESS_DATA_ENTRY; }
15,589,589
pragma solidity ^0.4.21; contract ERC820Registry { function getManager(address addr) public view returns(address); function setManager(address addr, address newManager) public; function getInterfaceImplementer(address addr, bytes32 iHash) public constant returns (address); function setInterfaceImplementer(address addr, bytes32 iHash, address implementer) public; } contract ERC820Implementer { ERC820Registry erc820Registry = ERC820Registry(0x991a1bcb077599290d7305493c9A630c20f8b798); function setInterfaceImplementation(string ifaceLabel, address impl) internal { bytes32 ifaceHash = keccak256(ifaceLabel); erc820Registry.setInterfaceImplementer(this, ifaceHash, impl); } function interfaceAddr(address addr, string ifaceLabel) internal constant returns(address) { bytes32 ifaceHash = keccak256(ifaceLabel); return erc820Registry.getInterfaceImplementer(addr, ifaceHash); } function delegateManagement(address newManager) internal { erc820Registry.setManager(this, newManager); } } /** * @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 OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() 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 transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /// @title ERC777 ReferenceToken Contract /// @author Jordi Baylina, Jacques Dafflon /// @dev This token contract&#39;s goal is to give an example implementation /// of ERC777 with ERC20 compatiblity using the base ERC777 and ERC20 /// implementations provided with the erc777 package. /// This contract does not define any standard, but can be taken as a reference /// implementation in case of any ambiguity into the standard /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This code has not been reviewed. * Do not use or deploy this code before reviewing it personally first. */ // solhint-disable-next-line compiler-fixed interface ERC20Token { function name() public constant returns (string); function symbol() public constant returns (string); function decimals() public constant returns (uint8); function totalSupply() public constant returns (uint256); function balanceOf(address owner) public constant returns (uint256); function transfer(address to, uint256 amount) public returns (bool); function transferFrom(address from, address to, uint256 amount) public returns (bool); function approve(address spender, uint256 amount) public returns (bool); function allowance(address owner, address spender) public constant returns (uint256); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /** * @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) { 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&#39;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; } } /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This code has not been reviewed. * Do not use or deploy this code before reviewing it personally first. */ // solhint-disable-next-line compiler-fixed interface ERC777Token { function name() public view returns (string); function symbol() public view returns (string); function totalSupply() public view returns (uint256); function balanceOf(address owner) public view returns (uint256); function granularity() public view returns (uint256); function defaultOperators() public view returns (address[]); function isOperatorFor(address operator, address tokenHolder) public view returns (bool); function authorizeOperator(address operator) public; function revokeOperator(address operator) public; function send(address to, uint256 amount, bytes holderData) public; function operatorSend(address from, address to, uint256 amount, bytes holderData, bytes operatorData) public; function burn(uint256 amount, bytes holderData) public; function operatorBurn(address from, uint256 amount, bytes holderData, bytes operatorData) public; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes holderData, bytes operatorData ); // solhint-disable-next-line separate-by-one-line-in-contract event Minted(address indexed operator, address indexed to, uint256 amount, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes holderData, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This code has not been reviewed. * Do not use or deploy this code before reviewing it personally first. */ // solhint-disable-next-line compiler-fixed interface ERC777TokensSender { function tokensToSend( address operator, address from, address to, uint amount, bytes userData, bytes operatorData ) public; } /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This code has not been reviewed. * Do not use or deploy this code before reviewing it personally first. */ // solhint-disable-next-line compiler-fixed interface ERC777TokensRecipient { function tokensReceived( address operator, address from, address to, uint amount, bytes userData, bytes operatorData ) public; } contract ERC777BaseToken is ERC777Token, ERC820Implementer { using SafeMath for uint256; string internal mName; string internal mSymbol; uint256 internal mGranularity; uint256 internal mTotalSupply; mapping(address => uint) internal mBalances; mapping(address => mapping(address => bool)) internal mAuthorized; address[] internal mDefaultOperators; mapping(address => bool) internal mIsDefaultOperator; mapping(address => mapping(address => bool)) internal mRevokedDefaultOperator; /* -- Constructor -- */ // /// @notice Constructor to create a ReferenceToken /// @param _name Name of the new token /// @param _symbol Symbol of the new token. /// @param _granularity Minimum transferable chunk. function ERC777BaseToken(string _name, string _symbol, uint256 _granularity, address[] _defaultOperators) internal { mName = _name; mSymbol = _symbol; mTotalSupply = 0; require(_granularity >= 1); mGranularity = _granularity; mDefaultOperators = _defaultOperators; for (uint i = 0; i < mDefaultOperators.length; i++) { mIsDefaultOperator[mDefaultOperators[i]] = true; } setInterfaceImplementation("ERC777Token", this); } /* -- ERC777 Interface Implementation -- */ // /// @return the name of the token function name() public constant returns (string) { return mName; } /// @return the symbol of the token function symbol() public constant returns (string) { return mSymbol; } /// @return the granularity of the token function granularity() public constant returns (uint256) { return mGranularity; } /// @return the total supply of the token function totalSupply() public constant returns (uint256) { return mTotalSupply; } /// @notice Return the account balance of some account /// @param _tokenHolder Address for which the balance is returned /// @return the balance of `_tokenAddress`. function balanceOf(address _tokenHolder) public constant returns (uint256) { return mBalances[_tokenHolder]; } /// @notice Return the list of default operators /// @return the list of all the default operators function defaultOperators() public view returns (address[]) { return mDefaultOperators; } /// @notice Send `_amount` of tokens to address `_to` passing `_userData` to the recipient /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent function send(address _to, uint256 _amount, bytes _userData) public { doSend(msg.sender, msg.sender, _to, _amount, _userData, "", true); } /// @notice Authorize a third party `_operator` to manage (send) `msg.sender`&#39;s tokens. /// @param _operator The operator that wants to be Authorized function authorizeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = false; } else { mAuthorized[_operator][msg.sender] = true; } AuthorizedOperator(_operator, msg.sender); } /// @notice Revoke a third party `_operator`&#39;s rights to manage (send) `msg.sender`&#39;s tokens. /// @param _operator The operator that wants to be Revoked function revokeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = true; } else { mAuthorized[_operator][msg.sender] = false; } RevokedOperator(_operator, msg.sender); } /// @notice Check whether the `_operator` address is allowed to manage the tokens held by `_tokenHolder` address. /// @param _operator address to check if it has the right to manage the tokens /// @param _tokenHolder address which holds the tokens to be managed /// @return `true` if `_operator` is authorized for `_tokenHolder` function isOperatorFor(address _operator, address _tokenHolder) public constant returns (bool) { return (_operator == _tokenHolder || mAuthorized[_operator][_tokenHolder] || (mIsDefaultOperator[_operator] && !mRevokedDefaultOperator[_operator][_tokenHolder])); } /// @notice Send `_amount` of tokens on behalf of the address `from` to the address `to`. /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be sent to the recipient /// @param _operatorData Data generated by the operator to be sent to the recipient function operatorSend(address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _from)); doSend(msg.sender, _from, _to, _amount, _userData, _operatorData, true); } function burn(uint256 _amount, bytes _holderData) public { doBurn(msg.sender, msg.sender, _amount, _holderData, ""); } function operatorBurn(address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _tokenHolder)); doBurn(msg.sender, _tokenHolder, _amount, _holderData, _operatorData); } /* -- Helper Functions -- */ // /// @notice Internal function that ensures `_amount` is multiple of the granularity /// @param _amount The quantity that want&#39;s to be checked function requireMultiple(uint256 _amount) internal view { require(_amount.div(mGranularity).mul(mGranularity) == _amount); } /// @notice Check whether an address is a regular address or not. /// @param _addr Address of the contract that has to be checked /// @return `true` if `_addr` is a regular address (not a contract) function isRegularAddress(address _addr) internal constant returns(bool) { if (_addr == 0) { return false; } uint size; assembly { size := extcodesize(_addr) } // solhint-disable-line no-inline-assembly return size == 0; } /// @notice Helper function actually performing the sending of tokens. /// @param _operator The address performing the send /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `erc777_tokenHolder`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function doSend( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { requireMultiple(_amount); callSender(_operator, _from, _to, _amount, _userData, _operatorData); require(_to != address(0)); // forbid sending to 0x0 (=burning) require(mBalances[_from] >= _amount); // ensure enough funds mBalances[_from] = mBalances[_from].sub(_amount); mBalances[_to] = mBalances[_to].add(_amount); callRecipient(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking); Sent(_operator, _from, _to, _amount, _userData, _operatorData); } /// @notice Helper function actually performing the burning of tokens. /// @param _operator The address performing the burn /// @param _tokenHolder The address holding the tokens being burn /// @param _amount The number of tokens to be burnt /// @param _holderData Data generated by the token holder /// @param _operatorData Data generated by the operator function doBurn(address _operator, address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) internal { requireMultiple(_amount); require(balanceOf(_tokenHolder) >= _amount); mBalances[_tokenHolder] = mBalances[_tokenHolder].sub(_amount); mTotalSupply = mTotalSupply.sub(_amount); callSender(_operator, _tokenHolder, 0x0, _amount, _holderData, _operatorData); Burned(_operator, _tokenHolder, _amount, _holderData, _operatorData); } /// @notice Helper function that checks for ERC777TokensRecipient on the recipient and calls it. /// May throw according to `_preventLocking` /// @param _operator The address performing the send or mint /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `ERC777TokensRecipient`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callRecipient( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { address recipientImplementation = interfaceAddr(_to, "ERC777TokensRecipient"); if (recipientImplementation != 0) { ERC777TokensRecipient(recipientImplementation).tokensReceived( _operator, _from, _to, _amount, _userData, _operatorData); } else if (_preventLocking) { require(isRegularAddress(_to)); } } /// @notice Helper function that checks for ERC777TokensSender on the sender and calls it. /// May throw according to `_preventLocking` /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The amount of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// implementing `ERC777TokensSender`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callSender( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData ) internal { address senderImplementation = interfaceAddr(_from, "ERC777TokensSender"); if (senderImplementation == 0) { return; } ERC777TokensSender(senderImplementation).tokensToSend(_operator, _from, _to, _amount, _userData, _operatorData); } } contract ERC777ERC20BaseToken is ERC20Token, ERC777BaseToken { bool internal mErc20compatible; bool public unlocked; mapping(address => mapping(address => bool)) internal mAuthorized; mapping(address => mapping(address => uint256)) internal mAllowed; function ERC777ERC20BaseToken( string _name, string _symbol, uint256 _granularity, address[] _defaultOperators ) internal ERC777BaseToken(_name, _symbol, _granularity, _defaultOperators) { mErc20compatible = true; unlocked = true; setInterfaceImplementation("ERC20Token", this); } /// @notice This modifier is applied to erc20 obsolete methods that are /// implemented only to maintain backwards compatibility. When the erc20 /// compatibility is disabled, this methods will fail. modifier erc20 () { require(mErc20compatible); _; } /// @notice For Backwards compatibility /// @return The decimls of the token. Forced to 18 in ERC777. function decimals() public erc20 constant returns (uint8) { return uint8(18); } /// @notice ERC20 backwards compatible transfer. /// @param _to The address of the recipient /// @param _amount The number of tokens to be transferred /// @return `true`, if the transfer can&#39;t be done, it should fail. function transfer(address _to, uint256 _amount) public erc20 returns (bool success) { doSend(msg.sender, msg.sender, _to, _amount, "", "", false); return true; } /// @notice ERC20 backwards compatible transferFrom. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The number of tokens to be transferred /// @return `true`, if the transfer can&#39;t be done, it should fail. function transferFrom(address _from, address _to, uint256 _amount) public erc20 returns (bool success) { require(_amount <= mAllowed[_from][msg.sender]); // Cannot be after doSend because of tokensReceived re-entry mAllowed[_from][msg.sender] = mAllowed[_from][msg.sender].sub(_amount); doSend(msg.sender, _from, _to, _amount, "", "", false); return true; } /// @notice ERC20 backwards compatible approve. /// `msg.sender` approves `_spender` to spend `_amount` tokens on its behalf. /// @param _spender The address of the account able to transfer the tokens /// @param _amount The number of tokens to be approved for transfer /// @return `true`, if the approve can&#39;t be done, it should fail. function approve(address _spender, uint256 _amount) public erc20 returns (bool success) { mAllowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /// @notice ERC20 backwards compatible allowance. /// This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender) public erc20 constant returns (uint256 remaining) { return mAllowed[_owner][_spender]; } function doSend( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { require(unlocked); super.doSend(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking); if (mErc20compatible) { Transfer(_from, _to, _amount); } } function doBurn(address _operator, address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) internal { super.doBurn(_operator, _tokenHolder, _amount, _holderData, _operatorData); if (mErc20compatible) { Transfer(_tokenHolder, 0x0, _amount); } } } contract ReferenceToken is ERC777ERC20BaseToken, Ownable { address private mBurnOperator; function ReferenceToken( string _name, string _symbol, uint256 _granularity, address[] _defaultOperators, address _burnOperator ) public ERC777ERC20BaseToken(_name, _symbol, _granularity, _defaultOperators) { mBurnOperator = _burnOperator; } /// @notice Disables the ERC20 interface. This function can only be called /// by the owner. function disableERC20() public onlyOwner { mErc20compatible = false; setInterfaceImplementation("ERC20Token", 0x0); } /// @notice Re enables the ERC20 interface. This function can only be called /// by the owner. function enableERC20() public onlyOwner { mErc20compatible = true; setInterfaceImplementation("ERC20Token", this); } /// @notice Disables an interface. This function can only be called /// by the owner. function disableInterface(string _interface) public onlyOwner { setInterfaceImplementation(_interface, 0x0); } /// @notice Enables an interface. This function can only be called /// by the owner. function enableInterface(string _interface, address _impl) public onlyOwner { setInterfaceImplementation(_interface, _impl); } /// @notice sets the manager of register implementations of interfaces. This function can only be called /// by the owner. function delegateERC820Management(address _newManager) public onlyOwner { delegateManagement(_newManager); } /// @notice Locks the token. In later stage, this feature will be disabled. This function can only be called /// by the owner. function lock() public onlyOwner { unlocked = false; } /// @notice Unlocks the token. This function can only be called /// by the owner. function unlock() public onlyOwner { unlocked = true;} /* -- Mint And Burn Functions (not part of the ERC777 standard, only the Events/tokensReceived call are) -- */ // /// @notice Generates `_amount` tokens to be assigned to `_tokenHolder` /// Sample mint function to showcase the use of the `Minted` event and the logic to notify the recipient. /// @param _tokenHolder The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @param _operatorData Data that will be passed to the recipient as a first transfer function mint(address _tokenHolder, uint256 _amount, bytes _operatorData) public onlyOwner { requireMultiple(_amount); mTotalSupply = mTotalSupply.add(_amount); mBalances[_tokenHolder] = mBalances[_tokenHolder].add(_amount); callRecipient(msg.sender, 0x0, _tokenHolder, _amount, "", _operatorData, true); Minted(msg.sender, _tokenHolder, _amount, _operatorData); if (mErc20compatible) { Transfer(0x0, _tokenHolder, _amount); } } /// @notice Burns `_amount` tokens from `_tokenHolder` /// Silly example of overriding the `burn` function to only let the owner burn its tokens. /// Do not forget to override the `burn` function in your token contract if you want to prevent users from /// burning their tokens. /// @param _amount The quantity of tokens to burn function burn(uint256 _amount, bytes _holderData) public onlyOwner { require(msg.sender == mBurnOperator); super.burn(_amount, _holderData); } /// @notice Burns `_amount` tokens from `_tokenHolder` by `_operator` /// Silly example of overriding the `operatorBurn` function to only let a specific operator burn tokens. /// Do not forget to override the `operatorBurn` function in your token contract if you want to prevent users from /// burning their tokens. /// @param _tokenHolder The address that will lose the tokens /// @param _amount The quantity of tokens to burn function operatorBurn(address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) public { require(msg.sender == mBurnOperator); super.operatorBurn(_tokenHolder, _amount, _holderData, _operatorData); } }
Revoke a third party `_operator`&39;s rights to manage (send) `msg.sender`&39;s tokens. _operator The operator that wants to be Revoked
function revokeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = true; mAuthorized[_operator][msg.sender] = false; } RevokedOperator(_operator, msg.sender); }
2,445,220
// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "./CampaignFactory.sol"; import "./Campaign.sol"; import "../utils/Roles.sol"; import "../interfaces/ICampaignFactory.sol"; import "../interfaces/ICampaign.sol"; import "../utils/AccessControl.sol"; import "../libraries/contracts/CampaignFactoryLib.sol"; import "../libraries/contracts/CampaignLib.sol"; contract CampaignReward is Initializable, Roles, PausableUpgradeable { using SafeMathUpgradeable for uint256; /// @dev `Initializer Event` event CampaignRewardOwnerSet(address owner); /// @dev `Reward Events` event RewardCreated( uint256 indexed rewardId, uint256 value, uint256 deliveryDate, uint256 stock, string hashedReward, bool active ); event RewardModified( uint256 indexed rewardId, uint256 value, uint256 deliveryDate, uint256 stock, bool active ); event RewardStockIncreased(uint256 indexed rewardId, uint256 count); event RewardDestroyed(uint256 indexed rewardId); /// @dev `Rward Recipient Events` event RewardRecipientAdded( uint256 indexed rewardRecipientId, uint256 indexed rewardId, uint256 amount, address indexed user ); event RewarderApproval(uint256 indexed rewardRecipientId, bool status); event RewardRecipientApproval(uint256 indexed rewardRecipientId); ICampaignFactory public campaignFactoryInterface; ICampaign public campaignInterface; address public campaignRewardAddress; Campaign public campaign; /// @dev `Reward` struct Reward { uint256 value; uint256 deliveryDate; uint256 stock; string hashedReward; bool exists; bool active; } Reward[] public rewards; mapping(uint256 => uint256) public rewardToRewardRecipientCount; // number of users eligible per reward /// @dev `RewardRecipient` struct RewardRecipient { uint256 rewardId; address user; bool deliveryConfirmedByCampaign; bool deliveryConfirmedByUser; } RewardRecipient[] public rewardRecipients; mapping(address => uint256) public userRewardCount; // number of rewards owned by a user /// @dev Ensures a user is verified modifier userIsVerified(address _user) { bool verified; (, , verified) = CampaignFactoryLib.userInfo( campaignFactoryInterface, _user ); require(verified, "user not verified"); _; } /// @dev Ensures caller is a registered campaign contract from factory modifier onlyRegisteredCampaigns() { require(address(campaign) == msg.sender, "forbidden"); _; } /// @dev Ensures caller is campaign owner modifier hasRole(bytes32 _permission, address _user) { require(campaignInterface.isAllowed(_permission, _user)); _; } /** * @dev Constructor * @param _campaignFactory Address of factory * @param _campaign Address of campaign this contract belongs to */ function __CampaignReward_init( CampaignFactory _campaignFactory, Campaign _campaign ) public initializer { campaignFactoryInterface = ICampaignFactory(address(_campaignFactory)); campaignInterface = ICampaign(address(_campaign)); campaign = _campaign; campaignRewardAddress = address(this); emit CampaignRewardOwnerSet(msg.sender); } /** * @dev Creates rewards contributors can attain * @param _value Reward cost * @param _deliveryDate Time in which reward will be deliverd to contriutors * @param _stock Quantity available for dispatch * @param _hashedReward CID reference of the reward on IPFS * @param _active Indicates if contributors can attain the reward */ function createReward( uint256 _value, uint256 _deliveryDate, uint256 _stock, string memory _hashedReward, bool _active ) external hasRole(CREATE_REWARD, msg.sender) userIsVerified(msg.sender) { require( _value > CampaignFactoryLib.getCampaignFactoryConfig( campaignFactoryInterface, "minimumContributionAllowed" ), "amount too low" ); require( _value < CampaignFactoryLib.getCampaignFactoryConfig( campaignFactoryInterface, "maximumContributionAllowed" ), "amount too high" ); rewards.push( Reward(_value, _deliveryDate, _stock, _hashedReward, true, _active) ); emit RewardCreated( rewards.length.sub(1), _value, _deliveryDate, _stock, _hashedReward, _active ); } /** * @dev Assigns a reward to a user after payment from parent contract Campaign * @param _rewardId ID of the reward being assigned * @param _amount Amount being paid by the user * @param _user Address of user reward is being assigned to */ function assignReward( uint256 _rewardId, uint256 _amount, address _user ) external onlyRegisteredCampaigns userIsVerified(_user) returns (uint256) { require(_amount >= rewards[_rewardId].value, "amount too low"); require(rewards[_rewardId].stock >= 1, "out of stock"); require(rewards[_rewardId].exists, "not found"); require(rewards[_rewardId].active, "not active"); rewardRecipients.push(RewardRecipient(_rewardId, _user, false, false)); userRewardCount[_user] = userRewardCount[_user].add(1); rewardToRewardRecipientCount[_rewardId] = rewardToRewardRecipientCount[ _rewardId ].add(1); emit RewardRecipientAdded( rewardRecipients.length.sub(1), _rewardId, _amount, _user ); return rewardRecipients.length.sub(1); } /** * @dev Modifies a reward by id * @param _rewardId Reward unique id * @param _value Reward cost * @param _deliveryDate Time in which reward will be deliverd to contriutors * @param _stock Quantity available for dispatch * @param _active Indicates if contributors can attain the reward * @param _hashedReward Initial or new CID refrence of the reward on IPFS */ function modifyReward( uint256 _rewardId, uint256 _value, uint256 _deliveryDate, uint256 _stock, bool _active, string memory _hashedReward ) external hasRole(MODIFY_REWARD, msg.sender) { /** * To modify a reward: * check reward has no backers * check reward exists */ require(rewards[_rewardId].exists, "not found"); require(rewardToRewardRecipientCount[_rewardId] < 1, "has backers"); require( _value > CampaignFactoryLib.getCampaignFactoryConfig( campaignFactoryInterface, "minimumContributionAllowed" ), "amount too low" ); require( _value < CampaignFactoryLib.getCampaignFactoryConfig( campaignFactoryInterface, "maximumContributionAllowed" ), "amount too high" ); rewards[_rewardId].value = _value; rewards[_rewardId].deliveryDate = _deliveryDate; rewards[_rewardId].stock = _stock; rewards[_rewardId].active = _active; rewards[_rewardId].hashedReward = _hashedReward; emit RewardModified(_rewardId, _value, _deliveryDate, _stock, _active); } /** * @dev Increases a reward stock count * @param _rewardId Reward unique id * @param _count Stock count to increase by */ function increaseRewardStock(uint256 _rewardId, uint256 _count) external hasRole(MODIFY_REWARD, msg.sender) { require(rewards[_rewardId].exists, "not found"); rewards[_rewardId].stock = rewards[_rewardId].stock.add(_count); emit RewardStockIncreased(_rewardId, _count); } /** * @dev Deletes a reward by id * @param _rewardId Reward unique id */ function destroyReward(uint256 _rewardId) external hasRole(DESTROY_REWARD, msg.sender) { // check reward has no backers require(rewardToRewardRecipientCount[_rewardId] < 1, "has backers"); require(rewards[_rewardId].exists, "not found"); delete rewards[_rewardId]; emit RewardDestroyed(_rewardId); } /** * @dev Called by the campaign owner to indicate they delivered the reward to the rewardRecipient * @param _rewardRecipientId ID to struct containing reward and user to be rewarded * @param _status Indicates if the delivery was successful or not */ function campaignSentReward(uint256 _rewardRecipientId, bool _status) external hasRole(MODIFY_REWARD, msg.sender) { require( rewardToRewardRecipientCount[ rewardRecipients[_rewardRecipientId].rewardId ] >= 1 ); rewardRecipients[_rewardRecipientId] .deliveryConfirmedByCampaign = _status; emit RewarderApproval(_rewardRecipientId, _status); } /** * @dev Called by a user eligible for rewards to indicate they received their reward * @param _rewardRecipientId ID to struct containing reward and user to be rewarded */ function userReceivedCampaignReward(uint256 _rewardRecipientId) external userIsVerified(msg.sender) { require( CampaignLib.isAnApprover(campaignInterface, msg.sender), "not an approver" ); require( rewardRecipients[_rewardRecipientId].deliveryConfirmedByCampaign, "reward not delivered yet" ); require( !rewardRecipients[_rewardRecipientId].deliveryConfirmedByUser, "reward already marked as sent" ); require( rewardRecipients[_rewardRecipientId].user == msg.sender, "not owner of reward" ); require(userRewardCount[msg.sender] >= 1, "you have no reward"); rewardRecipients[_rewardRecipientId].deliveryConfirmedByUser = true; emit RewardRecipientApproval(_rewardRecipientId); } /** * @dev Renounces rewards owned by the specified user * @param _user Address of user who rewards are being renounced */ function renounceRewards(address _user) external onlyRegisteredCampaigns { if (userRewardCount[_user] >= 1) { userRewardCount[_user] = 0; // deduct rewardRecipients count for (uint256 index = 0; index < rewardRecipients.length; index++) { rewardToRewardRecipientCount[ rewardRecipients[index].rewardId ] = rewardToRewardRecipientCount[ rewardRecipients[index].rewardId ].sub(1); } } } /** * @dev Transfers rewards from the old owner to a new owner * @param _oldAddress Address of previous owner of rewards * @param _newAddress Address of new owner rewards are being transferred to */ function transferRewards(address _oldAddress, address _newAddress) external onlyRegisteredCampaigns { if (userRewardCount[_oldAddress] >= 1) { userRewardCount[_newAddress] = userRewardCount[_oldAddress]; userRewardCount[_oldAddress] = 0; for (uint256 index = 0; index < rewardRecipients.length; index++) { if (rewardRecipients[index].user == _oldAddress) { rewardRecipients[index].user = _newAddress; } } } } }
Increases a reward stock count _rewardId Reward unique id _count Stock count to increase by/
function increaseRewardStock(uint256 _rewardId, uint256 _count) external hasRole(MODIFY_REWARD, msg.sender) { require(rewards[_rewardId].exists, "not found"); rewards[_rewardId].stock = rewards[_rewardId].stock.add(_count); emit RewardStockIncreased(_rewardId, _count); }
5,539,153
/* Copyright 2021 Set Labs 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. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; /** * @title RgtMigrationWrapAdater * @author FlattestWhite * * Wrap adapter for one time token migration that returns data for wrapping RGT into TRIBE. * Note: RGT can not be unwrapped into TRIBE, because migration can not be reversed. */ contract RgtMigrationWrapAdapter { /* ============ State Variables ============ */ address public immutable pegExchanger; /* ============ Constructor ============ */ /** * Set state variables * * @param _pegExchanger Address of PegExchanger contract */ constructor( address _pegExchanger ) public { pegExchanger = _pegExchanger; } /* ============ External Getter Functions ============ */ /** * Generates the calldata to migrate RGT tokens to TRIBE tokens. * * @param _underlyingUnits Total quantity of underlying units to wrap * * @return address Target contract address * @return uint256 Total quantity of underlying units (if underlying is ETH) * @return bytes Wrap calldata */ function getWrapCallData( address /* _underlyingToken */, address /* _wrappedToken */, uint256 _underlyingUnits ) external view returns (address, uint256, bytes memory) { // exchange(uint256 amount) bytes memory callData = abi.encodeWithSignature("exchange(uint256)", _underlyingUnits); return (pegExchanger, 0, callData); } /** * This function will revert, since migration cannot be reversed. */ function getUnwrapCallData( address /* _underlyingToken */, address /* _wrappedToken */, uint256 /* _wrappedTokenUnits */ ) external pure returns (address, uint256, bytes memory) { revert("RGT migration cannot be reversed"); } /** * Returns the address to approve source tokens for wrapping. * * @return address Address of the contract to approve tokens to */ function getSpenderAddress(address /* _underlyingToken */, address /* _wrappedToken */) external view returns(address) { return pegExchanger; } }
Generates the calldata to migrate RGT tokens to TRIBE tokens. _underlyingUnits Total quantity of underlying units to wrap return address Target contract address return uint256 Total quantity of underlying units (if underlying is ETH) return bytes Wrap calldata/ exchange(uint256 amount)
function getWrapCallData( address /* _underlyingToken */, address /* _wrappedToken */, uint256 _underlyingUnits ) external view returns (address, uint256, bytes memory) { bytes memory callData = abi.encodeWithSignature("exchange(uint256)", _underlyingUnits); return (pegExchanger, 0, callData); }
2,076,158
pragma solidity ^0.5.2; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on 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-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } pragma solidity 0.5.16; import './SafeMath.sol'; /// @title Fund Bucket of TimeAlly Personal EraSwap Teller /// @author The EraSwap Team /// @notice The returns for PET Smart Contract are transparently stored in advance in this contract contract FundsBucketPET { /// @notice address of the maintainer address public deployer; /// @notice address of Era Swap ERC20 Smart Contract ERC20 public token; /// @notice address of PET Smart Contract address public petContract; /// @notice event schema for monitoring funds added by donors event FundsDeposited( address _depositer, uint256 _depositAmount ); /// @notice event schema for monitoring unallocated fund withdrawn by deployer event FundsWithdrawn( address _withdrawer, uint256 _withdrawAmount ); /// @notice restricting access to some functionalities to deployer modifier onlyDeployer() { require(msg.sender == deployer, 'only deployer can call'); _; } /// @notice this function is used to deploy FundsBucket Smart Contract /// the same time while deploying PET Smart Contract /// @dev this smart contract is deployed by PET Smart Contract while being set up /// @param _token: is EraSwap ERC20 Smart Contract Address /// @param _deployer: is address of the deployer of PET Smart Contract constructor(ERC20 _token, address _deployer) public { token = _token; deployer = _deployer; petContract = msg.sender; } /// @notice this function is used by well wishers to add funds to the fund bucket of PET /// @dev ERC20 approve is required to be done for this contract earlier /// @param _depositAmount: amount in exaES to deposit function addFunds(uint256 _depositAmount) public { token.transferFrom(msg.sender, address(this), _depositAmount); /// @dev approving the PET Smart Contract in advance token.approve(petContract, _depositAmount); emit FundsDeposited(msg.sender, _depositAmount); } /// @notice this function makes it possible for deployer to withdraw unallocated ES function withdrawFunds(bool _withdrawEverything, uint256 _withdrawlAmount) public onlyDeployer { if(_withdrawEverything) { _withdrawlAmount = token.balanceOf(address(this)); } token.transfer(msg.sender, _withdrawlAmount); emit FundsWithdrawn(msg.sender, _withdrawlAmount); } } /// @title TimeAlly Personal EraSwap Teller Smart Contract /// @author The EraSwap Team /// @notice Stakes EraSwap tokens with staker contract TimeAllyPET { using SafeMath for uint256; /// @notice data structure of a PET Plan struct PETPlan { bool isPlanActive; uint256 minimumMonthlyCommitmentAmount; uint256 monthlyBenefitFactorPerThousand; } /// @notice data structure of a PET Plan struct PET { uint256 planId; uint256 monthlyCommitmentAmount; uint256 initTimestamp; uint256 lastAnnuityWithdrawlMonthId; uint256 appointeeVotes; uint256 numberOfAppointees; mapping(uint256 => uint256) monthlyDepositAmount; mapping(uint256 => bool) isPowerBoosterWithdrawn; mapping(address => bool) nominees; mapping(address => bool) appointees; } /// @notice address storage of the deployer address public deployer; /// @notice address storage of fundsBucket from which tokens to be pulled for giving benefits address public fundsBucket; /// @notice address storage of Era Swap Token ERC20 Smart Contract ERC20 public token; /// @dev selected for taking care of leap years such that 1 Year = 365.242 days holds uint256 constant EARTH_SECONDS_IN_MONTH = 2629744; /// @notice storage for multiple PET plans PETPlan[] public petPlans; /// @notice storage for PETs deployed by stakers mapping(address => PET[]) public pets; /// @notice storage for prepaid Era Swaps available for any wallet address mapping(address => uint256) public prepaidES; /// @notice event schema for monitoring new pet plans event NewPETPlan ( uint256 _minimumMonthlyCommitmentAmount, uint256 _monthlyBenefitFactorPerThousand, uint256 _petPlanId ); /// @notice event schema for monitoring new pets by stakers event NewPET ( address indexed _staker, uint256 _petId, uint256 _monthlyCommitmentAmount ); /// @notice event schema for monitoring deposits made by stakers to their pets event NewDeposit ( address indexed _staker, uint256 indexed _petId, uint256 _monthId, uint256 _depositAmount, // uint256 _benefitAllocated, address _depositedBy, bool _usingPrepaidES ); /// @notice event schema for monitoring pet annuity withdrawn by stakers event AnnuityWithdrawl ( address indexed _staker, uint256 indexed _petId, uint256 _fromMonthId, uint256 _toMonthId, uint256 _withdrawlAmount, address _withdrawnBy ); /// @notice event schema for monitoring power booster withdrawn by stakers event PowerBoosterWithdrawl ( address indexed _staker, uint256 indexed _petId, uint256 _powerBoosterId, uint256 _withdrawlAmount, address _withdrawnBy ); /// @notice event schema for monitoring penalised power booster burning event BoosterBurn ( address _staker, uint256 _petId, uint256 _burningAmount ); /// @notice event schema for monitoring power booster withdrawn by stakers event NomineeUpdated ( address indexed _staker, uint256 indexed _petId, address indexed _nomineeAddress, bool _nomineeStatus ); /// @notice event schema for monitoring power booster withdrawls by stakers event AppointeeUpdated ( address indexed _staker, uint256 indexed _petId, address indexed _appointeeAddress, bool _appointeeStatus ); /// @notice event schema for monitoring power booster withdrawls by stakers event AppointeeVoted ( address indexed _staker, uint256 indexed _petId, address indexed _appointeeAddress ); /// @notice restricting access to some functionalities to deployer modifier onlyDeployer() { require(msg.sender == deployer, 'only deployer can call'); _; } /// @notice restricting access of staker's PET to them and their pet nominees modifier meOrNominee(address _stakerAddress, uint256 _petId) { PET storage _pet = pets[_stakerAddress][_petId]; /// @notice if transacter is not staker, then transacter should be nominee if(msg.sender != _stakerAddress) { require(_pet.nominees[msg.sender], 'nomination should be there'); } _; } /// @notice sets up TimeAllyPET contract when deployed and also deploys FundsBucket /// @param _token: is EraSwap ERC20 Smart Contract Address constructor(ERC20 _token) public { deployer = msg.sender; token = _token; fundsBucket = address(new FundsBucketPET(_token, msg.sender)); } /// @notice this function is used to add ES as prepaid for PET /// @dev ERC20 approve needs to be done /// @param _amount: ES to deposit function addToPrepaid(uint256 _amount) public { /// @notice transfering the tokens from user token.transferFrom(msg.sender, address(this), _amount); /// @notice then adding tokens to prepaidES prepaidES[msg.sender] = prepaidES[msg.sender].add(_amount); } /// @notice this function is used to send ES as prepaid for PET /// @dev some ES already in prepaid required /// @param _addresses: address array to send prepaid ES for PET /// @param _amounts: prepaid ES for PET amounts to send to corresponding addresses function sendPrepaidESDifferent( address[] memory _addresses, uint256[] memory _amounts ) public { for(uint256 i = 0; i < _addresses.length; i++) { /// @notice subtracting amount from sender prepaidES prepaidES[msg.sender] = prepaidES[msg.sender].sub(_amounts[i]); /// @notice then incrementing the amount into receiver's prepaidES prepaidES[_addresses[i]] = prepaidES[_addresses[i]].add(_amounts[i]); } } /// @notice this function is used by anyone to create a new PET /// @param _planId: id of PET in staker portfolio /// @param _monthlyCommitmentAmount: PET monthly commitment amount in exaES function newPET( uint256 _planId, uint256 _monthlyCommitmentAmount ) public { /// @notice enforcing that the plan should be active require( petPlans[_planId].isPlanActive , 'PET plan is not active' ); /// @notice enforcing that monthly commitment by the staker should be more than /// minimum monthly commitment in the selected plan require( _monthlyCommitmentAmount >= petPlans[_planId].minimumMonthlyCommitmentAmount , 'low monthlyCommitmentAmount' ); /// @notice adding the PET to staker's pets storage pets[msg.sender].push(PET({ planId: _planId, monthlyCommitmentAmount: _monthlyCommitmentAmount, initTimestamp: now, lastAnnuityWithdrawlMonthId: 0, appointeeVotes: 0, numberOfAppointees: 0 })); /// @notice emiting an event emit NewPET( msg.sender, pets[msg.sender].length - 1, _monthlyCommitmentAmount ); } /// @notice this function is used by deployer to create plans for new PETs /// @param _minimumMonthlyCommitmentAmount: minimum PET monthly amount in exaES /// @param _monthlyBenefitFactorPerThousand: this is per 1000; i.e 200 for 20% function createPETPlan( uint256 _minimumMonthlyCommitmentAmount, uint256 _monthlyBenefitFactorPerThousand ) public onlyDeployer { /// @notice adding the petPlan to storage petPlans.push(PETPlan({ isPlanActive: true, minimumMonthlyCommitmentAmount: _minimumMonthlyCommitmentAmount, monthlyBenefitFactorPerThousand: _monthlyBenefitFactorPerThousand })); /// @notice emitting an event emit NewPETPlan( _minimumMonthlyCommitmentAmount, _monthlyBenefitFactorPerThousand, petPlans.length - 1 ); } /// @notice this function is used by deployer to disable or re-enable a pet plan /// @dev pets already initiated by a plan will continue only new will be restricted /// @param _planId: select a plan to make it inactive /// @param _newStatus: true or false. function updatePlanStatus(uint256 _planId, bool _newStatus) public onlyDeployer { petPlans[_planId].isPlanActive = _newStatus; } /// @notice this function is used to update nominee status of a wallet address in PET /// @param _petId: id of PET in staker portfolio. /// @param _nomineeAddress: eth wallet address of nominee. /// @param _newNomineeStatus: true or false, whether this should be a nominee or not. function toogleNominee( uint256 _petId, address _nomineeAddress, bool _newNomineeStatus ) public { /// @notice updating nominee status pets[msg.sender][_petId].nominees[_nomineeAddress] = _newNomineeStatus; /// @notice emiting event for UI and other applications emit NomineeUpdated(msg.sender, _petId, _nomineeAddress, _newNomineeStatus); } /// @notice this function is used to update appointee status of a wallet address in PET /// @param _petId: id of PET in staker portfolio. /// @param _appointeeAddress: eth wallet address of appointee. /// @param _newAppointeeStatus: true or false, should this have appointee rights or not. function toogleAppointee( uint256 _petId, address _appointeeAddress, bool _newAppointeeStatus ) public { PET storage _pet = pets[msg.sender][_petId]; /// @notice if not an appointee already and _newAppointeeStatus is true, adding appointee if(!_pet.appointees[_appointeeAddress] && _newAppointeeStatus) { _pet.numberOfAppointees = _pet.numberOfAppointees.add(1); _pet.appointees[_appointeeAddress] = true; } /// @notice if already an appointee and _newAppointeeStatus is false, removing appointee else if(_pet.appointees[_appointeeAddress] && !_newAppointeeStatus) { _pet.appointees[_appointeeAddress] = false; _pet.numberOfAppointees = _pet.numberOfAppointees.sub(1); } emit AppointeeUpdated(msg.sender, _petId, _appointeeAddress, _newAppointeeStatus); } /// @notice this function is used by appointee to vote that nominees can withdraw early /// @dev need to be appointee, set by staker themselves /// @param _stakerAddress: address of initiater of this PET. /// @param _petId: id of PET in staker portfolio. function appointeeVote( address _stakerAddress, uint256 _petId ) public { PET storage _pet = pets[_stakerAddress][_petId]; /// @notice checking if appointee has rights to cast a vote require(_pet.appointees[msg.sender] , 'should be appointee to cast vote' ); /// @notice removing appointee's rights to vote again _pet.appointees[msg.sender] = false; /// @notice adding a vote to PET _pet.appointeeVotes = _pet.appointeeVotes.add(1); /// @notice emit that appointee has voted emit AppointeeVoted(_stakerAddress, _petId, msg.sender); } /// @notice this function is used by stakers to make deposits to their PETs /// @dev ERC20 approve is required to be done for this contract earlier if prepaidES /// is not selected, enough funds must be there in the funds bucket contract /// and also deposit can be done by nominee /// @param _stakerAddress: address of staker who has a PET /// @param _petId: id of PET in staker address portfolio /// @param _depositAmount: amount to deposit /// @param _usePrepaidES: should prepaidES be used function makeDeposit( address _stakerAddress, uint256 _petId, uint256 _depositAmount, bool _usePrepaidES ) public meOrNominee(_stakerAddress, _petId) { /// @notice check if non zero deposit require(_depositAmount > 0, 'deposit amount should be non zero'); /// @notice get the storage reference of staker's PET PET storage _pet = pets[_stakerAddress][_petId]; /// @notice calculate the deposit month based on time uint256 _depositMonth = getDepositMonth(_stakerAddress, _petId); /// @notice enforce no deposits after 12 months require(_depositMonth <= 12, 'cannot deposit after accumulation period'); if(_usePrepaidES) { /// @notice subtracting prepaidES from staker prepaidES[msg.sender] = prepaidES[msg.sender].sub(_depositAmount); } else { /// @notice transfering staker tokens to PET contract token.transferFrom(msg.sender, address(this), _depositAmount); } /// @notice calculate new deposit amount for the storage uint256 _updatedDepositAmount = _pet.monthlyDepositAmount[_depositMonth].add(_depositAmount); /// @notice carryforward small deposits in previous months uint256 _previousMonth = _depositMonth - 1; while(_previousMonth > 0) { if(0 < _pet.monthlyDepositAmount[_previousMonth] && _pet.monthlyDepositAmount[_previousMonth] < _pet.monthlyCommitmentAmount.div(2)) { _updatedDepositAmount = _updatedDepositAmount.add( _pet.monthlyDepositAmount[_previousMonth] ); _pet.monthlyDepositAmount[_previousMonth] = 0; } _previousMonth -= 1; } /// @notice calculate old allocation, to adjust it in new allocation uint256 _oldBenefitAllocation = _getBenefitAllocationByDepositAmount( _pet, 0, _depositMonth ); uint256 _extraBenefitAllocation = _getBenefitAllocationByDepositAmount( _pet, _updatedDepositAmount, _depositMonth ).sub(_oldBenefitAllocation); /// @notice pull funds from funds bucket token.transferFrom(fundsBucket, address(this), _extraBenefitAllocation); /// @notice recording the deposit by updating the value _pet.monthlyDepositAmount[_depositMonth] = _updatedDepositAmount; /// @notice emitting an event emit NewDeposit( _stakerAddress, _petId, _depositMonth, _depositAmount, // _extraBenefitAllocation, msg.sender, _usePrepaidES ); } /// @notice this function is used by stakers to make lum sum deposit /// @dev lum sum deposit is possible in the first month in a fresh PET /// @param _stakerAddress: address of staker who has a PET /// @param _petId: id of PET in staker address portfolio /// @param _totalDepositAmount: total amount to deposit for 12 months /// @param _frequencyMode: can be 3, 6 or 12 /// @param _usePrepaidES: should prepaidES be used // deposit frequency mode function makeFrequencyModeDeposit( address _stakerAddress, uint256 _petId, uint256 _totalDepositAmount, uint256 _frequencyMode, bool _usePrepaidES ) public { uint256 _fees; /// @dev using ether because ES also has 18 decimals like ETH if(_frequencyMode == 3) _fees = _totalDepositAmount.mul(1).div(100); else if(_frequencyMode == 6) _fees = _totalDepositAmount.mul(2).div(100); else if(_frequencyMode == 12) _fees = _totalDepositAmount.mul(3).div(100); else require(false, 'unsupported frequency'); /// @notice check if non zero deposit require(_totalDepositAmount > 0, 'deposit amount should be non zero'); /// @notice get the reference of staker's PET PET storage _pet = pets[_stakerAddress][_petId]; /// @notice calculate deposit month based on time and enforce first month uint256 _depositMonth = getDepositMonth(_stakerAddress, _petId); // require(_depositMonth == 1, 'allowed only in first month'); uint256 _uptoMonth = _depositMonth.add(_frequencyMode).sub(1); require(_uptoMonth <= 12, 'cannot deposit after accumulation period'); /// @notice enforce only fresh pets require(_pet.monthlyDepositAmount[_depositMonth] == 0, 'allowed only in fresh month deposit'); /// @notice calculate monthly deposit amount uint256 _monthlyDepositAmount = _totalDepositAmount.div(_frequencyMode); /// @notice check if single monthly deposit amount is at least commitment require( _monthlyDepositAmount >= _pet.monthlyCommitmentAmount , 'deposit not crossing commitment' ); /// @notice calculate benefit for a single month uint256 _benefitAllocationForSingleMonth = _getBenefitAllocationByDepositAmount( _pet, _monthlyDepositAmount, 1 ); if(_usePrepaidES) { /// @notice subtracting prepaidES from staker prepaidES[msg.sender] = prepaidES[msg.sender].sub(_totalDepositAmount.add(_fees)); } else { /// @notice transfering staker tokens to PET contract token.transferFrom(msg.sender, address(this), _totalDepositAmount.add(_fees)); } prepaidES[deployer] = prepaidES[deployer].add(_fees); // token.transfer(deployer, _fees); /// @notice pull funds from funds bucket token.transferFrom(fundsBucket, address(this), _benefitAllocationForSingleMonth.mul(_frequencyMode)); for(uint256 _monthId = _depositMonth; _monthId <= _uptoMonth; _monthId++) { /// @notice mark deposits in all the months _pet.monthlyDepositAmount[_monthId] = _monthlyDepositAmount; /// @notice emit events emit NewDeposit( _stakerAddress, _petId, _monthId, _monthlyDepositAmount, // _benefitAllocationForSingleMonth, msg.sender, _usePrepaidES ); } } /// @notice this function is used to withdraw annuity benefits /// @param _stakerAddress: address of staker who has a PET /// @param _petId: id of PET in staker address portfolio /// @param _endAnnuityMonthId: this is the month upto which benefits to be withdrawn function withdrawAnnuity( address _stakerAddress, uint256 _petId, uint256 _endAnnuityMonthId ) public meOrNominee(_stakerAddress, _petId) { PET storage _pet = pets[_stakerAddress][_petId]; uint256 _lastAnnuityWithdrawlMonthId = _pet.lastAnnuityWithdrawlMonthId; /// @notice enforcing withdrawls only once require( _lastAnnuityWithdrawlMonthId < _endAnnuityMonthId , 'start should be before end' ); /// @notice enforcing only 60 withdrawls require( _endAnnuityMonthId <= 60 , 'only 60 Annuity withdrawls' ); /// @notice calculating allowed timestamp uint256 _allowedTimestamp = getNomineeAllowedTimestamp( _stakerAddress, _petId, _endAnnuityMonthId ); /// @notice enforcing withdrawls only after allowed timestamp require( now >= _allowedTimestamp , 'cannot withdraw early' ); /// @notice calculating sum of annuity of the months uint256 _annuityBenefit = getSumOfMonthlyAnnuity( _stakerAddress, _petId, _lastAnnuityWithdrawlMonthId+1, _endAnnuityMonthId ); /// @notice updating last withdrawl month _pet.lastAnnuityWithdrawlMonthId = _endAnnuityMonthId; /// @notice burning penalised power booster tokens in the first annuity withdrawl if(_lastAnnuityWithdrawlMonthId == 0) { _burnPenalisedPowerBoosterTokens(_stakerAddress, _petId); } /// @notice transfering the annuity to withdrawer (staker or nominee) if(_annuityBenefit != 0) { token.transfer(msg.sender, _annuityBenefit); } // @notice emitting an event emit AnnuityWithdrawl( _stakerAddress, _petId, _lastAnnuityWithdrawlMonthId+1, _endAnnuityMonthId, _annuityBenefit, msg.sender ); } /// @notice this function is used by staker to withdraw power booster /// @param _stakerAddress: address of staker who has a PET /// @param _petId: id of PET in staker address portfolio /// @param _powerBoosterId: this is serial of power booster function withdrawPowerBooster( address _stakerAddress, uint256 _petId, uint256 _powerBoosterId ) public meOrNominee(_stakerAddress, _petId) { PET storage _pet = pets[_stakerAddress][_petId]; /// @notice enforcing 12 power booster withdrawls require( 1 <= _powerBoosterId && _powerBoosterId <= 12 , 'id should be in range' ); /// @notice enforcing power booster withdrawl once require( !_pet.isPowerBoosterWithdrawn[_powerBoosterId] , 'booster already withdrawn' ); /// @notice enforcing target to be acheived require( _pet.monthlyDepositAmount[13 - _powerBoosterId] >= _pet.monthlyCommitmentAmount , 'target not achieved' ); /// @notice calculating allowed timestamp based on time and nominee uint256 _allowedTimestamp = getNomineeAllowedTimestamp( _stakerAddress, _petId, _powerBoosterId*5+1 ); /// @notice enforcing withdrawl after _allowedTimestamp require( now >= _allowedTimestamp , 'cannot withdraw early' ); /// @notice calculating power booster amount uint256 _powerBoosterAmount = calculatePowerBoosterAmount(_stakerAddress, _petId); /// @notice marking power booster as withdrawn _pet.isPowerBoosterWithdrawn[_powerBoosterId] = true; if(_powerBoosterAmount > 0) { /// @notice sending the power booster amount to withdrawer (staker or nominee) token.transfer(msg.sender, _powerBoosterAmount); } /// @notice emitting an event emit PowerBoosterWithdrawl( _stakerAddress, _petId, _powerBoosterId, _powerBoosterAmount, msg.sender ); } /// @notice this function is used to view nomination /// @param _stakerAddress: address of initiater of this PET. /// @param _petId: id of PET in staker portfolio. /// @param _nomineeAddress: eth wallet address of nominee. /// @return tells whether this address is a nominee or not function viewNomination( address _stakerAddress, uint256 _petId, address _nomineeAddress ) public view returns (bool) { return pets[_stakerAddress][_petId].nominees[_nomineeAddress]; } /// @notice this function is used to view appointation /// @param _stakerAddress: address of initiater of this PET. /// @param _petId: id of PET in staker portfolio. /// @param _appointeeAddress: eth wallet address of apointee. /// @return tells whether this address is a appointee or not function viewAppointation( address _stakerAddress, uint256 _petId, address _appointeeAddress ) public view returns (bool) { return pets[_stakerAddress][_petId].appointees[_appointeeAddress]; } /// @notice this function is used by contract to get nominee's allowed timestamp /// @param _stakerAddress: address of staker who has a PET /// @param _petId: id of PET in staker address portfolio /// @param _annuityMonthId: this is the month for which timestamp to find /// @return nominee allowed timestamp function getNomineeAllowedTimestamp( address _stakerAddress, uint256 _petId, uint256 _annuityMonthId ) public view returns (uint256) { PET storage _pet = pets[_stakerAddress][_petId]; uint256 _allowedTimestamp = _pet.initTimestamp + (12 + _annuityMonthId - 1) * EARTH_SECONDS_IN_MONTH; /// @notice if tranasction sender is not the staker, then more delay to _allowedTimestamp if(msg.sender != _stakerAddress) { if(_pet.appointeeVotes > _pet.numberOfAppointees.div(2)) { _allowedTimestamp += EARTH_SECONDS_IN_MONTH * 6; } else { _allowedTimestamp += EARTH_SECONDS_IN_MONTH * 12; } } return _allowedTimestamp; } /// @notice this function is used to retrive monthly deposit in a PET /// @param _stakerAddress: address of staker who has PET /// @param _petId: id of PET in staket address portfolio /// @param _monthId: specify the month to deposit /// @return deposit in a particular month function getMonthlyDepositedAmount( address _stakerAddress, uint256 _petId, uint256 _monthId ) public view returns (uint256) { return pets[_stakerAddress][_petId].monthlyDepositAmount[_monthId]; } /// @notice this function is used to get the current month of a PET /// @param _stakerAddress: address of staker who has PET /// @param _petId: id of PET in staket address portfolio /// @return current month of a particular PET function getDepositMonth( address _stakerAddress, uint256 _petId ) public view returns (uint256) { return (now - pets[_stakerAddress][_petId].initTimestamp)/EARTH_SECONDS_IN_MONTH + 1; } /// @notice this function is used to get total annuity benefits between two months /// @param _stakerAddress: address of staker who has a PET /// @param _petId: id of PET in staker address portfolio /// @param _startAnnuityMonthId: this is the month (inclusive) to start from /// @param _endAnnuityMonthId: this is the month (inclusive) to stop at function getSumOfMonthlyAnnuity( address _stakerAddress, uint256 _petId, uint256 _startAnnuityMonthId, uint256 _endAnnuityMonthId ) public view returns (uint256) { /// @notice get the storage references of staker's PET and Plan PET storage _pet = pets[_stakerAddress][_petId]; PETPlan storage _petPlan = petPlans[_pet.planId]; uint256 _totalDeposits; /// @notice calculating both deposits for every month and adding it for(uint256 _i = _startAnnuityMonthId; _i <= _endAnnuityMonthId; _i++) { uint256 _modulo = _i%12; uint256 _depositAmountIncludingPET = _getTotalDepositedIncludingPET(_pet.monthlyDepositAmount[_modulo==0?12:_modulo], _pet.monthlyCommitmentAmount); _totalDeposits = _totalDeposits.add(_depositAmountIncludingPET); } /// @notice calculating annuity from total both deposits done return _totalDeposits.mul(_petPlan.monthlyBenefitFactorPerThousand).div(1000); } /// @notice calculating power booster amount /// @param _stakerAddress: address of staker who has PET /// @param _petId: id of PET in staket address portfolio /// @return single power booster amount function calculatePowerBoosterAmount( address _stakerAddress, uint256 _petId ) public view returns (uint256) { /// @notice get the storage reference of staker's PET PET storage _pet = pets[_stakerAddress][_petId]; uint256 _totalDepositedIncludingPET; /// @notice calculating total deposited by staker and pet in all 12 months for(uint256 _i = 1; _i <= 12; _i++) { uint256 _depositAmountIncludingPET = _getTotalDepositedIncludingPET( _pet.monthlyDepositAmount[_i], _pet.monthlyCommitmentAmount ); _totalDepositedIncludingPET = _totalDepositedIncludingPET.add(_depositAmountIncludingPET); } return _totalDepositedIncludingPET.div(12); } /// @notice this function is used internally to burn penalised booster tokens /// @param _stakerAddress: address of staker who has a PET /// @param _petId: id of PET in staker address portfolio function _burnPenalisedPowerBoosterTokens( address _stakerAddress, uint256 _petId ) private { /// @notice get the storage references of staker's PET PET storage _pet = pets[_stakerAddress][_petId]; uint256 _unachieveTargetCount; /// @notice calculating number of unacheived targets for(uint256 _i = 1; _i <= 12; _i++) { if(_pet.monthlyDepositAmount[_i] < _pet.monthlyCommitmentAmount) { _unachieveTargetCount++; } } uint256 _powerBoosterAmount = calculatePowerBoosterAmount(_stakerAddress, _petId); /// @notice burning the unacheived power boosters uint256 _burningAmount = _powerBoosterAmount.mul(_unachieveTargetCount); token.burn(_burningAmount); // @notice emitting an event emit BoosterBurn(_stakerAddress, _petId, _burningAmount); } /// @notice this function is used by contract to calculate benefit allocation when /// a staker makes a deposit /// @param _pet: this is a reference to staker's pet storage /// @param _depositAmount: this is amount deposited by staker /// @param _depositMonth: this is month at which deposit takes place /// @return benefit amount to be allocated due to the deposit function _getBenefitAllocationByDepositAmount( PET storage _pet, uint256 _depositAmount, uint256 _depositMonth ) private view returns (uint256) { uint256 _planId = _pet.planId; uint256 _amount = _depositAmount != 0 ? _depositAmount : _pet.monthlyDepositAmount[_depositMonth]; uint256 _monthlyCommitmentAmount = _pet.monthlyCommitmentAmount; PETPlan storage _petPlan = petPlans[_planId]; uint256 _petAmount; /// @notice if amount is above commitment then amount + commitment + amount / 2 if(_amount > _monthlyCommitmentAmount) { uint256 _topupAmount = _amount.sub(_monthlyCommitmentAmount); _petAmount = _monthlyCommitmentAmount.add(_topupAmount.div(2)); } /// @notice otherwise if amount is atleast half of commitment and at most commitment /// then take staker amount as the pet amount else if(_amount >= _monthlyCommitmentAmount.div(2)) { _petAmount = _amount; } /// @notice getting total deposit for the month including pet uint256 _depositAmountIncludingPET = _getTotalDepositedIncludingPET( _amount, _monthlyCommitmentAmount ); /// @dev starting with allocating power booster amount due to this deposit amount uint256 _benefitAllocation = _petAmount; /// @notice calculating the benefits in 5 years due to this deposit if(_amount >= _monthlyCommitmentAmount.div(2) || _depositMonth == 12) { _benefitAllocation = _benefitAllocation.add( _depositAmountIncludingPET.mul(_petPlan.monthlyBenefitFactorPerThousand).mul(5).div(1000) ); } return _benefitAllocation; } /// @notice this function is used by contract to get total deposited amount including PET /// @param _amount: amount of ES which is deposited /// @param _monthlyCommitmentAmount: commitment amount of staker /// @return staker plus pet deposit amount based on acheivement of commitment function _getTotalDepositedIncludingPET( uint256 _amount, uint256 _monthlyCommitmentAmount ) private pure returns (uint256) { uint256 _petAmount; /// @notice if there is topup then add half of topup to pet if(_amount > _monthlyCommitmentAmount) { uint256 _topupAmount = _amount.sub(_monthlyCommitmentAmount); _petAmount = _monthlyCommitmentAmount.add(_topupAmount.div(2)); } /// @notice otherwise if amount is atleast half of commitment and at most commitment /// then take staker amount as the pet amount else if(_amount >= _monthlyCommitmentAmount.div(2)) { _petAmount = _amount; } /// @notice finally sum staker amount and pet amount and return it return _amount.add(_petAmount); } } /// @dev For interface requirement contract ERC20 { function balanceOf(address tokenDeployer) public view returns (uint); function approve(address delegate, uint numTokens) public returns (bool); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function burn(uint256 value) public; function mou() public view returns (uint256); } pragma solidity ^0.5.2; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on 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-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } pragma solidity 0.5.16; import './SafeMath.sol'; /// @title Fund Bucket of TimeAlly Personal EraSwap Teller /// @author The EraSwap Team /// @notice The returns for PET Smart Contract are transparently stored in advance in this contract contract FundsBucketPET { /// @notice address of the maintainer address public deployer; /// @notice address of Era Swap ERC20 Smart Contract ERC20 public token; /// @notice address of PET Smart Contract address public petContract; /// @notice event schema for monitoring funds added by donors event FundsDeposited( address _depositer, uint256 _depositAmount ); /// @notice event schema for monitoring unallocated fund withdrawn by deployer event FundsWithdrawn( address _withdrawer, uint256 _withdrawAmount ); /// @notice restricting access to some functionalities to deployer modifier onlyDeployer() { require(msg.sender == deployer, 'only deployer can call'); _; } /// @notice this function is used to deploy FundsBucket Smart Contract /// the same time while deploying PET Smart Contract /// @dev this smart contract is deployed by PET Smart Contract while being set up /// @param _token: is EraSwap ERC20 Smart Contract Address /// @param _deployer: is address of the deployer of PET Smart Contract constructor(ERC20 _token, address _deployer) public { token = _token; deployer = _deployer; petContract = msg.sender; } /// @notice this function is used by well wishers to add funds to the fund bucket of PET /// @dev ERC20 approve is required to be done for this contract earlier /// @param _depositAmount: amount in exaES to deposit function addFunds(uint256 _depositAmount) public { token.transferFrom(msg.sender, address(this), _depositAmount); /// @dev approving the PET Smart Contract in advance token.approve(petContract, _depositAmount); emit FundsDeposited(msg.sender, _depositAmount); } /// @notice this function makes it possible for deployer to withdraw unallocated ES function withdrawFunds(bool _withdrawEverything, uint256 _withdrawlAmount) public onlyDeployer { if(_withdrawEverything) { _withdrawlAmount = token.balanceOf(address(this)); } token.transfer(msg.sender, _withdrawlAmount); emit FundsWithdrawn(msg.sender, _withdrawlAmount); } } /// @title TimeAlly Personal EraSwap Teller Smart Contract /// @author The EraSwap Team /// @notice Stakes EraSwap tokens with staker contract TimeAllyPET { using SafeMath for uint256; /// @notice data structure of a PET Plan struct PETPlan { bool isPlanActive; uint256 minimumMonthlyCommitmentAmount; uint256 monthlyBenefitFactorPerThousand; } /// @notice data structure of a PET Plan struct PET { uint256 planId; uint256 monthlyCommitmentAmount; uint256 initTimestamp; uint256 lastAnnuityWithdrawlMonthId; uint256 appointeeVotes; uint256 numberOfAppointees; mapping(uint256 => uint256) monthlyDepositAmount; mapping(uint256 => bool) isPowerBoosterWithdrawn; mapping(address => bool) nominees; mapping(address => bool) appointees; } /// @notice address storage of the deployer address public deployer; /// @notice address storage of fundsBucket from which tokens to be pulled for giving benefits address public fundsBucket; /// @notice address storage of Era Swap Token ERC20 Smart Contract ERC20 public token; /// @dev selected for taking care of leap years such that 1 Year = 365.242 days holds uint256 constant EARTH_SECONDS_IN_MONTH = 2629744; /// @notice storage for multiple PET plans PETPlan[] public petPlans; /// @notice storage for PETs deployed by stakers mapping(address => PET[]) public pets; /// @notice storage for prepaid Era Swaps available for any wallet address mapping(address => uint256) public prepaidES; /// @notice event schema for monitoring new pet plans event NewPETPlan ( uint256 _minimumMonthlyCommitmentAmount, uint256 _monthlyBenefitFactorPerThousand, uint256 _petPlanId ); /// @notice event schema for monitoring new pets by stakers event NewPET ( address indexed _staker, uint256 _petId, uint256 _monthlyCommitmentAmount ); /// @notice event schema for monitoring deposits made by stakers to their pets event NewDeposit ( address indexed _staker, uint256 indexed _petId, uint256 _monthId, uint256 _depositAmount, // uint256 _benefitAllocated, address _depositedBy, bool _usingPrepaidES ); /// @notice event schema for monitoring pet annuity withdrawn by stakers event AnnuityWithdrawl ( address indexed _staker, uint256 indexed _petId, uint256 _fromMonthId, uint256 _toMonthId, uint256 _withdrawlAmount, address _withdrawnBy ); /// @notice event schema for monitoring power booster withdrawn by stakers event PowerBoosterWithdrawl ( address indexed _staker, uint256 indexed _petId, uint256 _powerBoosterId, uint256 _withdrawlAmount, address _withdrawnBy ); /// @notice event schema for monitoring penalised power booster burning event BoosterBurn ( address _staker, uint256 _petId, uint256 _burningAmount ); /// @notice event schema for monitoring power booster withdrawn by stakers event NomineeUpdated ( address indexed _staker, uint256 indexed _petId, address indexed _nomineeAddress, bool _nomineeStatus ); /// @notice event schema for monitoring power booster withdrawls by stakers event AppointeeUpdated ( address indexed _staker, uint256 indexed _petId, address indexed _appointeeAddress, bool _appointeeStatus ); /// @notice event schema for monitoring power booster withdrawls by stakers event AppointeeVoted ( address indexed _staker, uint256 indexed _petId, address indexed _appointeeAddress ); /// @notice restricting access to some functionalities to deployer modifier onlyDeployer() { require(msg.sender == deployer, 'only deployer can call'); _; } /// @notice restricting access of staker's PET to them and their pet nominees modifier meOrNominee(address _stakerAddress, uint256 _petId) { PET storage _pet = pets[_stakerAddress][_petId]; /// @notice if transacter is not staker, then transacter should be nominee if(msg.sender != _stakerAddress) { require(_pet.nominees[msg.sender], 'nomination should be there'); } _; } /// @notice sets up TimeAllyPET contract when deployed and also deploys FundsBucket /// @param _token: is EraSwap ERC20 Smart Contract Address constructor(ERC20 _token) public { deployer = msg.sender; token = _token; fundsBucket = address(new FundsBucketPET(_token, msg.sender)); } /// @notice this function is used to add ES as prepaid for PET /// @dev ERC20 approve needs to be done /// @param _amount: ES to deposit function addToPrepaid(uint256 _amount) public { /// @notice transfering the tokens from user token.transferFrom(msg.sender, address(this), _amount); /// @notice then adding tokens to prepaidES prepaidES[msg.sender] = prepaidES[msg.sender].add(_amount); } /// @notice this function is used to send ES as prepaid for PET /// @dev some ES already in prepaid required /// @param _addresses: address array to send prepaid ES for PET /// @param _amounts: prepaid ES for PET amounts to send to corresponding addresses function sendPrepaidESDifferent( address[] memory _addresses, uint256[] memory _amounts ) public { for(uint256 i = 0; i < _addresses.length; i++) { /// @notice subtracting amount from sender prepaidES prepaidES[msg.sender] = prepaidES[msg.sender].sub(_amounts[i]); /// @notice then incrementing the amount into receiver's prepaidES prepaidES[_addresses[i]] = prepaidES[_addresses[i]].add(_amounts[i]); } } /// @notice this function is used by anyone to create a new PET /// @param _planId: id of PET in staker portfolio /// @param _monthlyCommitmentAmount: PET monthly commitment amount in exaES function newPET( uint256 _planId, uint256 _monthlyCommitmentAmount ) public { /// @notice enforcing that the plan should be active require( petPlans[_planId].isPlanActive , 'PET plan is not active' ); /// @notice enforcing that monthly commitment by the staker should be more than /// minimum monthly commitment in the selected plan require( _monthlyCommitmentAmount >= petPlans[_planId].minimumMonthlyCommitmentAmount , 'low monthlyCommitmentAmount' ); /// @notice adding the PET to staker's pets storage pets[msg.sender].push(PET({ planId: _planId, monthlyCommitmentAmount: _monthlyCommitmentAmount, initTimestamp: now, lastAnnuityWithdrawlMonthId: 0, appointeeVotes: 0, numberOfAppointees: 0 })); /// @notice emiting an event emit NewPET( msg.sender, pets[msg.sender].length - 1, _monthlyCommitmentAmount ); } /// @notice this function is used by deployer to create plans for new PETs /// @param _minimumMonthlyCommitmentAmount: minimum PET monthly amount in exaES /// @param _monthlyBenefitFactorPerThousand: this is per 1000; i.e 200 for 20% function createPETPlan( uint256 _minimumMonthlyCommitmentAmount, uint256 _monthlyBenefitFactorPerThousand ) public onlyDeployer { /// @notice adding the petPlan to storage petPlans.push(PETPlan({ isPlanActive: true, minimumMonthlyCommitmentAmount: _minimumMonthlyCommitmentAmount, monthlyBenefitFactorPerThousand: _monthlyBenefitFactorPerThousand })); /// @notice emitting an event emit NewPETPlan( _minimumMonthlyCommitmentAmount, _monthlyBenefitFactorPerThousand, petPlans.length - 1 ); } /// @notice this function is used by deployer to disable or re-enable a pet plan /// @dev pets already initiated by a plan will continue only new will be restricted /// @param _planId: select a plan to make it inactive /// @param _newStatus: true or false. function updatePlanStatus(uint256 _planId, bool _newStatus) public onlyDeployer { petPlans[_planId].isPlanActive = _newStatus; } /// @notice this function is used to update nominee status of a wallet address in PET /// @param _petId: id of PET in staker portfolio. /// @param _nomineeAddress: eth wallet address of nominee. /// @param _newNomineeStatus: true or false, whether this should be a nominee or not. function toogleNominee( uint256 _petId, address _nomineeAddress, bool _newNomineeStatus ) public { /// @notice updating nominee status pets[msg.sender][_petId].nominees[_nomineeAddress] = _newNomineeStatus; /// @notice emiting event for UI and other applications emit NomineeUpdated(msg.sender, _petId, _nomineeAddress, _newNomineeStatus); } /// @notice this function is used to update appointee status of a wallet address in PET /// @param _petId: id of PET in staker portfolio. /// @param _appointeeAddress: eth wallet address of appointee. /// @param _newAppointeeStatus: true or false, should this have appointee rights or not. function toogleAppointee( uint256 _petId, address _appointeeAddress, bool _newAppointeeStatus ) public { PET storage _pet = pets[msg.sender][_petId]; /// @notice if not an appointee already and _newAppointeeStatus is true, adding appointee if(!_pet.appointees[_appointeeAddress] && _newAppointeeStatus) { _pet.numberOfAppointees = _pet.numberOfAppointees.add(1); _pet.appointees[_appointeeAddress] = true; } /// @notice if already an appointee and _newAppointeeStatus is false, removing appointee else if(_pet.appointees[_appointeeAddress] && !_newAppointeeStatus) { _pet.appointees[_appointeeAddress] = false; _pet.numberOfAppointees = _pet.numberOfAppointees.sub(1); } emit AppointeeUpdated(msg.sender, _petId, _appointeeAddress, _newAppointeeStatus); } /// @notice this function is used by appointee to vote that nominees can withdraw early /// @dev need to be appointee, set by staker themselves /// @param _stakerAddress: address of initiater of this PET. /// @param _petId: id of PET in staker portfolio. function appointeeVote( address _stakerAddress, uint256 _petId ) public { PET storage _pet = pets[_stakerAddress][_petId]; /// @notice checking if appointee has rights to cast a vote require(_pet.appointees[msg.sender] , 'should be appointee to cast vote' ); /// @notice removing appointee's rights to vote again _pet.appointees[msg.sender] = false; /// @notice adding a vote to PET _pet.appointeeVotes = _pet.appointeeVotes.add(1); /// @notice emit that appointee has voted emit AppointeeVoted(_stakerAddress, _petId, msg.sender); } /// @notice this function is used by stakers to make deposits to their PETs /// @dev ERC20 approve is required to be done for this contract earlier if prepaidES /// is not selected, enough funds must be there in the funds bucket contract /// and also deposit can be done by nominee /// @param _stakerAddress: address of staker who has a PET /// @param _petId: id of PET in staker address portfolio /// @param _depositAmount: amount to deposit /// @param _usePrepaidES: should prepaidES be used function makeDeposit( address _stakerAddress, uint256 _petId, uint256 _depositAmount, bool _usePrepaidES ) public meOrNominee(_stakerAddress, _petId) { /// @notice check if non zero deposit require(_depositAmount > 0, 'deposit amount should be non zero'); /// @notice get the storage reference of staker's PET PET storage _pet = pets[_stakerAddress][_petId]; /// @notice calculate the deposit month based on time uint256 _depositMonth = getDepositMonth(_stakerAddress, _petId); /// @notice enforce no deposits after 12 months require(_depositMonth <= 12, 'cannot deposit after accumulation period'); if(_usePrepaidES) { /// @notice subtracting prepaidES from staker prepaidES[msg.sender] = prepaidES[msg.sender].sub(_depositAmount); } else { /// @notice transfering staker tokens to PET contract token.transferFrom(msg.sender, address(this), _depositAmount); } /// @notice calculate new deposit amount for the storage uint256 _updatedDepositAmount = _pet.monthlyDepositAmount[_depositMonth].add(_depositAmount); /// @notice carryforward small deposits in previous months uint256 _previousMonth = _depositMonth - 1; while(_previousMonth > 0) { if(0 < _pet.monthlyDepositAmount[_previousMonth] && _pet.monthlyDepositAmount[_previousMonth] < _pet.monthlyCommitmentAmount.div(2)) { _updatedDepositAmount = _updatedDepositAmount.add( _pet.monthlyDepositAmount[_previousMonth] ); _pet.monthlyDepositAmount[_previousMonth] = 0; } _previousMonth -= 1; } /// @notice calculate old allocation, to adjust it in new allocation uint256 _oldBenefitAllocation = _getBenefitAllocationByDepositAmount( _pet, 0, _depositMonth ); uint256 _extraBenefitAllocation = _getBenefitAllocationByDepositAmount( _pet, _updatedDepositAmount, _depositMonth ).sub(_oldBenefitAllocation); /// @notice pull funds from funds bucket token.transferFrom(fundsBucket, address(this), _extraBenefitAllocation); /// @notice recording the deposit by updating the value _pet.monthlyDepositAmount[_depositMonth] = _updatedDepositAmount; /// @notice emitting an event emit NewDeposit( _stakerAddress, _petId, _depositMonth, _depositAmount, // _extraBenefitAllocation, msg.sender, _usePrepaidES ); } /// @notice this function is used by stakers to make lum sum deposit /// @dev lum sum deposit is possible in the first month in a fresh PET /// @param _stakerAddress: address of staker who has a PET /// @param _petId: id of PET in staker address portfolio /// @param _totalDepositAmount: total amount to deposit for 12 months /// @param _frequencyMode: can be 3, 6 or 12 /// @param _usePrepaidES: should prepaidES be used // deposit frequency mode function makeFrequencyModeDeposit( address _stakerAddress, uint256 _petId, uint256 _totalDepositAmount, uint256 _frequencyMode, bool _usePrepaidES ) public { uint256 _fees; /// @dev using ether because ES also has 18 decimals like ETH if(_frequencyMode == 3) _fees = _totalDepositAmount.mul(1).div(100); else if(_frequencyMode == 6) _fees = _totalDepositAmount.mul(2).div(100); else if(_frequencyMode == 12) _fees = _totalDepositAmount.mul(3).div(100); else require(false, 'unsupported frequency'); /// @notice check if non zero deposit require(_totalDepositAmount > 0, 'deposit amount should be non zero'); /// @notice get the reference of staker's PET PET storage _pet = pets[_stakerAddress][_petId]; /// @notice calculate deposit month based on time and enforce first month uint256 _depositMonth = getDepositMonth(_stakerAddress, _petId); // require(_depositMonth == 1, 'allowed only in first month'); uint256 _uptoMonth = _depositMonth.add(_frequencyMode).sub(1); require(_uptoMonth <= 12, 'cannot deposit after accumulation period'); /// @notice enforce only fresh pets require(_pet.monthlyDepositAmount[_depositMonth] == 0, 'allowed only in fresh month deposit'); /// @notice calculate monthly deposit amount uint256 _monthlyDepositAmount = _totalDepositAmount.div(_frequencyMode); /// @notice check if single monthly deposit amount is at least commitment require( _monthlyDepositAmount >= _pet.monthlyCommitmentAmount , 'deposit not crossing commitment' ); /// @notice calculate benefit for a single month uint256 _benefitAllocationForSingleMonth = _getBenefitAllocationByDepositAmount( _pet, _monthlyDepositAmount, 1 ); if(_usePrepaidES) { /// @notice subtracting prepaidES from staker prepaidES[msg.sender] = prepaidES[msg.sender].sub(_totalDepositAmount.add(_fees)); } else { /// @notice transfering staker tokens to PET contract token.transferFrom(msg.sender, address(this), _totalDepositAmount.add(_fees)); } prepaidES[deployer] = prepaidES[deployer].add(_fees); // token.transfer(deployer, _fees); /// @notice pull funds from funds bucket token.transferFrom(fundsBucket, address(this), _benefitAllocationForSingleMonth.mul(_frequencyMode)); for(uint256 _monthId = _depositMonth; _monthId <= _uptoMonth; _monthId++) { /// @notice mark deposits in all the months _pet.monthlyDepositAmount[_monthId] = _monthlyDepositAmount; /// @notice emit events emit NewDeposit( _stakerAddress, _petId, _monthId, _monthlyDepositAmount, // _benefitAllocationForSingleMonth, msg.sender, _usePrepaidES ); } } /// @notice this function is used to withdraw annuity benefits /// @param _stakerAddress: address of staker who has a PET /// @param _petId: id of PET in staker address portfolio /// @param _endAnnuityMonthId: this is the month upto which benefits to be withdrawn function withdrawAnnuity( address _stakerAddress, uint256 _petId, uint256 _endAnnuityMonthId ) public meOrNominee(_stakerAddress, _petId) { PET storage _pet = pets[_stakerAddress][_petId]; uint256 _lastAnnuityWithdrawlMonthId = _pet.lastAnnuityWithdrawlMonthId; /// @notice enforcing withdrawls only once require( _lastAnnuityWithdrawlMonthId < _endAnnuityMonthId , 'start should be before end' ); /// @notice enforcing only 60 withdrawls require( _endAnnuityMonthId <= 60 , 'only 60 Annuity withdrawls' ); /// @notice calculating allowed timestamp uint256 _allowedTimestamp = getNomineeAllowedTimestamp( _stakerAddress, _petId, _endAnnuityMonthId ); /// @notice enforcing withdrawls only after allowed timestamp require( now >= _allowedTimestamp , 'cannot withdraw early' ); /// @notice calculating sum of annuity of the months uint256 _annuityBenefit = getSumOfMonthlyAnnuity( _stakerAddress, _petId, _lastAnnuityWithdrawlMonthId+1, _endAnnuityMonthId ); /// @notice updating last withdrawl month _pet.lastAnnuityWithdrawlMonthId = _endAnnuityMonthId; /// @notice burning penalised power booster tokens in the first annuity withdrawl if(_lastAnnuityWithdrawlMonthId == 0) { _burnPenalisedPowerBoosterTokens(_stakerAddress, _petId); } /// @notice transfering the annuity to withdrawer (staker or nominee) if(_annuityBenefit != 0) { token.transfer(msg.sender, _annuityBenefit); } // @notice emitting an event emit AnnuityWithdrawl( _stakerAddress, _petId, _lastAnnuityWithdrawlMonthId+1, _endAnnuityMonthId, _annuityBenefit, msg.sender ); } /// @notice this function is used by staker to withdraw power booster /// @param _stakerAddress: address of staker who has a PET /// @param _petId: id of PET in staker address portfolio /// @param _powerBoosterId: this is serial of power booster function withdrawPowerBooster( address _stakerAddress, uint256 _petId, uint256 _powerBoosterId ) public meOrNominee(_stakerAddress, _petId) { PET storage _pet = pets[_stakerAddress][_petId]; /// @notice enforcing 12 power booster withdrawls require( 1 <= _powerBoosterId && _powerBoosterId <= 12 , 'id should be in range' ); /// @notice enforcing power booster withdrawl once require( !_pet.isPowerBoosterWithdrawn[_powerBoosterId] , 'booster already withdrawn' ); /// @notice enforcing target to be acheived require( _pet.monthlyDepositAmount[13 - _powerBoosterId] >= _pet.monthlyCommitmentAmount , 'target not achieved' ); /// @notice calculating allowed timestamp based on time and nominee uint256 _allowedTimestamp = getNomineeAllowedTimestamp( _stakerAddress, _petId, _powerBoosterId*5+1 ); /// @notice enforcing withdrawl after _allowedTimestamp require( now >= _allowedTimestamp , 'cannot withdraw early' ); /// @notice calculating power booster amount uint256 _powerBoosterAmount = calculatePowerBoosterAmount(_stakerAddress, _petId); /// @notice marking power booster as withdrawn _pet.isPowerBoosterWithdrawn[_powerBoosterId] = true; if(_powerBoosterAmount > 0) { /// @notice sending the power booster amount to withdrawer (staker or nominee) token.transfer(msg.sender, _powerBoosterAmount); } /// @notice emitting an event emit PowerBoosterWithdrawl( _stakerAddress, _petId, _powerBoosterId, _powerBoosterAmount, msg.sender ); } /// @notice this function is used to view nomination /// @param _stakerAddress: address of initiater of this PET. /// @param _petId: id of PET in staker portfolio. /// @param _nomineeAddress: eth wallet address of nominee. /// @return tells whether this address is a nominee or not function viewNomination( address _stakerAddress, uint256 _petId, address _nomineeAddress ) public view returns (bool) { return pets[_stakerAddress][_petId].nominees[_nomineeAddress]; } /// @notice this function is used to view appointation /// @param _stakerAddress: address of initiater of this PET. /// @param _petId: id of PET in staker portfolio. /// @param _appointeeAddress: eth wallet address of apointee. /// @return tells whether this address is a appointee or not function viewAppointation( address _stakerAddress, uint256 _petId, address _appointeeAddress ) public view returns (bool) { return pets[_stakerAddress][_petId].appointees[_appointeeAddress]; } /// @notice this function is used by contract to get nominee's allowed timestamp /// @param _stakerAddress: address of staker who has a PET /// @param _petId: id of PET in staker address portfolio /// @param _annuityMonthId: this is the month for which timestamp to find /// @return nominee allowed timestamp function getNomineeAllowedTimestamp( address _stakerAddress, uint256 _petId, uint256 _annuityMonthId ) public view returns (uint256) { PET storage _pet = pets[_stakerAddress][_petId]; uint256 _allowedTimestamp = _pet.initTimestamp + (12 + _annuityMonthId - 1) * EARTH_SECONDS_IN_MONTH; /// @notice if tranasction sender is not the staker, then more delay to _allowedTimestamp if(msg.sender != _stakerAddress) { if(_pet.appointeeVotes > _pet.numberOfAppointees.div(2)) { _allowedTimestamp += EARTH_SECONDS_IN_MONTH * 6; } else { _allowedTimestamp += EARTH_SECONDS_IN_MONTH * 12; } } return _allowedTimestamp; } /// @notice this function is used to retrive monthly deposit in a PET /// @param _stakerAddress: address of staker who has PET /// @param _petId: id of PET in staket address portfolio /// @param _monthId: specify the month to deposit /// @return deposit in a particular month function getMonthlyDepositedAmount( address _stakerAddress, uint256 _petId, uint256 _monthId ) public view returns (uint256) { return pets[_stakerAddress][_petId].monthlyDepositAmount[_monthId]; } /// @notice this function is used to get the current month of a PET /// @param _stakerAddress: address of staker who has PET /// @param _petId: id of PET in staket address portfolio /// @return current month of a particular PET function getDepositMonth( address _stakerAddress, uint256 _petId ) public view returns (uint256) { return (now - pets[_stakerAddress][_petId].initTimestamp)/EARTH_SECONDS_IN_MONTH + 1; } /// @notice this function is used to get total annuity benefits between two months /// @param _stakerAddress: address of staker who has a PET /// @param _petId: id of PET in staker address portfolio /// @param _startAnnuityMonthId: this is the month (inclusive) to start from /// @param _endAnnuityMonthId: this is the month (inclusive) to stop at function getSumOfMonthlyAnnuity( address _stakerAddress, uint256 _petId, uint256 _startAnnuityMonthId, uint256 _endAnnuityMonthId ) public view returns (uint256) { /// @notice get the storage references of staker's PET and Plan PET storage _pet = pets[_stakerAddress][_petId]; PETPlan storage _petPlan = petPlans[_pet.planId]; uint256 _totalDeposits; /// @notice calculating both deposits for every month and adding it for(uint256 _i = _startAnnuityMonthId; _i <= _endAnnuityMonthId; _i++) { uint256 _modulo = _i%12; uint256 _depositAmountIncludingPET = _getTotalDepositedIncludingPET(_pet.monthlyDepositAmount[_modulo==0?12:_modulo], _pet.monthlyCommitmentAmount); _totalDeposits = _totalDeposits.add(_depositAmountIncludingPET); } /// @notice calculating annuity from total both deposits done return _totalDeposits.mul(_petPlan.monthlyBenefitFactorPerThousand).div(1000); } /// @notice calculating power booster amount /// @param _stakerAddress: address of staker who has PET /// @param _petId: id of PET in staket address portfolio /// @return single power booster amount function calculatePowerBoosterAmount( address _stakerAddress, uint256 _petId ) public view returns (uint256) { /// @notice get the storage reference of staker's PET PET storage _pet = pets[_stakerAddress][_petId]; uint256 _totalDepositedIncludingPET; /// @notice calculating total deposited by staker and pet in all 12 months for(uint256 _i = 1; _i <= 12; _i++) { uint256 _depositAmountIncludingPET = _getTotalDepositedIncludingPET( _pet.monthlyDepositAmount[_i], _pet.monthlyCommitmentAmount ); _totalDepositedIncludingPET = _totalDepositedIncludingPET.add(_depositAmountIncludingPET); } return _totalDepositedIncludingPET.div(12); } /// @notice this function is used internally to burn penalised booster tokens /// @param _stakerAddress: address of staker who has a PET /// @param _petId: id of PET in staker address portfolio function _burnPenalisedPowerBoosterTokens( address _stakerAddress, uint256 _petId ) private { /// @notice get the storage references of staker's PET PET storage _pet = pets[_stakerAddress][_petId]; uint256 _unachieveTargetCount; /// @notice calculating number of unacheived targets for(uint256 _i = 1; _i <= 12; _i++) { if(_pet.monthlyDepositAmount[_i] < _pet.monthlyCommitmentAmount) { _unachieveTargetCount++; } } uint256 _powerBoosterAmount = calculatePowerBoosterAmount(_stakerAddress, _petId); /// @notice burning the unacheived power boosters uint256 _burningAmount = _powerBoosterAmount.mul(_unachieveTargetCount); token.burn(_burningAmount); // @notice emitting an event emit BoosterBurn(_stakerAddress, _petId, _burningAmount); } /// @notice this function is used by contract to calculate benefit allocation when /// a staker makes a deposit /// @param _pet: this is a reference to staker's pet storage /// @param _depositAmount: this is amount deposited by staker /// @param _depositMonth: this is month at which deposit takes place /// @return benefit amount to be allocated due to the deposit function _getBenefitAllocationByDepositAmount( PET storage _pet, uint256 _depositAmount, uint256 _depositMonth ) private view returns (uint256) { uint256 _planId = _pet.planId; uint256 _amount = _depositAmount != 0 ? _depositAmount : _pet.monthlyDepositAmount[_depositMonth]; uint256 _monthlyCommitmentAmount = _pet.monthlyCommitmentAmount; PETPlan storage _petPlan = petPlans[_planId]; uint256 _petAmount; /// @notice if amount is above commitment then amount + commitment + amount / 2 if(_amount > _monthlyCommitmentAmount) { uint256 _topupAmount = _amount.sub(_monthlyCommitmentAmount); _petAmount = _monthlyCommitmentAmount.add(_topupAmount.div(2)); } /// @notice otherwise if amount is atleast half of commitment and at most commitment /// then take staker amount as the pet amount else if(_amount >= _monthlyCommitmentAmount.div(2)) { _petAmount = _amount; } /// @notice getting total deposit for the month including pet uint256 _depositAmountIncludingPET = _getTotalDepositedIncludingPET( _amount, _monthlyCommitmentAmount ); /// @dev starting with allocating power booster amount due to this deposit amount uint256 _benefitAllocation = _petAmount; /// @notice calculating the benefits in 5 years due to this deposit if(_amount >= _monthlyCommitmentAmount.div(2) || _depositMonth == 12) { _benefitAllocation = _benefitAllocation.add( _depositAmountIncludingPET.mul(_petPlan.monthlyBenefitFactorPerThousand).mul(5).div(1000) ); } return _benefitAllocation; } /// @notice this function is used by contract to get total deposited amount including PET /// @param _amount: amount of ES which is deposited /// @param _monthlyCommitmentAmount: commitment amount of staker /// @return staker plus pet deposit amount based on acheivement of commitment function _getTotalDepositedIncludingPET( uint256 _amount, uint256 _monthlyCommitmentAmount ) private pure returns (uint256) { uint256 _petAmount; /// @notice if there is topup then add half of topup to pet if(_amount > _monthlyCommitmentAmount) { uint256 _topupAmount = _amount.sub(_monthlyCommitmentAmount); _petAmount = _monthlyCommitmentAmount.add(_topupAmount.div(2)); } /// @notice otherwise if amount is atleast half of commitment and at most commitment /// then take staker amount as the pet amount else if(_amount >= _monthlyCommitmentAmount.div(2)) { _petAmount = _amount; } /// @notice finally sum staker amount and pet amount and return it return _amount.add(_petAmount); } } /// @dev For interface requirement contract ERC20 { function balanceOf(address tokenDeployer) public view returns (uint); function approve(address delegate, uint numTokens) public returns (bool); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function burn(uint256 value) public; function mou() public view returns (uint256); } pragma solidity ^0.5.2; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on 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-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } pragma solidity 0.5.16; import './SafeMath.sol'; /// @title Fund Bucket of TimeAlly Personal EraSwap Teller /// @author The EraSwap Team /// @notice The returns for PET Smart Contract are transparently stored in advance in this contract contract FundsBucketPET { /// @notice address of the maintainer address public deployer; /// @notice address of Era Swap ERC20 Smart Contract ERC20 public token; /// @notice address of PET Smart Contract address public petContract; /// @notice event schema for monitoring funds added by donors event FundsDeposited( address _depositer, uint256 _depositAmount ); /// @notice event schema for monitoring unallocated fund withdrawn by deployer event FundsWithdrawn( address _withdrawer, uint256 _withdrawAmount ); /// @notice restricting access to some functionalities to deployer modifier onlyDeployer() { require(msg.sender == deployer, 'only deployer can call'); _; } /// @notice this function is used to deploy FundsBucket Smart Contract /// the same time while deploying PET Smart Contract /// @dev this smart contract is deployed by PET Smart Contract while being set up /// @param _token: is EraSwap ERC20 Smart Contract Address /// @param _deployer: is address of the deployer of PET Smart Contract constructor(ERC20 _token, address _deployer) public { token = _token; deployer = _deployer; petContract = msg.sender; } /// @notice this function is used by well wishers to add funds to the fund bucket of PET /// @dev ERC20 approve is required to be done for this contract earlier /// @param _depositAmount: amount in exaES to deposit function addFunds(uint256 _depositAmount) public { token.transferFrom(msg.sender, address(this), _depositAmount); /// @dev approving the PET Smart Contract in advance token.approve(petContract, _depositAmount); emit FundsDeposited(msg.sender, _depositAmount); } /// @notice this function makes it possible for deployer to withdraw unallocated ES function withdrawFunds(bool _withdrawEverything, uint256 _withdrawlAmount) public onlyDeployer { if(_withdrawEverything) { _withdrawlAmount = token.balanceOf(address(this)); } token.transfer(msg.sender, _withdrawlAmount); emit FundsWithdrawn(msg.sender, _withdrawlAmount); } } /// @title TimeAlly Personal EraSwap Teller Smart Contract /// @author The EraSwap Team /// @notice Stakes EraSwap tokens with staker contract TimeAllyPET { using SafeMath for uint256; /// @notice data structure of a PET Plan struct PETPlan { bool isPlanActive; uint256 minimumMonthlyCommitmentAmount; uint256 monthlyBenefitFactorPerThousand; } /// @notice data structure of a PET Plan struct PET { uint256 planId; uint256 monthlyCommitmentAmount; uint256 initTimestamp; uint256 lastAnnuityWithdrawlMonthId; uint256 appointeeVotes; uint256 numberOfAppointees; mapping(uint256 => uint256) monthlyDepositAmount; mapping(uint256 => bool) isPowerBoosterWithdrawn; mapping(address => bool) nominees; mapping(address => bool) appointees; } /// @notice address storage of the deployer address public deployer; /// @notice address storage of fundsBucket from which tokens to be pulled for giving benefits address public fundsBucket; /// @notice address storage of Era Swap Token ERC20 Smart Contract ERC20 public token; /// @dev selected for taking care of leap years such that 1 Year = 365.242 days holds uint256 constant EARTH_SECONDS_IN_MONTH = 2629744; /// @notice storage for multiple PET plans PETPlan[] public petPlans; /// @notice storage for PETs deployed by stakers mapping(address => PET[]) public pets; /// @notice storage for prepaid Era Swaps available for any wallet address mapping(address => uint256) public prepaidES; /// @notice event schema for monitoring new pet plans event NewPETPlan ( uint256 _minimumMonthlyCommitmentAmount, uint256 _monthlyBenefitFactorPerThousand, uint256 _petPlanId ); /// @notice event schema for monitoring new pets by stakers event NewPET ( address indexed _staker, uint256 _petId, uint256 _monthlyCommitmentAmount ); /// @notice event schema for monitoring deposits made by stakers to their pets event NewDeposit ( address indexed _staker, uint256 indexed _petId, uint256 _monthId, uint256 _depositAmount, // uint256 _benefitAllocated, address _depositedBy, bool _usingPrepaidES ); /// @notice event schema for monitoring pet annuity withdrawn by stakers event AnnuityWithdrawl ( address indexed _staker, uint256 indexed _petId, uint256 _fromMonthId, uint256 _toMonthId, uint256 _withdrawlAmount, address _withdrawnBy ); /// @notice event schema for monitoring power booster withdrawn by stakers event PowerBoosterWithdrawl ( address indexed _staker, uint256 indexed _petId, uint256 _powerBoosterId, uint256 _withdrawlAmount, address _withdrawnBy ); /// @notice event schema for monitoring penalised power booster burning event BoosterBurn ( address _staker, uint256 _petId, uint256 _burningAmount ); /// @notice event schema for monitoring power booster withdrawn by stakers event NomineeUpdated ( address indexed _staker, uint256 indexed _petId, address indexed _nomineeAddress, bool _nomineeStatus ); /// @notice event schema for monitoring power booster withdrawls by stakers event AppointeeUpdated ( address indexed _staker, uint256 indexed _petId, address indexed _appointeeAddress, bool _appointeeStatus ); /// @notice event schema for monitoring power booster withdrawls by stakers event AppointeeVoted ( address indexed _staker, uint256 indexed _petId, address indexed _appointeeAddress ); /// @notice restricting access to some functionalities to deployer modifier onlyDeployer() { require(msg.sender == deployer, 'only deployer can call'); _; } /// @notice restricting access of staker's PET to them and their pet nominees modifier meOrNominee(address _stakerAddress, uint256 _petId) { PET storage _pet = pets[_stakerAddress][_petId]; /// @notice if transacter is not staker, then transacter should be nominee if(msg.sender != _stakerAddress) { require(_pet.nominees[msg.sender], 'nomination should be there'); } _; } /// @notice sets up TimeAllyPET contract when deployed and also deploys FundsBucket /// @param _token: is EraSwap ERC20 Smart Contract Address constructor(ERC20 _token) public { deployer = msg.sender; token = _token; fundsBucket = address(new FundsBucketPET(_token, msg.sender)); } /// @notice this function is used to add ES as prepaid for PET /// @dev ERC20 approve needs to be done /// @param _amount: ES to deposit function addToPrepaid(uint256 _amount) public { /// @notice transfering the tokens from user token.transferFrom(msg.sender, address(this), _amount); /// @notice then adding tokens to prepaidES prepaidES[msg.sender] = prepaidES[msg.sender].add(_amount); } /// @notice this function is used to send ES as prepaid for PET /// @dev some ES already in prepaid required /// @param _addresses: address array to send prepaid ES for PET /// @param _amounts: prepaid ES for PET amounts to send to corresponding addresses function sendPrepaidESDifferent( address[] memory _addresses, uint256[] memory _amounts ) public { for(uint256 i = 0; i < _addresses.length; i++) { /// @notice subtracting amount from sender prepaidES prepaidES[msg.sender] = prepaidES[msg.sender].sub(_amounts[i]); /// @notice then incrementing the amount into receiver's prepaidES prepaidES[_addresses[i]] = prepaidES[_addresses[i]].add(_amounts[i]); } } /// @notice this function is used by anyone to create a new PET /// @param _planId: id of PET in staker portfolio /// @param _monthlyCommitmentAmount: PET monthly commitment amount in exaES function newPET( uint256 _planId, uint256 _monthlyCommitmentAmount ) public { /// @notice enforcing that the plan should be active require( petPlans[_planId].isPlanActive , 'PET plan is not active' ); /// @notice enforcing that monthly commitment by the staker should be more than /// minimum monthly commitment in the selected plan require( _monthlyCommitmentAmount >= petPlans[_planId].minimumMonthlyCommitmentAmount , 'low monthlyCommitmentAmount' ); /// @notice adding the PET to staker's pets storage pets[msg.sender].push(PET({ planId: _planId, monthlyCommitmentAmount: _monthlyCommitmentAmount, initTimestamp: now, lastAnnuityWithdrawlMonthId: 0, appointeeVotes: 0, numberOfAppointees: 0 })); /// @notice emiting an event emit NewPET( msg.sender, pets[msg.sender].length - 1, _monthlyCommitmentAmount ); } /// @notice this function is used by deployer to create plans for new PETs /// @param _minimumMonthlyCommitmentAmount: minimum PET monthly amount in exaES /// @param _monthlyBenefitFactorPerThousand: this is per 1000; i.e 200 for 20% function createPETPlan( uint256 _minimumMonthlyCommitmentAmount, uint256 _monthlyBenefitFactorPerThousand ) public onlyDeployer { /// @notice adding the petPlan to storage petPlans.push(PETPlan({ isPlanActive: true, minimumMonthlyCommitmentAmount: _minimumMonthlyCommitmentAmount, monthlyBenefitFactorPerThousand: _monthlyBenefitFactorPerThousand })); /// @notice emitting an event emit NewPETPlan( _minimumMonthlyCommitmentAmount, _monthlyBenefitFactorPerThousand, petPlans.length - 1 ); } /// @notice this function is used by deployer to disable or re-enable a pet plan /// @dev pets already initiated by a plan will continue only new will be restricted /// @param _planId: select a plan to make it inactive /// @param _newStatus: true or false. function updatePlanStatus(uint256 _planId, bool _newStatus) public onlyDeployer { petPlans[_planId].isPlanActive = _newStatus; } /// @notice this function is used to update nominee status of a wallet address in PET /// @param _petId: id of PET in staker portfolio. /// @param _nomineeAddress: eth wallet address of nominee. /// @param _newNomineeStatus: true or false, whether this should be a nominee or not. function toogleNominee( uint256 _petId, address _nomineeAddress, bool _newNomineeStatus ) public { /// @notice updating nominee status pets[msg.sender][_petId].nominees[_nomineeAddress] = _newNomineeStatus; /// @notice emiting event for UI and other applications emit NomineeUpdated(msg.sender, _petId, _nomineeAddress, _newNomineeStatus); } /// @notice this function is used to update appointee status of a wallet address in PET /// @param _petId: id of PET in staker portfolio. /// @param _appointeeAddress: eth wallet address of appointee. /// @param _newAppointeeStatus: true or false, should this have appointee rights or not. function toogleAppointee( uint256 _petId, address _appointeeAddress, bool _newAppointeeStatus ) public { PET storage _pet = pets[msg.sender][_petId]; /// @notice if not an appointee already and _newAppointeeStatus is true, adding appointee if(!_pet.appointees[_appointeeAddress] && _newAppointeeStatus) { _pet.numberOfAppointees = _pet.numberOfAppointees.add(1); _pet.appointees[_appointeeAddress] = true; } /// @notice if already an appointee and _newAppointeeStatus is false, removing appointee else if(_pet.appointees[_appointeeAddress] && !_newAppointeeStatus) { _pet.appointees[_appointeeAddress] = false; _pet.numberOfAppointees = _pet.numberOfAppointees.sub(1); } emit AppointeeUpdated(msg.sender, _petId, _appointeeAddress, _newAppointeeStatus); } /// @notice this function is used by appointee to vote that nominees can withdraw early /// @dev need to be appointee, set by staker themselves /// @param _stakerAddress: address of initiater of this PET. /// @param _petId: id of PET in staker portfolio. function appointeeVote( address _stakerAddress, uint256 _petId ) public { PET storage _pet = pets[_stakerAddress][_petId]; /// @notice checking if appointee has rights to cast a vote require(_pet.appointees[msg.sender] , 'should be appointee to cast vote' ); /// @notice removing appointee's rights to vote again _pet.appointees[msg.sender] = false; /// @notice adding a vote to PET _pet.appointeeVotes = _pet.appointeeVotes.add(1); /// @notice emit that appointee has voted emit AppointeeVoted(_stakerAddress, _petId, msg.sender); } /// @notice this function is used by stakers to make deposits to their PETs /// @dev ERC20 approve is required to be done for this contract earlier if prepaidES /// is not selected, enough funds must be there in the funds bucket contract /// and also deposit can be done by nominee /// @param _stakerAddress: address of staker who has a PET /// @param _petId: id of PET in staker address portfolio /// @param _depositAmount: amount to deposit /// @param _usePrepaidES: should prepaidES be used function makeDeposit( address _stakerAddress, uint256 _petId, uint256 _depositAmount, bool _usePrepaidES ) public meOrNominee(_stakerAddress, _petId) { /// @notice check if non zero deposit require(_depositAmount > 0, 'deposit amount should be non zero'); /// @notice get the storage reference of staker's PET PET storage _pet = pets[_stakerAddress][_petId]; /// @notice calculate the deposit month based on time uint256 _depositMonth = getDepositMonth(_stakerAddress, _petId); /// @notice enforce no deposits after 12 months require(_depositMonth <= 12, 'cannot deposit after accumulation period'); if(_usePrepaidES) { /// @notice subtracting prepaidES from staker prepaidES[msg.sender] = prepaidES[msg.sender].sub(_depositAmount); } else { /// @notice transfering staker tokens to PET contract token.transferFrom(msg.sender, address(this), _depositAmount); } /// @notice calculate new deposit amount for the storage uint256 _updatedDepositAmount = _pet.monthlyDepositAmount[_depositMonth].add(_depositAmount); /// @notice carryforward small deposits in previous months uint256 _previousMonth = _depositMonth - 1; while(_previousMonth > 0) { if(0 < _pet.monthlyDepositAmount[_previousMonth] && _pet.monthlyDepositAmount[_previousMonth] < _pet.monthlyCommitmentAmount.div(2)) { _updatedDepositAmount = _updatedDepositAmount.add( _pet.monthlyDepositAmount[_previousMonth] ); _pet.monthlyDepositAmount[_previousMonth] = 0; } _previousMonth -= 1; } /// @notice calculate old allocation, to adjust it in new allocation uint256 _oldBenefitAllocation = _getBenefitAllocationByDepositAmount( _pet, 0, _depositMonth ); uint256 _extraBenefitAllocation = _getBenefitAllocationByDepositAmount( _pet, _updatedDepositAmount, _depositMonth ).sub(_oldBenefitAllocation); /// @notice pull funds from funds bucket token.transferFrom(fundsBucket, address(this), _extraBenefitAllocation); /// @notice recording the deposit by updating the value _pet.monthlyDepositAmount[_depositMonth] = _updatedDepositAmount; /// @notice emitting an event emit NewDeposit( _stakerAddress, _petId, _depositMonth, _depositAmount, // _extraBenefitAllocation, msg.sender, _usePrepaidES ); } /// @notice this function is used by stakers to make lum sum deposit /// @dev lum sum deposit is possible in the first month in a fresh PET /// @param _stakerAddress: address of staker who has a PET /// @param _petId: id of PET in staker address portfolio /// @param _totalDepositAmount: total amount to deposit for 12 months /// @param _frequencyMode: can be 3, 6 or 12 /// @param _usePrepaidES: should prepaidES be used // deposit frequency mode function makeFrequencyModeDeposit( address _stakerAddress, uint256 _petId, uint256 _totalDepositAmount, uint256 _frequencyMode, bool _usePrepaidES ) public { uint256 _fees; /// @dev using ether because ES also has 18 decimals like ETH if(_frequencyMode == 3) _fees = _totalDepositAmount.mul(1).div(100); else if(_frequencyMode == 6) _fees = _totalDepositAmount.mul(2).div(100); else if(_frequencyMode == 12) _fees = _totalDepositAmount.mul(3).div(100); else require(false, 'unsupported frequency'); /// @notice check if non zero deposit require(_totalDepositAmount > 0, 'deposit amount should be non zero'); /// @notice get the reference of staker's PET PET storage _pet = pets[_stakerAddress][_petId]; /// @notice calculate deposit month based on time and enforce first month uint256 _depositMonth = getDepositMonth(_stakerAddress, _petId); // require(_depositMonth == 1, 'allowed only in first month'); uint256 _uptoMonth = _depositMonth.add(_frequencyMode).sub(1); require(_uptoMonth <= 12, 'cannot deposit after accumulation period'); /// @notice enforce only fresh pets require(_pet.monthlyDepositAmount[_depositMonth] == 0, 'allowed only in fresh month deposit'); /// @notice calculate monthly deposit amount uint256 _monthlyDepositAmount = _totalDepositAmount.div(_frequencyMode); /// @notice check if single monthly deposit amount is at least commitment require( _monthlyDepositAmount >= _pet.monthlyCommitmentAmount , 'deposit not crossing commitment' ); /// @notice calculate benefit for a single month uint256 _benefitAllocationForSingleMonth = _getBenefitAllocationByDepositAmount( _pet, _monthlyDepositAmount, 1 ); if(_usePrepaidES) { /// @notice subtracting prepaidES from staker prepaidES[msg.sender] = prepaidES[msg.sender].sub(_totalDepositAmount.add(_fees)); } else { /// @notice transfering staker tokens to PET contract token.transferFrom(msg.sender, address(this), _totalDepositAmount.add(_fees)); } prepaidES[deployer] = prepaidES[deployer].add(_fees); // token.transfer(deployer, _fees); /// @notice pull funds from funds bucket token.transferFrom(fundsBucket, address(this), _benefitAllocationForSingleMonth.mul(_frequencyMode)); for(uint256 _monthId = _depositMonth; _monthId <= _uptoMonth; _monthId++) { /// @notice mark deposits in all the months _pet.monthlyDepositAmount[_monthId] = _monthlyDepositAmount; /// @notice emit events emit NewDeposit( _stakerAddress, _petId, _monthId, _monthlyDepositAmount, // _benefitAllocationForSingleMonth, msg.sender, _usePrepaidES ); } } /// @notice this function is used to withdraw annuity benefits /// @param _stakerAddress: address of staker who has a PET /// @param _petId: id of PET in staker address portfolio /// @param _endAnnuityMonthId: this is the month upto which benefits to be withdrawn function withdrawAnnuity( address _stakerAddress, uint256 _petId, uint256 _endAnnuityMonthId ) public meOrNominee(_stakerAddress, _petId) { PET storage _pet = pets[_stakerAddress][_petId]; uint256 _lastAnnuityWithdrawlMonthId = _pet.lastAnnuityWithdrawlMonthId; /// @notice enforcing withdrawls only once require( _lastAnnuityWithdrawlMonthId < _endAnnuityMonthId , 'start should be before end' ); /// @notice enforcing only 60 withdrawls require( _endAnnuityMonthId <= 60 , 'only 60 Annuity withdrawls' ); /// @notice calculating allowed timestamp uint256 _allowedTimestamp = getNomineeAllowedTimestamp( _stakerAddress, _petId, _endAnnuityMonthId ); /// @notice enforcing withdrawls only after allowed timestamp require( now >= _allowedTimestamp , 'cannot withdraw early' ); /// @notice calculating sum of annuity of the months uint256 _annuityBenefit = getSumOfMonthlyAnnuity( _stakerAddress, _petId, _lastAnnuityWithdrawlMonthId+1, _endAnnuityMonthId ); /// @notice updating last withdrawl month _pet.lastAnnuityWithdrawlMonthId = _endAnnuityMonthId; /// @notice burning penalised power booster tokens in the first annuity withdrawl if(_lastAnnuityWithdrawlMonthId == 0) { _burnPenalisedPowerBoosterTokens(_stakerAddress, _petId); } /// @notice transfering the annuity to withdrawer (staker or nominee) if(_annuityBenefit != 0) { token.transfer(msg.sender, _annuityBenefit); } // @notice emitting an event emit AnnuityWithdrawl( _stakerAddress, _petId, _lastAnnuityWithdrawlMonthId+1, _endAnnuityMonthId, _annuityBenefit, msg.sender ); } /// @notice this function is used by staker to withdraw power booster /// @param _stakerAddress: address of staker who has a PET /// @param _petId: id of PET in staker address portfolio /// @param _powerBoosterId: this is serial of power booster function withdrawPowerBooster( address _stakerAddress, uint256 _petId, uint256 _powerBoosterId ) public meOrNominee(_stakerAddress, _petId) { PET storage _pet = pets[_stakerAddress][_petId]; /// @notice enforcing 12 power booster withdrawls require( 1 <= _powerBoosterId && _powerBoosterId <= 12 , 'id should be in range' ); /// @notice enforcing power booster withdrawl once require( !_pet.isPowerBoosterWithdrawn[_powerBoosterId] , 'booster already withdrawn' ); /// @notice enforcing target to be acheived require( _pet.monthlyDepositAmount[13 - _powerBoosterId] >= _pet.monthlyCommitmentAmount , 'target not achieved' ); /// @notice calculating allowed timestamp based on time and nominee uint256 _allowedTimestamp = getNomineeAllowedTimestamp( _stakerAddress, _petId, _powerBoosterId*5+1 ); /// @notice enforcing withdrawl after _allowedTimestamp require( now >= _allowedTimestamp , 'cannot withdraw early' ); /// @notice calculating power booster amount uint256 _powerBoosterAmount = calculatePowerBoosterAmount(_stakerAddress, _petId); /// @notice marking power booster as withdrawn _pet.isPowerBoosterWithdrawn[_powerBoosterId] = true; if(_powerBoosterAmount > 0) { /// @notice sending the power booster amount to withdrawer (staker or nominee) token.transfer(msg.sender, _powerBoosterAmount); } /// @notice emitting an event emit PowerBoosterWithdrawl( _stakerAddress, _petId, _powerBoosterId, _powerBoosterAmount, msg.sender ); } /// @notice this function is used to view nomination /// @param _stakerAddress: address of initiater of this PET. /// @param _petId: id of PET in staker portfolio. /// @param _nomineeAddress: eth wallet address of nominee. /// @return tells whether this address is a nominee or not function viewNomination( address _stakerAddress, uint256 _petId, address _nomineeAddress ) public view returns (bool) { return pets[_stakerAddress][_petId].nominees[_nomineeAddress]; } /// @notice this function is used to view appointation /// @param _stakerAddress: address of initiater of this PET. /// @param _petId: id of PET in staker portfolio. /// @param _appointeeAddress: eth wallet address of apointee. /// @return tells whether this address is a appointee or not function viewAppointation( address _stakerAddress, uint256 _petId, address _appointeeAddress ) public view returns (bool) { return pets[_stakerAddress][_petId].appointees[_appointeeAddress]; } /// @notice this function is used by contract to get nominee's allowed timestamp /// @param _stakerAddress: address of staker who has a PET /// @param _petId: id of PET in staker address portfolio /// @param _annuityMonthId: this is the month for which timestamp to find /// @return nominee allowed timestamp function getNomineeAllowedTimestamp( address _stakerAddress, uint256 _petId, uint256 _annuityMonthId ) public view returns (uint256) { PET storage _pet = pets[_stakerAddress][_petId]; uint256 _allowedTimestamp = _pet.initTimestamp + (12 + _annuityMonthId - 1) * EARTH_SECONDS_IN_MONTH; /// @notice if tranasction sender is not the staker, then more delay to _allowedTimestamp if(msg.sender != _stakerAddress) { if(_pet.appointeeVotes > _pet.numberOfAppointees.div(2)) { _allowedTimestamp += EARTH_SECONDS_IN_MONTH * 6; } else { _allowedTimestamp += EARTH_SECONDS_IN_MONTH * 12; } } return _allowedTimestamp; } /// @notice this function is used to retrive monthly deposit in a PET /// @param _stakerAddress: address of staker who has PET /// @param _petId: id of PET in staket address portfolio /// @param _monthId: specify the month to deposit /// @return deposit in a particular month function getMonthlyDepositedAmount( address _stakerAddress, uint256 _petId, uint256 _monthId ) public view returns (uint256) { return pets[_stakerAddress][_petId].monthlyDepositAmount[_monthId]; } /// @notice this function is used to get the current month of a PET /// @param _stakerAddress: address of staker who has PET /// @param _petId: id of PET in staket address portfolio /// @return current month of a particular PET function getDepositMonth( address _stakerAddress, uint256 _petId ) public view returns (uint256) { return (now - pets[_stakerAddress][_petId].initTimestamp)/EARTH_SECONDS_IN_MONTH + 1; } /// @notice this function is used to get total annuity benefits between two months /// @param _stakerAddress: address of staker who has a PET /// @param _petId: id of PET in staker address portfolio /// @param _startAnnuityMonthId: this is the month (inclusive) to start from /// @param _endAnnuityMonthId: this is the month (inclusive) to stop at function getSumOfMonthlyAnnuity( address _stakerAddress, uint256 _petId, uint256 _startAnnuityMonthId, uint256 _endAnnuityMonthId ) public view returns (uint256) { /// @notice get the storage references of staker's PET and Plan PET storage _pet = pets[_stakerAddress][_petId]; PETPlan storage _petPlan = petPlans[_pet.planId]; uint256 _totalDeposits; /// @notice calculating both deposits for every month and adding it for(uint256 _i = _startAnnuityMonthId; _i <= _endAnnuityMonthId; _i++) { uint256 _modulo = _i%12; uint256 _depositAmountIncludingPET = _getTotalDepositedIncludingPET(_pet.monthlyDepositAmount[_modulo==0?12:_modulo], _pet.monthlyCommitmentAmount); _totalDeposits = _totalDeposits.add(_depositAmountIncludingPET); } /// @notice calculating annuity from total both deposits done return _totalDeposits.mul(_petPlan.monthlyBenefitFactorPerThousand).div(1000); } /// @notice calculating power booster amount /// @param _stakerAddress: address of staker who has PET /// @param _petId: id of PET in staket address portfolio /// @return single power booster amount function calculatePowerBoosterAmount( address _stakerAddress, uint256 _petId ) public view returns (uint256) { /// @notice get the storage reference of staker's PET PET storage _pet = pets[_stakerAddress][_petId]; uint256 _totalDepositedIncludingPET; /// @notice calculating total deposited by staker and pet in all 12 months for(uint256 _i = 1; _i <= 12; _i++) { uint256 _depositAmountIncludingPET = _getTotalDepositedIncludingPET( _pet.monthlyDepositAmount[_i], _pet.monthlyCommitmentAmount ); _totalDepositedIncludingPET = _totalDepositedIncludingPET.add(_depositAmountIncludingPET); } return _totalDepositedIncludingPET.div(12); } /// @notice this function is used internally to burn penalised booster tokens /// @param _stakerAddress: address of staker who has a PET /// @param _petId: id of PET in staker address portfolio function _burnPenalisedPowerBoosterTokens( address _stakerAddress, uint256 _petId ) private { /// @notice get the storage references of staker's PET PET storage _pet = pets[_stakerAddress][_petId]; uint256 _unachieveTargetCount; /// @notice calculating number of unacheived targets for(uint256 _i = 1; _i <= 12; _i++) { if(_pet.monthlyDepositAmount[_i] < _pet.monthlyCommitmentAmount) { _unachieveTargetCount++; } } uint256 _powerBoosterAmount = calculatePowerBoosterAmount(_stakerAddress, _petId); /// @notice burning the unacheived power boosters uint256 _burningAmount = _powerBoosterAmount.mul(_unachieveTargetCount); token.burn(_burningAmount); // @notice emitting an event emit BoosterBurn(_stakerAddress, _petId, _burningAmount); } /// @notice this function is used by contract to calculate benefit allocation when /// a staker makes a deposit /// @param _pet: this is a reference to staker's pet storage /// @param _depositAmount: this is amount deposited by staker /// @param _depositMonth: this is month at which deposit takes place /// @return benefit amount to be allocated due to the deposit function _getBenefitAllocationByDepositAmount( PET storage _pet, uint256 _depositAmount, uint256 _depositMonth ) private view returns (uint256) { uint256 _planId = _pet.planId; uint256 _amount = _depositAmount != 0 ? _depositAmount : _pet.monthlyDepositAmount[_depositMonth]; uint256 _monthlyCommitmentAmount = _pet.monthlyCommitmentAmount; PETPlan storage _petPlan = petPlans[_planId]; uint256 _petAmount; /// @notice if amount is above commitment then amount + commitment + amount / 2 if(_amount > _monthlyCommitmentAmount) { uint256 _topupAmount = _amount.sub(_monthlyCommitmentAmount); _petAmount = _monthlyCommitmentAmount.add(_topupAmount.div(2)); } /// @notice otherwise if amount is atleast half of commitment and at most commitment /// then take staker amount as the pet amount else if(_amount >= _monthlyCommitmentAmount.div(2)) { _petAmount = _amount; } /// @notice getting total deposit for the month including pet uint256 _depositAmountIncludingPET = _getTotalDepositedIncludingPET( _amount, _monthlyCommitmentAmount ); /// @dev starting with allocating power booster amount due to this deposit amount uint256 _benefitAllocation = _petAmount; /// @notice calculating the benefits in 5 years due to this deposit if(_amount >= _monthlyCommitmentAmount.div(2) || _depositMonth == 12) { _benefitAllocation = _benefitAllocation.add( _depositAmountIncludingPET.mul(_petPlan.monthlyBenefitFactorPerThousand).mul(5).div(1000) ); } return _benefitAllocation; } /// @notice this function is used by contract to get total deposited amount including PET /// @param _amount: amount of ES which is deposited /// @param _monthlyCommitmentAmount: commitment amount of staker /// @return staker plus pet deposit amount based on acheivement of commitment function _getTotalDepositedIncludingPET( uint256 _amount, uint256 _monthlyCommitmentAmount ) private pure returns (uint256) { uint256 _petAmount; /// @notice if there is topup then add half of topup to pet if(_amount > _monthlyCommitmentAmount) { uint256 _topupAmount = _amount.sub(_monthlyCommitmentAmount); _petAmount = _monthlyCommitmentAmount.add(_topupAmount.div(2)); } /// @notice otherwise if amount is atleast half of commitment and at most commitment /// then take staker amount as the pet amount else if(_amount >= _monthlyCommitmentAmount.div(2)) { _petAmount = _amount; } /// @notice finally sum staker amount and pet amount and return it return _amount.add(_petAmount); } } /// @dev For interface requirement contract ERC20 { function balanceOf(address tokenDeployer) public view returns (uint); function approve(address delegate, uint numTokens) public returns (bool); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function burn(uint256 value) public; function mou() public view returns (uint256); }
this function is used by anyone to create a new PET _planId: id of PET in staker portfolio _monthlyCommitmentAmount: PET monthly commitment amount in exaES enforcing that the plan should be active enforcing that monthly commitment by the staker should be more than minimum monthly commitment in the selected plan adding the PET to staker's pets storage
function newPET( uint256 _planId, uint256 _monthlyCommitmentAmount ) public { require( petPlans[_planId].isPlanActive , 'PET plan is not active' ); require( _monthlyCommitmentAmount >= petPlans[_planId].minimumMonthlyCommitmentAmount , 'low monthlyCommitmentAmount' ); pets[msg.sender].push(PET({ planId: _planId, monthlyCommitmentAmount: _monthlyCommitmentAmount, initTimestamp: now, lastAnnuityWithdrawlMonthId: 0, appointeeVotes: 0, numberOfAppointees: 0 })); msg.sender, pets[msg.sender].length - 1, _monthlyCommitmentAmount ); }
12,883,705
./full_match/5/0xD80Fe76E599505DcC553620eEC6F138af719Af6b/sources/contracts/CompanyReceipts.sol
RECEIPT FUNCTIONS Function for a company to issue a receipt Calculate the total
function issueReceipt( string[] memory _names, uint256[] memory _prices, uint256[] memory _quantities ) public returns (Receipt memory, string memory companyName) { Company storage company = companies[msg.sender]; require(company.approved, "Company not approved"); require( _names.length == _prices.length && _names.length == _quantities.length, "Data arrays provided are not of equal length!" ); uint256 _saleAmount = 0; for (uint i = 0; i < _prices.length; i++) { _saleAmount += _prices[i] * _quantities[i]; } Receipt storage receipt = receipts[receiptId]; receipt.company = msg.sender; receipt.saleDate = block.timestamp; receipt.itemNames = _names; receipt.itemPrices = _prices; receipt.itemQuantities = _quantities; company.monthlySales[getMonth(block.timestamp)] += _saleAmount; emit ReceiptIssued(msg.sender, receiptId, block.timestamp); return getReceipt(receiptId); }
1,874,052
// File: zos-lib/contracts/Initializable.sol pragma solidity >=0.4.24 <0.6.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ 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 use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. uint256 cs; assembly { cs := extcodesize(address) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: openzeppelin-eth/contracts/ownership/Ownable.sol pragma solidity ^0.4.24; /** * @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 is Initializable { address private _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. */ function initialize(address sender) public initializer { _owner = sender; } /** * @return the address of the owner. */ function owner() public view returns(address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns(bool) { return 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; } uint256[50] private ______gap; } // File: contracts/lib/SafeMathInt.sol /* MIT License Copyright (c) 2018 requestnetwork Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity >=0.4.24; /** * @title SafeMathInt * @dev Math operations for int256 with overflow safety checks. */ library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two int256 variables and fails on overflow. */ 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; } /** * @dev Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } } // File: contracts/lib/UInt256Lib.sol pragma solidity >=0.4.24; /** * @title Various utilities useful for uint256. */ library UInt256Lib { uint256 private constant MAX_INT256 = ~(uint256(1) << 255); /** * @dev Safely converts a uint256 to an int256. */ function toInt256Safe(uint256 a) internal pure returns (int256) { require(a <= MAX_INT256); return int256(a); } } // File: contracts/interface/ISeignorageShares.sol pragma solidity >=0.4.24; interface ISeigniorageShares { function setDividendPoints(address account, uint256 totalDividends) external returns (bool); function mintShares(address account, uint256 amount) external returns (bool); function lastDividendPoints(address who) external view returns (uint256); function externalRawBalanceOf(address who) external view returns (uint256); function externalTotalSupply() external view returns (uint256); } // File: openzeppelin-eth/contracts/math/SafeMath.sol pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on 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-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts 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; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: openzeppelin-eth/contracts/token/ERC20/IERC20.sol pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: openzeppelin-eth/contracts/token/ERC20/ERC20Detailed.sol pragma solidity ^0.4.24; /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract ERC20Detailed is Initializable, IERC20 { string private _name; string private _symbol; uint8 private _decimals; function initialize(string name, string symbol, uint8 decimals) public initializer { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns(string) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns(string) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns(uint8) { return _decimals; } uint256[50] private ______gap; } // File: contracts/dollars.sol pragma solidity >=0.4.24; interface IDollarPolicy { function getUsdSharePrice() external view returns (uint256 price); } /* * Dollar ERC20 */ contract Dollars is ERC20Detailed, Ownable { using SafeMath for uint256; using SafeMathInt for int256; event LogRebase(uint256 indexed epoch, uint256 totalSupply); event LogContraction(uint256 indexed epoch, uint256 dollarsToBurn); event LogRebasePaused(bool paused); event LogBurn(address indexed from, uint256 value); event LogClaim(address indexed from, uint256 value); event LogMonetaryPolicyUpdated(address monetaryPolicy); // Used for authentication address public monetaryPolicy; address public sharesAddress; modifier onlyMonetaryPolicy() { require(msg.sender == monetaryPolicy); _; } // Precautionary emergency controls. bool public rebasePaused; modifier whenRebaseNotPaused() { require(!rebasePaused); _; } // coins needing to be burned (9 decimals) uint256 private _remainingDollarsToBeBurned; modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); _; } uint256 private constant DECIMALS = 9; uint256 private constant MAX_UINT256 = ~uint256(0); uint256 private constant INITIAL_DOLLAR_SUPPLY = 1 * 10**6 * 10**DECIMALS; uint256 private _maxDiscount; modifier validDiscount(uint256 discount) { require(discount >= 0, 'POSITIVE_DISCOUNT'); // 0% require(discount <= _maxDiscount, 'DISCOUNT_TOO_HIGH'); _; } uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1 uint256 private _totalSupply; uint256 private constant POINT_MULTIPLIER = 10 ** 9; uint256 private _totalDividendPoints; uint256 private _unclaimedDividends; ISeigniorageShares Shares; mapping(address => uint256) private _dollarBalances; // This is denominated in Dollars, because the cents-dollars conversion might change before // it's fully paid. mapping (address => mapping (address => uint256)) private _allowedDollars; IDollarPolicy DollarPolicy; uint256 public burningDiscount; // percentage (10 ** 9 Decimals) uint256 public defaultDiscount; // discount on first negative rebase uint256 public defaultDailyBonusDiscount; // how much the discount increases per day for consecutive contractions uint256 public minimumBonusThreshold; bool reEntrancyMutex; /** * @param monetaryPolicy_ The address of the monetary policy contract to use for authentication. */ function setMonetaryPolicy(address monetaryPolicy_) external onlyOwner { monetaryPolicy = monetaryPolicy_; DollarPolicy = IDollarPolicy(monetaryPolicy_); emit LogMonetaryPolicyUpdated(monetaryPolicy_); } function setBurningDiscount(uint256 discount) external onlyOwner validDiscount(discount) { burningDiscount = discount; } function setMutex(bool _val) external onlyOwner { reEntrancyMutex = _val; } function setDefaultDiscount(uint256 discount) external onlyOwner validDiscount(discount) { defaultDiscount = discount; } function setMaxDiscount(uint256 discount) external onlyOwner { _maxDiscount = discount; } function setDefaultDailyBonusDiscount(uint256 discount) external onlyOwner validDiscount(discount) { defaultDailyBonusDiscount = discount; } /** * @dev Pauses or unpauses the execution of rebase operations. * @param paused Pauses rebase operations if this is true. */ function setRebasePaused(bool paused) external onlyOwner { rebasePaused = paused; emit LogRebasePaused(paused); } // action of claiming funds function claimDividends(address account) external updateAccount(account) returns (uint256) { uint256 owing = dividendsOwing(account); return owing; } function setMinimumBonusThreshold(uint256 minimum) external onlyOwner { require(minimum >= 0, 'POSITIVE_MINIMUM'); require(minimum < _totalSupply, 'MINIMUM_TOO_HIGH'); minimumBonusThreshold = minimum; } /** * @dev Notifies Dollars contract about a new rebase cycle. * @param supplyDelta The number of new dollar tokens to add into circulation via expansion. * @return The total number of dollars after the supply adjustment. */ function rebase(uint256 epoch, int256 supplyDelta) external onlyMonetaryPolicy whenRebaseNotPaused returns (uint256) { if (supplyDelta == 0) { emit LogRebase(epoch, _totalSupply); return _totalSupply; } if (supplyDelta < 0) { uint256 dollarsToBurn = uint256(supplyDelta.abs()); if (dollarsToBurn > _totalSupply.div(10)) { // maximum contraction is 10% of the total USD Supply dollarsToBurn = _totalSupply.div(10); } if (dollarsToBurn.add(_remainingDollarsToBeBurned) > _totalSupply) { dollarsToBurn = _totalSupply.sub(_remainingDollarsToBeBurned); } if (_remainingDollarsToBeBurned > minimumBonusThreshold) { burningDiscount = burningDiscount.add(defaultDailyBonusDiscount) > _maxDiscount ? _maxDiscount : burningDiscount.add(defaultDailyBonusDiscount); } else { burningDiscount = defaultDiscount; // default 1% } _remainingDollarsToBeBurned = _remainingDollarsToBeBurned.add(dollarsToBurn); emit LogContraction(epoch, dollarsToBurn); } else { disburse(uint256(supplyDelta)); emit LogRebase(epoch, _totalSupply); if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } } return _totalSupply; } function initialize(address owner_, address seigniorageAddress) public initializer { ERC20Detailed.initialize("Dollars", "USD", uint8(DECIMALS)); Ownable.initialize(owner_); rebasePaused = false; _totalSupply = INITIAL_DOLLAR_SUPPLY; sharesAddress = seigniorageAddress; Shares = ISeigniorageShares(seigniorageAddress); _dollarBalances[owner_] = _totalSupply; _maxDiscount = 50 * 10 ** 9; // 50% defaultDiscount = 1 * 10 ** 9; // 1% burningDiscount = defaultDiscount; defaultDailyBonusDiscount = 1 * 10 ** 9; // 1% minimumBonusThreshold = 100 * 10 ** 9; // 100 dollars is the minimum threshold. Anything above warrants increased discount emit Transfer(address(0x0), owner_, _totalSupply); } function dividendsOwing(address account) public view returns (uint256) { if (_totalDividendPoints > Shares.lastDividendPoints(account)) { uint256 newDividendPoints = _totalDividendPoints.sub(Shares.lastDividendPoints(account)); uint256 sharesBalance = Shares.externalRawBalanceOf(account); return sharesBalance.mul(newDividendPoints).div(POINT_MULTIPLIER); } else { return 0; } } // auto claim modifier // if user is owned, we pay out immedietly // if user is not owned, we prevent them from claiming until the next rebase modifier updateAccount(address account) { require(!reEntrancyMutex); reEntrancyMutex = true; uint256 owing = dividendsOwing(account); if (owing > 0) { _unclaimedDividends = _unclaimedDividends.sub(owing); _dollarBalances[account] += owing; } Shares.setDividendPoints(account, _totalDividendPoints); reEntrancyMutex = false; emit LogClaim(account, owing); _; } /** * @return The total number of dollars. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) public view returns (uint256) { return _dollarBalances[who].add(dividendsOwing(who)); } function getRemainingDollarsToBeBurned() public view returns (uint256) { return _remainingDollarsToBeBurned; } /** * @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) public validRecipient(to) updateAccount(msg.sender) updateAccount(to) returns (bool) { _dollarBalances[msg.sender] = _dollarBalances[msg.sender].sub(value); _dollarBalances[to] = _dollarBalances[to].add(value); emit Transfer(msg.sender, to, value); return true; } /** * @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) public view returns (uint256) { return _allowedDollars[owner_][spender]; } /** * @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) public validRecipient(to) updateAccount(from) updateAccount(msg.sender) updateAccount(to) returns (bool) { _allowedDollars[from][msg.sender] = _allowedDollars[from][msg.sender].sub(value); _dollarBalances[from] = _dollarBalances[from].sub(value); _dollarBalances[to] = _dollarBalances[to].add(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. 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) public validRecipient(spender) updateAccount(msg.sender) updateAccount(spender) returns (bool) { _allowedDollars[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) public updateAccount(msg.sender) updateAccount(spender) returns (bool) { _allowedDollars[msg.sender][spender] = _allowedDollars[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedDollars[msg.sender][spender]); return true; } // amount in is 10 ** 9 decimals function burn(uint256 amount) public updateAccount(msg.sender) { require(amount > 0, 'AMOUNT_MUST_BE_POSITIVE'); require(burningDiscount >= 0, 'DISCOUNT_NOT_VALID'); require(_remainingDollarsToBeBurned > 0, 'COIN_BURN_MUST_BE_GREATER_THAN_ZERO'); require(amount <= _dollarBalances[msg.sender], 'INSUFFICIENT_DOLLAR_BALANCE'); require(amount <= _remainingDollarsToBeBurned, 'AMOUNT_MUST_BE_LESS_THAN_OR_EQUAL_TO_REMAINING_COINS'); _burn(msg.sender, amount); } /** * @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) public updateAccount(spender) updateAccount(msg.sender) returns (bool) { uint256 oldValue = _allowedDollars[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedDollars[msg.sender][spender] = 0; } else { _allowedDollars[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedDollars[msg.sender][spender]); return true; } function consultBurn(uint256 amount) public returns (uint256) { require(amount > 0, 'AMOUNT_MUST_BE_POSITIVE'); require(burningDiscount >= 0, 'DISCOUNT_NOT_VALID'); require(_remainingDollarsToBeBurned > 0, 'COIN_BURN_MUST_BE_GREATER_THAN_ZERO'); require(amount <= _dollarBalances[msg.sender].add(dividendsOwing(msg.sender)), 'INSUFFICIENT_DOLLAR_BALANCE'); require(amount <= _remainingDollarsToBeBurned, 'AMOUNT_MUST_BE_LESS_THAN_OR_EQUAL_TO_REMAINING_COINS'); uint256 usdPerShare = DollarPolicy.getUsdSharePrice(); // 1 share = x dollars usdPerShare = usdPerShare.sub(usdPerShare.mul(burningDiscount).div(100 * 10 ** 9)); // 10^9 uint256 sharesToMint = amount.mul(10 ** 9).div(usdPerShare); // 10^9 return sharesToMint; } function unclaimedDividends() public view returns (uint256) { return _unclaimedDividends; } function totalDividendPoints() public view returns (uint256) { return _totalDividendPoints; } function disburse(uint256 amount) internal returns (bool) { _totalDividendPoints = _totalDividendPoints.add(amount.mul(POINT_MULTIPLIER).div(Shares.externalTotalSupply())); _totalSupply = _totalSupply.add(amount); _unclaimedDividends = _unclaimedDividends.add(amount); return true; } function _burn(address account, uint256 amount) internal { require(!reEntrancyMutex); _totalSupply = _totalSupply.sub(amount); _dollarBalances[account] = _dollarBalances[account].sub(amount); reEntrancyMutex = true; uint256 usdPerShare = DollarPolicy.getUsdSharePrice(); // 1 share = x dollars usdPerShare = usdPerShare.sub(usdPerShare.mul(burningDiscount).div(100 * 10 ** 9)); // 10^9 uint256 sharesToMint = amount.mul(10 ** 9).div(usdPerShare); // 10^9 Shares.mintShares(account, sharesToMint); _remainingDollarsToBeBurned = _remainingDollarsToBeBurned.sub(amount); reEntrancyMutex = false; emit Transfer(account, address(0), amount); emit LogBurn(account, amount); } } // File: contracts/dollarsPolicy.sol pragma solidity >=0.4.24; /* * Dollar Policy */ interface IDecentralizedOracle { function update() external; function consult(address token, uint amountIn) external view returns (uint amountOut); } contract DollarsPolicy is Ownable { using SafeMath for uint256; using SafeMathInt for int256; using UInt256Lib for uint256; event LogRebase( uint256 indexed epoch, uint256 exchangeRate, uint256 cpi, int256 requestedSupplyAdjustment, uint256 timestampSec ); Dollars public dollars; // Provides the current CPI, as an 18 decimal fixed point number. IDecentralizedOracle public sharesPerUsdOracle; IDecentralizedOracle public ethPerUsdOracle; IDecentralizedOracle public ethPerUsdcOracle; uint256 public deviationThreshold; uint256 public rebaseLag; uint256 private cpi; uint256 public minRebaseTimeIntervalSec; uint256 public lastRebaseTimestampSec; uint256 public rebaseWindowOffsetSec; uint256 public rebaseWindowLengthSec; uint256 public epoch; address WETH_ADDRESS; address SHARE_ADDRESS; uint256 private constant DECIMALS = 18; uint256 private constant MAX_RATE = 10**6 * 10**DECIMALS; uint256 private constant MAX_SUPPLY = ~(uint256(1) << 255) / MAX_RATE; address public orchestrator; bool private initializedOracle; modifier onlyOrchestrator() { require(msg.sender == orchestrator); _; } function getUsdSharePrice() external view returns (uint256) { sharesPerUsdOracle.update(); uint256 sharePrice = sharesPerUsdOracle.consult(SHARE_ADDRESS, 1 * 10 ** 9); // 10^9 decimals return sharePrice; } function rebase() external onlyOrchestrator { require(inRebaseWindow()); require(initializedOracle == true, 'ORACLE_NOT_INITIALIZED'); require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now); lastRebaseTimestampSec = now.sub( now.mod(minRebaseTimeIntervalSec)).add(rebaseWindowOffsetSec); epoch = epoch.add(1); sharesPerUsdOracle.update(); ethPerUsdOracle.update(); ethPerUsdcOracle.update(); uint256 ethUsdcPrice = ethPerUsdcOracle.consult(WETH_ADDRESS, 1 * 10 ** 18); // 10^18 decimals ropsten, 10^6 mainnet uint256 ethUsdPrice = ethPerUsdOracle.consult(WETH_ADDRESS, 1 * 10 ** 18); // 10^9 decimals uint256 dollarCoinExchangeRate = ethUsdcPrice.mul(10 ** 21) // 10^18 decimals, 10**9 ropsten, 10**21 on mainnet .div(ethUsdPrice); uint256 sharePrice = sharesPerUsdOracle.consult(SHARE_ADDRESS, 1 * 10 ** 9); // 10^9 decimals uint256 shareExchangeRate = sharePrice.mul(dollarCoinExchangeRate).div(10 ** 9); // 10^18 decimals uint256 targetRate = cpi; if (dollarCoinExchangeRate > MAX_RATE) { dollarCoinExchangeRate = MAX_RATE; } // dollarCoinExchangeRate & targetRate arre 10^18 decimals int256 supplyDelta = computeSupplyDelta(dollarCoinExchangeRate, targetRate); // supplyDelta = 10^9 decimals // Apply the Dampening factor. supplyDelta = supplyDelta.div(rebaseLag.toInt256Safe()); // check on the expansionary side if (supplyDelta > 0 && dollars.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) { supplyDelta = (MAX_SUPPLY.sub(dollars.totalSupply())).toInt256Safe(); } // check on the contraction side if (supplyDelta < 0 && dollars.getRemainingDollarsToBeBurned().add(uint256(supplyDelta.abs())) > MAX_SUPPLY) { supplyDelta = (MAX_SUPPLY.sub(dollars.getRemainingDollarsToBeBurned())).toInt256Safe(); } uint256 supplyAfterRebase; if (supplyDelta < 0) { // contraction, we send the amount of shares to mint uint256 sharesToMint = uint256(supplyDelta.abs()); supplyAfterRebase = dollars.rebase(epoch, (sharesToMint).toInt256Safe().mul(-1)); } else { // expansion, we send the amount of dollars to mint supplyAfterRebase = dollars.rebase(epoch, supplyDelta); } assert(supplyAfterRebase <= MAX_SUPPLY); emit LogRebase(epoch, dollarCoinExchangeRate, cpi, supplyDelta, now); } function setOrchestrator(address orchestrator_) external onlyOwner { orchestrator = orchestrator_; } function setDeviationThreshold(uint256 deviationThreshold_) external onlyOwner { deviationThreshold = deviationThreshold_; } function setCpi(uint256 cpi_) external onlyOwner { require(cpi_ > 0); cpi = cpi_; } function setRebaseLag(uint256 rebaseLag_) external onlyOwner { require(rebaseLag_ > 0); rebaseLag = rebaseLag_; } function initializeOracles( address sharesPerUsdOracleAddress, address ethPerUsdOracleAddress, address ethPerUsdcOracleAddress ) external onlyOwner { require(initializedOracle == false, 'ALREADY_INITIALIZED_ORACLE'); sharesPerUsdOracle = IDecentralizedOracle(sharesPerUsdOracleAddress); ethPerUsdOracle = IDecentralizedOracle(ethPerUsdOracleAddress); ethPerUsdcOracle = IDecentralizedOracle(ethPerUsdcOracleAddress); initializedOracle = true; } function changeOracles( address sharesPerUsdOracleAddress, address ethPerUsdOracleAddress, address ethPerUsdcOracleAddress ) external onlyOwner { sharesPerUsdOracle = IDecentralizedOracle(sharesPerUsdOracleAddress); ethPerUsdOracle = IDecentralizedOracle(ethPerUsdOracleAddress); ethPerUsdcOracle = IDecentralizedOracle(ethPerUsdcOracleAddress); } function setWethAddress(address wethAddress) external onlyOwner { WETH_ADDRESS = wethAddress; } function setShareAddress(address shareAddress) external onlyOwner { SHARE_ADDRESS = shareAddress; } function setRebaseTimingParameters( uint256 minRebaseTimeIntervalSec_, uint256 rebaseWindowOffsetSec_, uint256 rebaseWindowLengthSec_) external onlyOwner { require(minRebaseTimeIntervalSec_ > 0); require(rebaseWindowOffsetSec_ < minRebaseTimeIntervalSec_); minRebaseTimeIntervalSec = minRebaseTimeIntervalSec_; rebaseWindowOffsetSec = rebaseWindowOffsetSec_; rebaseWindowLengthSec = rebaseWindowLengthSec_; } function initialize(address owner_, Dollars dollars_) public initializer { Ownable.initialize(owner_); deviationThreshold = 5 * 10 ** (DECIMALS-2); rebaseLag = 50; minRebaseTimeIntervalSec = 1 days; rebaseWindowOffsetSec = 63000; // with stock market, 63000 for 1:30pm EST (debug) rebaseWindowLengthSec = 15 minutes; lastRebaseTimestampSec = 0; cpi = 1 * 10 ** 18; epoch = 0; dollars = dollars_; } function inRebaseWindow() public view returns (bool) { return ( now.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec && now.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec)) ); } function computeSupplyDelta(uint256 rate, uint256 targetRate) private view returns (int256) { if (withinDeviationThreshold(rate, targetRate)) { return 0; } int256 targetRateSigned = targetRate.toInt256Safe(); return dollars.totalSupply().toInt256Safe() .mul(rate.toInt256Safe().sub(targetRateSigned)) .div(targetRateSigned); } function withinDeviationThreshold(uint256 rate, uint256 targetRate) private view returns (bool) { uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold) .div(10 ** DECIMALS); return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold) || (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold); } } // File: contracts/orchestrator.sol pragma solidity >=0.4.24; /* * Orchestrator */ contract Orchestrator is Ownable { struct Transaction { bool enabled; address destination; bytes data; } event TransactionFailed(address indexed destination, uint index, bytes data); Transaction[] public transactions; DollarsPolicy public policy; constructor(address policy_) public { Ownable.initialize(msg.sender); policy = DollarsPolicy(policy_); } function rebase() external { require(msg.sender == tx.origin); // solhint-disable-line avoid-tx-origin policy.rebase(); for (uint i = 0; i < transactions.length; i++) { Transaction storage t = transactions[i]; if (t.enabled) { bool result = externalCall(t.destination, t.data); if (!result) { emit TransactionFailed(t.destination, i, t.data); revert("Transaction Failed"); } } } } function addTransaction(address destination, bytes data) external onlyOwner { transactions.push(Transaction({ enabled: true, destination: destination, data: data })); } function removeTransaction(uint index) external onlyOwner { require(index < transactions.length, "index out of bounds"); if (index < transactions.length - 1) { transactions[index] = transactions[transactions.length - 1]; } transactions.length--; } function setTransactionEnabled(uint index, bool enabled) external onlyOwner { require(index < transactions.length, "index must be in range of stored tx list"); transactions[index].enabled = enabled; } function transactionsSize() external view returns (uint256) { return transactions.length; } function externalCall(address destination, bytes data) internal returns (bool) { bool result; assembly { // solhint-disable-line no-inline-assembly // "Allocate" memory for output // (0x40 is where "free memory" pointer is stored by convention) let outputAddress := mload(0x40) // First 32 bytes are the padded length of data, so exclude that let dataAddress := add(data, 32) result := call( // 34710 is the value that solidity is currently emitting // It includes callGas (700) + callVeryLow (3, to pay for SUB) // + callValueTransferGas (9000) + callNewAccountGas // (25000, in case the destination address does not exist and needs creating) sub(gas, 34710), destination, 0, // transfer value in wei dataAddress, mload(data), // Size of the input, in bytes. Stored in position 0 of the array. outputAddress, 0 // Output is ignored, therefore the output size is zero ) } return result; } }
Decrease the amount of tokens that an owner has allowed to a spender. spender The address which will spend the funds. subtractedValue The amount of tokens to decrease the allowance by./
{ uint256 oldValue = _allowedDollars[msg.sender][spender]; function totalSupply() public view returns (uint256) } function balanceOf(address who) public view returns (uint256) } function getRemainingDollarsToBeBurned() public view returns (uint256) } function transfer(address to, uint256 value) public validRecipient(to) updateAccount(msg.sender) updateAccount(to) returns (bool) } function allowance(address owner_, address spender) public view returns (uint256) } function transferFrom(address from, address to, uint256 value) public validRecipient(to) updateAccount(from) updateAccount(msg.sender) updateAccount(to) returns (bool) } function approve(address spender, uint256 value) public validRecipient(spender) updateAccount(msg.sender) updateAccount(spender) returns (bool) } function increaseAllowance(address spender, uint256 addedValue) public updateAccount(msg.sender) updateAccount(spender) returns (bool) } } function decreaseAllowance(address spender, uint256 subtractedValue) public updateAccount(spender) updateAccount(msg.sender) returns (bool) if (subtractedValue >= oldValue) { _allowedDollars[msg.sender][spender] = 0; _allowedDollars[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedDollars[msg.sender][spender]); return true; } else { }
434,491
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; interface IYakuzaKummiai { function mintTo(address _to, uint256 tokenId) external; function setBaseTokenURI(string memory _baseTokenURI) external; } contract YakuzaKumiaiSale is AccessControl { using Strings for string; uint256 constant public totalSales = 8930; uint256 constant public preSale1Count = 1024; uint256 constant public preSale2Count = 30; uint256 public maxPreSale1MintPerWallet = 2; uint256 public maxPreSale2MintPerWallet = 1; uint256 public maxPreSale3MintPerWallet = 20; uint256 constant public maxPublicSaleMintPerWallet = 25; uint256 constant public preSale1Start = 1648954800; // 4.3, 12 pm JST uint256 constant public preSale1End = 1649127600; // 4.5, 12 pm JST uint256 constant public preSale2Start = 1649170800; // 4.6, 12 am JST uint256 constant public preSale2End = 1649214000; // 4.6, 12 pm JST uint256 constant public preSale3Start = 1649257200; // 4.7, 12 am JST uint256 constant public preSale3End = 1649390400; // 4.8, 12 pm JST uint256 constant public publicSaleStart = 1649516400; // 4.10 12 am JST uint256 constant public preSale1MintFee = 0.01 ether; uint256 constant public preSale2MintFee = 0.02 ether; uint256 constant public publicSaleMintFee = 0.07 ether; // roles bytes32 public constant WITHDRAWER_ROLE = keccak256("WITHDRAWER"); bytes32 public constant ADMIN = keccak256("ADMIN"); bytes32 public merkleRootWL1 = 0xb5d235c7dc95984c578f696a365fc833e64459b72a1c5304d1c105ec6822d59b; bytes32 public merkleRootWL2 = 0xb5d235c7dc95984c578f696a365fc833e64459b72a1c5304d1c105ec6822d59b; address payable public wallet1 = payable(0x192F6CCD0b9bd54bdA1A7e3776b718F908028EC4); // wallet address for accounts payable and marketing address payable public wallet2 = payable(0x8d6AE8FE3A583A0B60cF7670332726b9bb30A507); // wallet address for giveaway address payable public wallet3 = payable(0xd5a5c1B25EdB13ED2737247B0a7E0578705bEBe9); // wallet address for tool development address payable public wallet4 = payable(0x8C06E7617575576a26954779fbB58a467faa6f16); // wallet address for anime studio address payable public wallet5 = payable(0x80c1c51dD714d42A93E70e4544007984079EBE0B); // wallet address for dev team address payable public wallet6 = payable(0x7b62AC97F6a9Fb98Ec7F48EAA109014C1B685A95); // wallet address for addy (lead developer) address public nftAddress; mapping (address => uint256) public mintedTokens; uint256 totalMints = 0; uint256 marketWithdrawlAmount = 0 ether; modifier onlyAdmin() { require(hasRole(ADMIN, msg.sender), "Access is allowed for only ADMIN"); _; } constructor(address _nftAddress) { nftAddress = _nftAddress; _grantRole(ADMIN, msg.sender); } /// @notice Update the base Uri /// @param _baseTokenURI baseTokenURI function setBaseTokenURI(string memory _baseTokenURI) external onlyAdmin { IYakuzaKummiai(nftAddress).setBaseTokenURI(_baseTokenURI); } /// @notice Update the whitelist1 function updateMerkleRootWL1(bytes32 _merkleRootWl) external onlyAdmin { merkleRootWL1 = _merkleRootWl; } /// @notice Update the whitelist2 function updateMerkleRootWL2(bytes32 _merkleRootWl) external onlyAdmin { merkleRootWL2 = _merkleRootWl; } /// @notice Update the wallet address of funders /// @param _walletName wallet name to update /// @param _address wallet address function updateWalletAddress(string memory _walletName, address _address) external onlyAdmin { if (keccak256(abi.encodePacked(_walletName)) == keccak256(abi.encodePacked("wallet1")) ) { wallet1 = payable(_address); } if (keccak256(abi.encodePacked(_walletName)) == keccak256(abi.encodePacked("wallet2"))) { wallet2 = payable(_address); } if (keccak256(abi.encodePacked(_walletName)) == keccak256(abi.encodePacked("wallet3"))) { wallet3 = payable(_address); } if (keccak256(abi.encodePacked(_walletName)) == keccak256(abi.encodePacked("wallet4"))) { wallet4 = payable(_address); } if (keccak256(abi.encodePacked(_walletName)) == keccak256(abi.encodePacked("wallet5"))) { wallet5 = payable(_address); } } /// @notice get the wallet list function getWalletList(string memory _walletName) public view onlyAdmin returns (address) { if (keccak256(abi.encodePacked(_walletName)) == keccak256(abi.encodePacked("wallet1")) ) { return wallet1; } if (keccak256(abi.encodePacked(_walletName)) == keccak256(abi.encodePacked("wallet2"))) { return wallet2; } if (keccak256(abi.encodePacked(_walletName)) == keccak256(abi.encodePacked("wallet3"))) { return wallet3; } if (keccak256(abi.encodePacked(_walletName)) == keccak256(abi.encodePacked("wallet4"))) { return wallet4; } if (keccak256(abi.encodePacked(_walletName)) == keccak256(abi.encodePacked("wallet5"))) { return wallet5; } return wallet2; } /// @notice Get max count per wallet for presale function getPreSaleMintAmount() public view returns (uint256) { return maxPreSale1MintPerWallet; } /// @notice Main mint function /// @param _to mint address /// @param _count nft count to mint function _mint(address _to, uint256 _count) internal { require(totalMints + _count <= totalSales, "PS: Exceeds total sales"); totalMints += _count; IYakuzaKummiai(nftAddress).mintTo(_to, _count); mintedTokens[_to] += _count; } /// @notice Check if presale is finished function isPresale1Finished() public view returns (bool) { return block.timestamp > preSale1End || totalMints >= preSale1Count; } /// @notice Check if presale is finished function isPresale2Finished() public view returns (bool) { return block.timestamp > preSale2End || totalMints >= preSale1Count + preSale2Count; } /// @notice Check if presale is finished function isPresale3Finished() public view returns (bool) { return block.timestamp > preSale3End || totalMints >= preSale1Count + preSale2Count; } /// @notice Check if balance is available for withdrawal function isWithdraw() internal view returns (bool) { uint256 total = address(this).balance; if (total < 0) { return false; } return true; } /// @notice Mint function for public sale /// @param _to mint address /// @param _count token count to mint function mint(address _to, uint256 _count) external payable { require(block.timestamp >= publicSaleStart, "PS: Public sale is not started"); require(msg.value >= publicSaleMintFee * _count, "PS: Not enough funds sent"); require(mintedTokens[_to] + _count <= maxPublicSaleMintPerWallet, "PS: Max limited per wallet"); _mint(_to, _count); } /// @notice Mint function for presale1 function whiteListMint1(bytes32[] calldata _merkleProof, address _to, uint256 _count) external payable{ require(block.timestamp >= preSale1Start, "PS: Presale1 is not started yet" ); require(!isPresale1Finished(), "PS: Presale1 Finished"); require(mintedTokens[_to] + _count <= maxPreSale1MintPerWallet, "PS: Max limited per wallet"); require(msg.value >= preSale1MintFee * _count, "PS: Not enough funds sent"); bytes32 leaf = keccak256(abi.encodePacked(_to)); require(MerkleProof.verify(_merkleProof, merkleRootWL1, leaf), "PS: Failed to verify WhiteList"); _mint(_to, _count); } /// @notice Mint function for presale2 function whiteListMint2(bytes32[] calldata _merkleProof, address _to, uint256 _count) external payable{ require(block.timestamp >= preSale2Start, "PS: Presale2 is not started yet" ); require(!isPresale2Finished(), "PS: Presale2 Finished"); require(mintedTokens[_to] + _count <= maxPreSale2MintPerWallet, "PS: Max limited per wallet"); require(msg.value >= preSale2MintFee * _count, "PS: Not enough funds sent"); bytes32 leaf = keccak256(abi.encodePacked(_to)); require(MerkleProof.verify(_merkleProof, merkleRootWL2, leaf), "PS: Failed to verify WhiteList"); _mint(_to, _count); } /// @notice Mint function for presale2 function whiteListMint3(bytes32[] calldata _merkleProof, address _to, uint256 _count) external payable{ require(block.timestamp >= preSale3Start, "PS: Presale3 is not started yet" ); require(!isPresale3Finished(), "PS: Presale3 Finished"); require(mintedTokens[_to] + _count <= maxPreSale3MintPerWallet, "PS: Max limited per wallet"); require(msg.value >= preSale2MintFee * _count, "PS: Not enough funds sent"); bytes32 leaf = keccak256(abi.encodePacked(_to)); require(MerkleProof.verify(_merkleProof, merkleRootWL1, leaf) || MerkleProof.verify(_merkleProof, merkleRootWL2, leaf), "PS: Failed to verify WhiteList"); _mint(_to, _count); } /// @notice Withdraw funds for marketing function withdrawToMarketingFunder() public payable onlyAdmin { require(isWithdraw(), "PS: Not enough funds to widthdraw"); require( marketWithdrawlAmount < 50 ether, "PS: Marketing funds has already been finished"); uint256 total = address(this).balance; // wallet1.transfer(total); uint256 restAmount = 50 ether - marketWithdrawlAmount; if (total > restAmount) { marketWithdrawlAmount += restAmount; wallet1.transfer(restAmount); } else { marketWithdrawlAmount += total; wallet1.transfer(total); } } /// @notice Distribute the funds to team members function withdrawToFounders() public payable onlyAdmin { require(isWithdraw(), "PS: Not enough funds to split"); require( marketWithdrawlAmount >= 50 ether, "PS: Marketing funds is not finished yet!"); uint256 total = address(this).balance; wallet2.transfer(total * 1967 / 10000); wallet3.transfer(total * 2951 / 10000); wallet4.transfer(total * 2951 / 10000); wallet5.transfer(total * 1948 / 10000); wallet6.transfer(total * 184 / 10000); } /// @notice Grants the withdrawer role /// @param _role Role which needs to be assigned /// @param _user Address of the new withdrawer function grantRole(bytes32 _role, address _user) public override onlyAdmin { _grantRole(_role, _user); } /// @notice Revokes the withdrawer role /// @param _role Role which needs to be revoked /// @param _user Address which we want to revoke function revokeRole(bytes32 _role, address _user) public override onlyAdmin { _revokeRole(_role, _user); } function withdrawl() public payable onlyAdmin { require(isWithdraw(), "PS: Not enough funds to split"); uint256 total = address(this).balance; wallet1.transfer(total); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _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); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { 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); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @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 AccessControl is Context, IAccessControl, ERC165 { 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(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual 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 virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.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 virtual 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 revoked `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}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ 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); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @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; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @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 ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
Mint function for presale1
function whiteListMint1(bytes32[] calldata _merkleProof, address _to, uint256 _count) external payable{ require(block.timestamp >= preSale1Start, "PS: Presale1 is not started yet" ); require(!isPresale1Finished(), "PS: Presale1 Finished"); require(mintedTokens[_to] + _count <= maxPreSale1MintPerWallet, "PS: Max limited per wallet"); require(msg.value >= preSale1MintFee * _count, "PS: Not enough funds sent"); bytes32 leaf = keccak256(abi.encodePacked(_to)); require(MerkleProof.verify(_merkleProof, merkleRootWL1, leaf), "PS: Failed to verify WhiteList"); _mint(_to, _count); }
14,487,595
// SPDX-License-Identifier: MIT // ENVELOP (NIFTSY) protocol for NFT. Wrapper & Distributor contract pragma solidity ^0.8.6; import "WrapperWithERC20Collateral.sol"; import "IERC721Mintable.sol"; /** * @title ERC-721 Non-Fungible Token Wrapper * @dev For wrpap existing ERC721 with ability add ERC20 collateral */ contract WrapperDistributor721 is WrapperWithERC20Collateral { using SafeERC20 for IERC20; using ERC165Checker for address; mapping(address => bool) public distributors; event GasLimit(uint256 wrappedAmountCount, address lastReceiver); constructor (address _erc20) WrapperWithERC20Collateral(_erc20) { distributors[msg.sender] = true; } /// !!!!For gas safe this low levelfunction has NO any check before wrap /// So you have NO warranty to do Unwrap well function WrapAndDistrib721WithMint( address _original721, address[] memory _receivers, uint256[] memory _tokenIds, ERC20Collateral[] memory _forDistrib, uint256 _unwrapAfter ) public payable { require(distributors[msg.sender], "Only for distributors"); //require(_receivers.length <= 256, "Not more 256"); require(_receivers.length == _tokenIds.length, "Not equal arrays"); // topup wrapper contract with erc20 that would be added in collateral for (uint8 i = 0; i < _forDistrib.length; i ++) { IERC20(_forDistrib[i].erc20Token).safeTransferFrom( msg.sender, address(this), _forDistrib[i].amount * _receivers.length ); } for (uint8 i = 0; i < _receivers.length; i ++) { // 1. Lits mint 721, but for gas save we will not do it for receiver // but wrapper contract as part of wrapp process IERC721Mintable(_original721).mint(address(this), _tokenIds[i]); // 2.Mint wrapped NFT for receiver and populate storage lastWrappedNFTId += 1; _mint(_receivers[i], lastWrappedNFTId); wrappedTokens[lastWrappedNFTId] = NFT( _original721, _tokenIds[i], msg.value / _receivers.length, // native blockchain asset 0, // accumalated fee token _unwrapAfter, // timelock 0, //_transferFee, address(0), // _royaltyBeneficiary, 0, //_royaltyPercent, 0, //_unwraptFeeThreshold, address(0), //_transferFeeToken, AssetType.ERC721, 0 ); // 3.Add erc20 collateral ERC20Collateral[] storage coll = erc20Collateral[lastWrappedNFTId]; for (uint8 j = 0; j < _forDistrib.length; j ++) { coll.push(ERC20Collateral({ erc20Token: _forDistrib[j].erc20Token, amount: _forDistrib[j].amount })); } emit Wrapped(_original721, _tokenIds[i], lastWrappedNFTId); // Safe Emergency exit if (gasleft() <= 1_000) { emit GasLimit(i + 1, _receivers[i]); return; } } } /// !!!!For gas safe this low levelfunction has NO any check before wrap /// So you have NO warranty to do Unwrap well function WrapAndDistribEmpty( address[] memory _receivers, ERC20Collateral[] memory _forDistrib, uint256 _unwrapAfter ) public payable { require(distributors[msg.sender], "Only for distributors"); require(_receivers.length <= 256, "Not more 256"); //require(_receivers.length == _tokenIds.length, "Not equal arrays"); // topup wrapper contract with erc20 that would be added in collateral for (uint8 i = 0; i < _forDistrib.length; i ++) { IERC20(_forDistrib[i].erc20Token).safeTransferFrom( msg.sender, address(this), _forDistrib[i].amount * _receivers.length ); } for (uint8 i = 0; i < _receivers.length; i ++) { // 2.Mint wrapped NFT for receiver and populate storage lastWrappedNFTId += 1; _mint(_receivers[i], lastWrappedNFTId); wrappedTokens[lastWrappedNFTId] = NFT( address(0), // _original721, 0, // _tokenIds[i], msg.value / _receivers.length, // native blockchain asset 0, // accumalated fee token _unwrapAfter, // timelock 0, //_transferFee, address(0), // _royaltyBeneficiary, 0, //_royaltyPercent, 0, //_unwraptFeeThreshold, address(0), //_transferFeeToken, AssetType.UNDEFINED, 0 ); // 3.Add erc20 collateral ERC20Collateral[] storage coll = erc20Collateral[lastWrappedNFTId]; for (uint8 j = 0; j < _forDistrib.length; j ++) { coll.push(ERC20Collateral({ erc20Token: _forDistrib[j].erc20Token, amount: _forDistrib[j].amount })); } emit Wrapped(address(0), 0, lastWrappedNFTId); // Safe Emergency exit if (gasleft() <= 1_000) { emit GasLimit(i + 1, _receivers[i]); return; } } } //////////////////////////////////////////////////////////////// ////////// Admins ////// //////////////////////////////////////////////////////////////// function setDistributorState(address _user, bool _state) external onlyOwner { distributors[_user] = _state; } //////////////////////////////////////////////////////////////// function _baseURI() internal view override(ERC721) returns (string memory) { return 'https://envelop.is/distribmetadata/'; } /** * @dev Function returns tokenURI of **underline original token** * * @param _tokenId id of protocol token (new wrapped token) */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { NFT storage nft = wrappedTokens[_tokenId]; if (nft.tokenContract != address(0)) { return IERC721Metadata(nft.tokenContract).tokenURI(nft.tokenId); } else { return ERC721.tokenURI(_tokenId); } } } // SPDX-License-Identifier: MIT // NIFTSY protocol for NFT. Wrapper - main protocol contract pragma solidity ^0.8.6; import "WrapperBase.sol"; import "ERC165Checker.sol"; /** * @title ERC-721 Non-Fungible Token Wrapper * @dev For wrpap existing ERC721 with ability add ERC20 collateral */ contract WrapperWithERC20Collateral is WrapperBase { using SafeERC20 for IERC20; using ERC165Checker for address; struct ERC20Collateral { address erc20Token; uint256 amount; } uint16 public MAX_ERC20_COUNT = 25; //max coins type count in collateral // Map from wrapped token id to array with erc20 collateral balances mapping(uint256 => ERC20Collateral[]) public erc20Collateral; // Map from collateral conatrct address to bool(enabled-as-collateral) //mapping(address => bool) public enabledForCollateral; event PartialUnWrapp(uint256 wrappedId, address owner); event SuspiciousFail(address failERC20, uint256 amount); event CollateralStatusChanged(address erc20, bool newStatus); event MaxCollateralCountChanged(uint256 oldValue, uint256 newValue); constructor (address _erc20) WrapperBase(_erc20) { partnersTokenList[_erc20].enabledForCollateral = true; } /** * @dev Function for add arbitrary ERC20 collaterals * * @param _wrappedTokenId NFT id from thgis contarct * @param _erc20 address of erc20 collateral for add * @param _amount amount erc20 collateral for add */ function addERC20Collateral( uint256 _wrappedTokenId, address _erc20, uint256 _amount ) external nonReentrant { require(ownerOf(_wrappedTokenId) != address(0)); require(enabledForCollateral(_erc20), "This ERC20 is not enabled for collateral"); require( IERC20(_erc20).balanceOf(msg.sender) >= _amount, "Low balance for add collateral" ); require( IERC20(_erc20).allowance(msg.sender, address(this)) >= _amount, "Please approve first" ); ERC20Collateral[] storage e = erc20Collateral[_wrappedTokenId]; //If collateral with this _erc20 already exist just update if (getERC20CollateralBalance(_wrappedTokenId, _erc20) > 0) { for (uint256 i = 0; i < e.length; i ++) { if (e[i].erc20Token == _erc20) { e[i].amount += _amount; break; } } } else { //So if we are here hence there is NO that _erc20 in collateral yet //We can add more tokens if limit NOT exccedd require(e.length < MAX_ERC20_COUNT, "To much ERC20 tokens in collatteral"); e.push(ERC20Collateral({ erc20Token: _erc20, amount: _amount })); } //Move collateral to contract balance IERC20(_erc20).safeTransferFrom(msg.sender, address(this), _amount); } //////////////////////////////////////////////// ///// Admin Functions //// //////////////////////////////////////////////// /** * @dev Function for operate Protocol ERC20 Collateral WhiteList * * @param _erc20 - collateral token address * @param _isEnabled - collateral contract status for Protocol */ function setCollateralStatus(address _erc20, bool _isEnabled) external onlyOwner { require(_erc20 != address(0), "No Zero Address"); partnersTokenList[_erc20].enabledForCollateral = _isEnabled; emit CollateralStatusChanged(_erc20, _isEnabled); } /** * @dev Function set ERC20 Collateral Count Limit * * @param _count - collateral count limit */ function setMaxERC20CollateralCount(uint16 _count) external onlyOwner { MAX_ERC20_COUNT = _count; emit MaxCollateralCountChanged(MAX_ERC20_COUNT, _count); } //////////////////////////////////////////////// /** * @dev Function returns array with info about ERC20 * colleteral of wrapped token * * @param _wrappedId new protocol NFT id from this contarct */ function getERC20Collateral(uint256 _wrappedId) external view returns (ERC20Collateral[] memory) { return erc20Collateral[_wrappedId]; } /** * @dev Function returns collateral balance of this NFT in _erc20 * colleteral of wrapped token * * @param _wrappedId new protocol NFT id from this contarct * @param _erc20 - collateral token address */ function getERC20CollateralBalance(uint256 _wrappedId, address _erc20) public view returns (uint256) { ERC20Collateral[] memory e = erc20Collateral[_wrappedId]; for (uint256 i = 0; i < e.length; i ++) { if (e[i].erc20Token == _erc20) { return e[i].amount; } } } function enabledForCollateral(address _contract) public view returns (bool) { return partnersTokenList[_contract].enabledForCollateral; } /** * @dev Helper function for check that _underlineContract supports * some interface accordingly ERC165. So for check IERC721 support * use _interfaceId like this: * /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd *_INTERFACE_ID_ERC721 = 0x80ac58cd; * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f * bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; * * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 * bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; * ****************************** * @param _underlineContract contract address for check */ function isERC721(address _underlineContract, bytes4 _interfaceId) public view returns (bool) { return _underlineContract.supportsInterface(_interfaceId); } ///////////////////////////////////////////////////////////////////// ///////////// Internals /////////////////////////////////////// ///////////////////////////////////////////////////////////////////// /** * @dev This hook may be overriden in inheritor contracts for extend * base functionality. * * @param _tokenId -wrapped token * * must returna true for success unwrapping enable */ function _beforeUnWrapHook(uint256 _tokenId) internal virtual override(WrapperBase) returns (bool){ return _returnERC20Collateral(_tokenId); } /** * @dev Function returns all ERC20 collateral to user who unWrap * protocol token. Returns true if all tokens are transfered. * Otherwise returns false. In that case need just call unWrap721 * one more time * * * @param _tokenId -wrapped token * */ function _returnERC20Collateral(uint256 _tokenId) internal returns (bool) { //First we need release erc20 collateral, because erc20 transfers are // can be expencive ERC20Collateral[] storage e = erc20Collateral[_tokenId]; if (e.length > 0) { for (uint256 i = e.length; i > 0; i --){ if (e[i-1].amount > 0) { // we need this try for protect from malicious // erc20 contract that can block unWrap NFT try // We dont use SafeTransfer because try works only for external function call // https://docs.soliditylang.org/en/v0.8.6/control-structures.html#try-catch IERC20(e[i-1].erc20Token).transfer(msg.sender, e[i-1].amount) { e[i-1].amount = 0; } catch { emit SuspiciousFail(e[i-1].erc20Token, e[i-1].amount); } // comment string below due in some case it c can be very costly // https://docs.soliditylang.org/en/v0.8.9/types.html#array-members //e.pop(); if (gasleft() <= 1_000) { emit PartialUnWrapp(_tokenId, msg.sender); return false; } } } } return true; } } // SPDX-License-Identifier: MIT // ENVELOP(NIFTSY) protocol for NFT. Wrapper - main protocol contract pragma solidity ^0.8.6; import "Ownable.sol"; import "ERC721Enumerable.sol"; import "SafeERC20.sol"; import "ReentrancyGuard.sol"; import "TechToken.sol"; import "ITechToken.sol"; import "IFeeRoyaltyCharger.sol"; /** * @title ERC-721 Non-Fungible Token Wrapper * @dev For wrpap existing ERC721 and ERC1155(now only 721) */ contract WrapperBase is ERC721Enumerable, Ownable, ReentrancyGuard, IFeeRoyaltyCharger { using SafeERC20 for IERC20; enum AssetType {UNDEFINED, ERC20, ERC721, ERC1155} struct NFT { address tokenContract; //Address of wrapping token contract uint256 tokenId; //Wrapping tokenId uint256 backedValue; //ETH uint256 backedTokens; //native project tokens uint256 unwrapAfter; //Freez date uint256 transferFee; //transferFee amount with decimals i.e. 20e18 address royaltyBeneficiary; //Royalty payments receiver uint256 royaltyPercent; //% from transferFee uint256 unwraptFeeThreshold;//unwrap possiple only after backedTokens achive this amount address transferFeeToken; //user can define transfer fee token contract from whitelist AssetType asset; //wrapped Asset type uint256 balance; //wrapping balance for erc 1155 } struct ListItem { bool enabledForCollateral; address transferFeeModel; bool disabledForWrap; } uint256 constant public MAX_ROYALTY_PERCENT = 50; uint256 constant public MAX_TIME_TO_UNWRAP = 365 days; uint256 constant public MAX_FEE_THRESHOLD_PERCENT = 1; //percent from project token totalSupply uint256 public protocolFee = 0; uint256 public chargeFeeAfter = type(uint256).max; uint256 public protocolFeeRaised; address public projectToken; address public protocolFeeToken; uint256 public lastWrappedNFTId; // Map from wrapped token id => NFT record mapping(uint256 => NFT) public wrappedTokens; //Private in Production // Map from conatrct address to enabled-as-collateral or blacklisted mapping(address => ListItem) public partnersTokenList; event Wrapped( address underlineContract, uint256 tokenId, uint256 indexed wrappedTokenId ); event UnWrapped( uint256 indexed wrappedId, address indexed owner, uint256 nativeCollateralAmount, uint256 feeAmount ); event NewFee(uint256 feeAmount, uint256 startDate); event NiftsyProtocolTransfer( uint256 indexed wrappedTokenId, address indexed royaltyBeneficiary, uint256 transferFee, uint256 royalty, address feeToken ); constructor(address _erc20) ERC721("ENVELOP Wrapped NFT Distributor", "wNFT") { require(_erc20 != address(0), "ProjectToken cant be zero value"); projectToken = _erc20; } /** * @dev DEPRICTAED method due * @dev Function for wrap existing ERC721 * * @param _underlineContract address of native NFT contract * @param _tokenId id of NFT that need to be wraped * @param _unwrapAfter Unix time value after that token can be unwrapped * @param _transferFee transferFee amount of projectToken with decimals i.e. 20e18 * @param _royaltyBeneficiary - address for royalty transfers * @param _royaltyPercent - integer 1..100, not more then MAX_ROYALTY_PERCENT * @param _unwraptFeeThreshold - token amounts in baccked fee for unwrap enable * @param _transferFeeToken - token address for fee and royalty settlemnet. By default * tech virtual project token * @return uint256 id of new wrapped token that represent old */ function wrap721( address _underlineContract, uint256 _tokenId, uint256 _unwrapAfter, uint256 _transferFee, address _royaltyBeneficiary, uint256 _royaltyPercent, uint256 _unwraptFeeThreshold, address _transferFeeToken ) external payable returns (uint256) { /////////////////Sanity checks//////////////////////// //0. Check blacklist for wrapping NFT require ( !partnersTokenList[_underlineContract].disabledForWrap, "This NFT is blacklisted for wrap" ); //1. ERC allowance // require( // IERC721(_underlineContract).getApproved(_tokenId) == address(this), // "Please call approve in your NFT contract" // ); //2. Logic around transfer fee if (_transferFee > 0) { if (_royaltyPercent > 0) { require(_royaltyPercent <= MAX_ROYALTY_PERCENT, "Royalty percent too big"); require(_royaltyBeneficiary != address(0), "Royalty to zero address"); } } else { require(_royaltyPercent == 0, "Royalty source is transferFee"); require(_royaltyBeneficiary == address(0), "No Royalty without transferFee"); require(_unwraptFeeThreshold == 0, "Cant set Threshold without transferFee"); } //3. MAX time to UNWRAP require( _unwrapAfter <= block.timestamp + MAX_TIME_TO_UNWRAP, "Too long Wrap" ); //4. For custom transfer fee token lets check MAX_FEE_THRESHOLD_PERCENT if (_transferFeeToken != address(0) && _transferFeeToken != projectToken) { require ( partnersTokenList[_transferFeeToken].enabledForCollateral, "This transferFee token is not enabled" ); require( _unwraptFeeThreshold < IERC20(_transferFeeToken).totalSupply() * MAX_FEE_THRESHOLD_PERCENT / 100, "Too much threshold" ); } ////////////////////////////////////////////////////// //Protocol fee can be not zero in the future // if (_getProtocolFeeAmount() > 0) { require( _chargeFee(msg.sender, _getProtocolFeeAmount()), "Cant charge protocol fee" ); protocolFeeRaised += _getProtocolFeeAmount(); } //////////////////////// /// WRAP LOGIC //// IERC721(_underlineContract).transferFrom(msg.sender, address(this), _tokenId); lastWrappedNFTId += 1; _mint(msg.sender, lastWrappedNFTId); wrappedTokens[lastWrappedNFTId] = NFT( _underlineContract, _tokenId, msg.value, 0, _unwrapAfter, _transferFee, _royaltyBeneficiary, _royaltyPercent, _unwraptFeeThreshold, _transferFeeToken, AssetType.ERC721, 0 ); emit Wrapped(_underlineContract, _tokenId, lastWrappedNFTId); return lastWrappedNFTId; } /** * @dev Function add native(eth, bnb) collateral to wrapped token * * @param _wrappedTokenId id of protocol token fo add */ function addNativeCollateral(uint256 _wrappedTokenId) external payable { require(ownerOf(_wrappedTokenId) != address(0)); NFT storage nft = wrappedTokens[_wrappedTokenId]; nft.backedValue += msg.value; } /** * @dev Function for unwrap protocol token. If wrapped NFT * has many erc20 collateral tokens it possible call this method * more than once, until unwrapped * * @param _tokenId id of protocol token to unwrapp */ function unWrap721(uint256 _tokenId) external nonReentrant { /////////////////////////////////////////////// //// Base Protocol checks /// /////////////////////////////////////////////// //1. Only token owner can UnWrap require(ownerOf(_tokenId) == msg.sender, 'Only owner can unwrap it!'); //storoge did not work because there is no this var after delete NFT memory nft = wrappedTokens[_tokenId]; //2. Time lock check if (nft.unwrapAfter != 0) { require(nft.unwrapAfter <= block.timestamp, "Cant unwrap before day X"); } //3. Fee accumulated check if (nft.unwraptFeeThreshold > 0){ require(nft.backedTokens >= nft.unwraptFeeThreshold, "Cant unwrap due Fee Threshold"); } /////////////////////////////////////////////// /// Place for hook //// /////////////////////////////////////////////// if (!_beforeUnWrapHook(_tokenId)) { return; } /////////////////////////////////////////////// /// Main UnWrap Logic ////// /////////////////////////////////////////////// _burn(_tokenId); if (nft.asset == AssetType.ERC721) { IERC721(nft.tokenContract).transferFrom(address(this), msg.sender, nft.tokenId); } delete wrappedTokens[_tokenId]; //Return backed ether if (nft.backedValue > 0) { address payable toPayable = payable(msg.sender); toPayable.transfer(nft.backedValue); } //Return backed tokens if (nft.backedTokens > 0) { if (nft.transferFeeToken == address(0)) { IERC20(projectToken).transfer(msg.sender, nft.backedTokens); } else { IERC20(nft.transferFeeToken).safeTransfer(msg.sender, nft.backedTokens); } } emit UnWrapped( _tokenId, msg.sender, nft.backedValue, nft.backedTokens ); } /** * @dev Function is part of transferFeeModel interface * for charge fee in tech protokol Token * */ function chargeTransferFeeAndRoyalty( address from, address to, uint256 transferFee, uint256 royaltyPercent, address royaltyBeneficiary, address _transferFeeToken ) external override returns (uint256 feeIncrement) { require(msg.sender == address(this), "Wrapper only"); uint256 rAmount = royaltyPercent * transferFee / 100; ITechToken(projectToken).mint(address(this), transferFee - rAmount); if (rAmount > 0) { ITechToken(projectToken).mint(royaltyBeneficiary, rAmount); } return transferFee - rAmount; } /** * @dev Function returns tokenURI of **underline original token** * * @param _tokenId id of protocol token (new wrapped token) */ function tokenURI(uint256 _tokenId) public view override virtual returns (string memory) { NFT storage nft = wrappedTokens[_tokenId]; return IERC721Metadata(nft.tokenContract).tokenURI(nft.tokenId); } /** * @dev Function returns tuple with accumulated amounts of * native chain collateral(eth, bnb,..) and transfer Fee * * @param _tokenId id of protocol token (new wrapped token) */ function getTokenValue(uint256 _tokenId) external view returns (uint256, uint256) { NFT storage nft = wrappedTokens[_tokenId]; return (nft.backedValue, nft.backedTokens); } /** * @dev Function returns structure with all data about * new protocol token * * @param _tokenId id of protocol token (new wrapped token) */ function getWrappedToken(uint256 _tokenId) external view returns (NFT memory) { return wrappedTokens[_tokenId]; } ///////////////////////////////////////////////////////////////////// // Admin functions // ///////////////////////////////////////////////////////////////////// function setFee(uint256 _fee, uint256 _startDate, address _protocolFeeToken) external onlyOwner { require(_protocolFeeToken != address(0), "No zero address"); protocolFee = _fee; chargeFeeAfter = _startDate; protocolFeeToken = _protocolFeeToken; emit NewFee(_fee, _startDate); } function editPartnersItem ( address _contract, bool _isCollateral, address _transferFeeModel, bool _isBlackListed ) external onlyOwner { partnersTokenList[_contract] = ListItem( _isCollateral, _transferFeeModel, _isBlackListed ); } ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// ///////////// Internals /////////////////////////////////////// ///////////////////////////////////////////////////////////////////// function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); //Not for mint and burn if (to != address(0) && from !=address(0)) { NFT storage nft = wrappedTokens[tokenId]; //Transfer fee charge if (nft.transferFee > 0) { address feeCharger = partnersTokenList[nft.transferFeeToken].transferFeeModel; // If there is no custom fee&royalty model then use // tech virtual protokol token if (feeCharger == address(0)) { feeCharger = address(this); } uint256 feeinc = IFeeRoyaltyCharger(feeCharger).chargeTransferFeeAndRoyalty( from, to, nft.transferFee, nft.royaltyPercent, nft.royaltyBeneficiary, nft.transferFeeToken ); nft.backedTokens += feeinc; emit NiftsyProtocolTransfer( tokenId, nft.royaltyBeneficiary, nft.transferFee, nft.transferFee - feeinc, nft.transferFeeToken ); } } } /** * @dev Function charge fee in project token * * @param _payer fee payer, must have non zero balance in project token * @param _amount fee amount for charge */ function _chargeFee(address _payer, uint256 _amount) internal returns(bool) { require( IERC20(protocolFeeToken).balanceOf(_payer) >= _amount, "insufficient protocol fee token balance for fee" ); IERC20(protocolFeeToken).transferFrom(_payer, address(this), _amount); return true; } /** * @dev This hook may be overriden in inheritor contracts for extend * base functionality. * * @param _tokenId -wrapped token * * must returna true for success unwrapping enable */ function _beforeUnWrapHook(uint256 _tokenId) internal virtual returns (bool){ return true; } function _getProtocolFeeAmount() internal view returns (uint256) { if (block.timestamp >= chargeFeeAfter) { return protocolFee; } else { return 0; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "ERC721.sol"; import "IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @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` cannot be the zero address. * - `to` cannot be the zero address. * * 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 override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "IERC721.sol"; import "IERC721Receiver.sol"; import "IERC721Metadata.sol"; import "Address.sol"; import "Context.sol"; import "Strings.sol"; import "ERC165.sol"; /** * @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 ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings 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. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).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 = ERC721.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 { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_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 = ERC721.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 = ERC721.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(ERC721.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(ERC721.ownerOf(tokenId), to, tokenId); } /** * @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 IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.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 {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, 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; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT 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 IERC721Receiver { /** * @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); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @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); } // SPDX-License-Identifier: MIT 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); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { 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); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "IERC165.sol"; /** * @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 ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "IERC20.sol"; import "Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; 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' 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) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _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 require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT 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 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; } } // SPDX-License-Identifier: MIT // NIFTSY protocol ERC20 pragma solidity ^0.8.6; import "ERC20.sol"; import "MinterRole.sol"; contract TechToken is ERC20, MinterRole { constructor() ERC20("Virtual Envelop Transfer Fee Token", "vENVLP") MinterRole(msg.sender) { } function mint(address _to, uint256 _value) external onlyMinter { _mint(_to, _value); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "IERC20.sol"; import "IERC20Metadata.sol"; import "Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.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 ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.6; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor(address sender) { if (!isMinter(sender)) { _addMinter(sender); } } modifier onlyMinter() { require(isMinter(msg.sender), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.6; import "IERC20.sol"; interface ITechToken is IERC20 { function mint(address _to, uint256 _value) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.6; interface IFeeRoyaltyCharger { function chargeTransferFeeAndRoyalty( address from, address to, uint256 transferFee, uint256 royaltyPercent, address royaltyBeneficiary, address _transferFeeToken ) external returns (uint256 feeIncrement); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "IERC165.sol"; /** * @dev Library used to query support of an interface declared via {IERC165}. * * Note that these functions return the actual result of the query: they do not * `revert` if an interface is not supported. It is up to the caller to decide * what to do in these cases. */ library ERC165Checker { // As per the EIP-165 spec, no interface should ever match 0xffffffff bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff; /** * @dev Returns true if `account` supports the {IERC165} interface, */ function supportsERC165(address account) internal view returns (bool) { // Any contract that implements ERC165 must explicitly indicate support of // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid return _supportsERC165Interface(account, type(IERC165).interfaceId) && !_supportsERC165Interface(account, _INTERFACE_ID_INVALID); } /** * @dev Returns true if `account` supports the interface defined by * `interfaceId`. Support for {IERC165} itself is queried automatically. * * See {IERC165-supportsInterface}. */ function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) { // query support of both ERC165 as per the spec and support of _interfaceId return supportsERC165(account) && _supportsERC165Interface(account, interfaceId); } /** * @dev Returns a boolean array where each value corresponds to the * interfaces passed in and whether they're supported or not. This allows * you to batch check interfaces for a contract where your expectation * is that some interfaces may not be supported. * * See {IERC165-supportsInterface}. * * _Available since v3.4._ */ function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) { // an array of booleans corresponding to interfaceIds and whether they're supported or not bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length); // query support of ERC165 itself if (supportsERC165(account)) { // query support of each interface in interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]); } } return interfaceIdsSupported; } /** * @dev Returns true if `account` supports all the interfaces defined in * `interfaceIds`. Support for {IERC165} itself is queried automatically. * * Batch-querying can lead to gas savings by skipping repeated checks for * {IERC165} support. * * See {IERC165-supportsInterface}. */ function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { // query support of ERC165 itself if (!supportsERC165(account)) { return false; } // query support of each interface in _interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { if (!_supportsERC165Interface(account, interfaceIds[i])) { return false; } } // all interfaces supported return true; } /** * @notice Query if a contract implements an interface, does not check ERC165 support * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return true if the contract at account indicates support of the interface with * identifier interfaceId, false otherwise * @dev Assumes that account contains a contract that supports ERC165, otherwise * the behavior of this method is undefined. This precondition can be checked * with {supportsERC165}. * Interface identification is specified in ERC-165. */ function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) { bytes memory encodedParams = abi.encodeWithSelector(IERC165.supportsInterface.selector, interfaceId); (bool success, bytes memory result) = account.staticcall{gas: 30000}(encodedParams); if (result.length < 32) return false; return success && abi.decode(result, (bool)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.6; import "IERC721Metadata.sol"; interface IERC721Mintable is IERC721Metadata { function mint(address _to, uint256 _tokenId) external; }
!!!!For gas safe this low levelfunction has NO any check before wrap So you have NO warranty to do Unwrap wellrequire(_receivers.length == _tokenIds.length, "Not equal arrays"); topup wrapper contract with erc20 that would be added in collateral 2.Mint wrapped NFT for receiver and populate storage 3.Add erc20 collateral Safe Emergency exit
function WrapAndDistribEmpty( address[] memory _receivers, ERC20Collateral[] memory _forDistrib, uint256 _unwrapAfter ) public payable { require(distributors[msg.sender], "Only for distributors"); require(_receivers.length <= 256, "Not more 256"); for (uint8 i = 0; i < _forDistrib.length; i ++) { IERC20(_forDistrib[i].erc20Token).safeTransferFrom( msg.sender, address(this), _forDistrib[i].amount * _receivers.length ); } for (uint8 i = 0; i < _receivers.length; i ++) { lastWrappedNFTId += 1; _mint(_receivers[i], lastWrappedNFTId); wrappedTokens[lastWrappedNFTId] = NFT( AssetType.UNDEFINED, 0 ); ERC20Collateral[] storage coll = erc20Collateral[lastWrappedNFTId]; for (uint8 j = 0; j < _forDistrib.length; j ++) { coll.push(ERC20Collateral({ erc20Token: _forDistrib[j].erc20Token, amount: _forDistrib[j].amount })); } emit Wrapped(address(0), 0, lastWrappedNFTId); if (gasleft() <= 1_000) { emit GasLimit(i + 1, _receivers[i]); return; } } }
9,916,632
/* ・ * ★ ・ 。  ・ ゚☆ 。     * ★ ゚・。 * 。   * ☆ 。・゚*.。    ゚ *.。☆。★ ・ ​ ` .-:::::-.` `-::---...``` `-:` .:+ssssoooo++//:.` .-/+shhhhhhhhhhhhhyyyssooo: .--::. .+ossso+/////++/:://-` .////+shhhhhhhhhhhhhhhhhhhhhy `-----::. `/+////+++///+++/:--:/+/- -////+shhhhhhhhhhhhhhhhhhhhhy `------:::-` `//-.``.-/+ooosso+:-.-/oso- -////+shhhhhhhhhhhhhhhhhhhhhy .--------:::-` :+:.` .-/osyyyyyyso++syhyo.-////+shhhhhhhhhhhhhhhhhhhhhy `-----------:::-. +o+:-.-:/oyhhhhhhdhhhhhdddy:-////+shhhhhhhhhhhhhhhhhhhhhy .------------::::-- `oys+/::/+shhhhhhhdddddddddy/-////+shhhhhhhhhhhhhhhhhhhhhy .--------------:::::-` +ys+////+yhhhhhhhddddddddhy:-////+yhhhhhhhhhhhhhhhhhhhhhy `----------------::::::-`.ss+/:::+oyhhhhhhhhhhhhhhho`-////+shhhhhhhhhhhhhhhhhhhhhy .------------------:::::::.-so//::/+osyyyhhhhhhhhhys` -////+shhhhhhhhhhhhhhhhhhhhhy `.-------------------::/:::::..+o+////+oosssyyyyyyys+` .////+shhhhhhhhhhhhhhhhhhhhhy .--------------------::/:::.` -+o++++++oooosssss/. `-//+shhhhhhhhhhhhhhhhhhhhyo .------- ``````.......--` `-/+ooooosso+/-` `./++++///:::--...``hhhhyo ````` *  ・ 。     ・  ゚☆ 。     * ★ ゚・。 * 。   * ☆ 。・゚*.。    ゚ *.。☆。★ ・ *  ゚。·*・。 ゚*    ☆゚・。°*. ゚   ・ ゚*。・゚★。   ・ *゚。   *  ・゚*。★・ ☆∴。 * ・ 。 */ // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interfaces/IERC20Approve.sol"; import "./libraries/BytesLibrary.sol"; /** * @notice Deploys contracts which auto-forwards any ETH sent to it to a list of recipients * considering their percent share of the payment received. * @dev Uses create2 counterfactual addresses so that the destination is known from the terms of the split. */ contract PercentSplitETH is Initializable { using AddressUpgradeable for address payable; using AddressUpgradeable for address; using BytesLibrary for bytes; using SafeMath for uint256; struct Share { address payable recipient; uint256 percentInBasisPoints; } uint256 internal constant BASIS_POINTS = 10000; Share[] private _shares; event PercentSplitCreated(address indexed contractAddress); event PercentSplitShare(address indexed recipient, uint256 percentInBasisPoints); event ETHTransferred(address indexed account, uint256 amount); event ERC20Transferred(address indexed erc20Contract, address indexed account, uint256 amount); /** * @dev Requires that the msg.sender is one of the recipients in this split. */ modifier onlyRecipient() { for (uint256 i = 0; i < _shares.length; i++) { if (_shares[i].recipient == msg.sender) { _; return; } } revert("Split: Can only be called by one of the recipients"); } /** * @notice Creates a new minimal proxy contract and initializes it with the given split terms. * If the contract had already been created, its address is returned. * This must be called on the original implementation and not a proxy created previously. */ function createSplit(Share[] memory shares) public returns (PercentSplitETH splitInstance) { bytes32 salt = keccak256(abi.encode(shares)); address clone = Clones.predictDeterministicAddress(address(this), salt); splitInstance = PercentSplitETH(payable(clone)); if (!clone.isContract()) { emit PercentSplitCreated(clone); Clones.cloneDeterministic(address(this), salt); splitInstance.initialize(shares); } } /** * @notice Returns the address for the proxy contract which would represent the given split terms. * @dev The contract may or may not already be deployed at the address returned. * Ensure that it is deployed before sending funds to this address. */ function getPredictedSplitAddress(Share[] memory shares) public view returns (address) { bytes32 salt = keccak256(abi.encode(shares)); return Clones.predictDeterministicAddress(address(this), salt); } /** * @notice Called once to configure the contract after the initial deployment. * @dev This will be called by `createSplit` after deploying the proxy so it should never be called directly. */ function initialize(Share[] memory shares) public initializer { require(shares.length >= 2, "Split: Too few recipients"); require(shares.length <= 5, "Split: Too many recipients"); uint256 total; for (uint256 i = 0; i < shares.length; i++) { total += shares[i].percentInBasisPoints; _shares.push(shares[i]); emit PercentSplitShare(shares[i].recipient, shares[i].percentInBasisPoints); } require(total == BASIS_POINTS, "Split: Total amount must equal 100%"); } /** * @notice Returns a tuple with the terms of this split. */ function getShares() public view returns (Share[] memory) { return _shares; } /** * @notice Returns how many recipients are part of this split. */ function getShareLength() public view returns (uint256) { return _shares.length; } /** * @notice Returns a recipient in this split. */ function getShareRecipientByIndex(uint256 index) public view returns (address payable) { return _shares[index].recipient; } /** * @notice Returns a recipient's percent share in basis points. */ function getPercentInBasisPointsByIndex(uint256 index) public view returns (uint256) { return _shares[index].percentInBasisPoints; } /** * @notice Forwards any ETH received to the recipients in this split. * @dev Each recipient increases the gas required to split * and contract recipients may significantly increase the gas required. */ receive() external payable { _splitETH(msg.value); } /** * @notice Allows any ETH stored by the contract to be split among recipients. * @dev Normally ETH is forwarded as it comes in, but a balance in this contract * is possible if it was sent before the contract was created or if self destruct was used. */ function splitETH() public { _splitETH(address(this).balance); } function _splitETH(uint256 value) internal { if (value > 0) { uint256 totalSent; uint256 amountToSend; unchecked { for (uint256 i = _shares.length - 1; i > 0; i--) { Share memory share = _shares[i]; amountToSend = (value * share.percentInBasisPoints) / BASIS_POINTS; totalSent += amountToSend; share.recipient.sendValue(amountToSend); emit ETHTransferred(share.recipient, amountToSend); } // Favor the 1st recipient if there are any rounding issues amountToSend = value - totalSent; } _shares[0].recipient.sendValue(amountToSend); emit ETHTransferred(_shares[0].recipient, amountToSend); } } /** * @notice Anyone can call this function to split all available tokens at the provided address between the recipients. * @dev This contract is built to split ETH payments. The ability to attempt to split ERC20 tokens is here * just in case tokens were also sent so that they don't get locked forever in the contract. */ function splitERC20Tokens(IERC20 erc20Contract) public { require(_splitERC20Tokens(erc20Contract), "Split: ERC20 split failed"); } function _splitERC20Tokens(IERC20 erc20Contract) internal returns (bool) { try erc20Contract.balanceOf(address(this)) returns (uint256 balance) { if (balance == 0) { return false; } uint256 amountToSend; uint256 totalSent; unchecked { for (uint256 i = _shares.length - 1; i > 0; i--) { Share memory share = _shares[i]; bool success; (success, amountToSend) = balance.tryMul(share.percentInBasisPoints); if (!success) { return false; } amountToSend /= BASIS_POINTS; totalSent += amountToSend; try erc20Contract.transfer(share.recipient, amountToSend) { emit ERC20Transferred(address(erc20Contract), share.recipient, amountToSend); } catch { return false; } } // Favor the 1st recipient if there are any rounding issues amountToSend = balance - totalSent; } try erc20Contract.transfer(_shares[0].recipient, amountToSend) { emit ERC20Transferred(address(erc20Contract), _shares[0].recipient, amountToSend); } catch { return false; } return true; } catch { return false; } } /** * @notice Allows the split recipients to make an arbitrary contract call. * @dev This is provided to allow recovering from unexpected scenarios, * such as receiving an NFT at this address. * * It will first attempt a fair split of ERC20 tokens before proceeding. * * This contract is built to split ETH payments. The ability to attempt to make other calls is here * just in case other assets were also sent so that they don't get locked forever in the contract. */ function proxyCall(address payable target, bytes memory callData) public onlyRecipient { require(!callData.startsWith(type(IERC20Approve).interfaceId), "Split: ERC20 tokens must be split"); _splitERC20Tokens(IERC20(target)); target.functionCall(callData); } } // SPDX-License-Identifier: MIT 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; } } } // SPDX-License-Identifier: MIT 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); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. * * _Available since v3.4._ */ library Clones { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create opcode, which should never revert. */ function clone(address implementation) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `implementation` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress( address implementation, bytes32 salt, address deployer ) internal pure returns (address predicted) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address implementation, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(implementation, salt, address(this)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.8.0; interface IERC20Approve { function approve(address spender, uint256 amount) external returns (bool); } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.8.0; /** * @notice A library for manipulation of byte arrays. */ library BytesLibrary { /** * @dev Replace the address at the given location in a byte array if the contents at that location * match the expected address. */ function replaceAtIf( bytes memory data, uint256 startLocation, address expectedAddress, address newAddress ) internal pure { bytes memory expectedData = abi.encodePacked(expectedAddress); bytes memory newData = abi.encodePacked(newAddress); // An address is 20 bytes long for (uint256 i = 0; i < 20; i++) { uint256 dataLocation = startLocation + i; require(data[dataLocation] == expectedData[i], "Bytes: Data provided does not include the expectedAddress"); data[dataLocation] = newData[i]; } } /** * @dev Checks if the call data starts with the given function signature. */ function startsWith(bytes memory callData, bytes4 functionSig) internal pure returns (bool) { // A signature is 4 bytes long if (callData.length < 4) { return false; } for (uint256 i = 0; i < 4; i++) { if (callData[i] != functionSig[i]) { return false; } } return true; } }
Creates a new minimal proxy contract and initializes it with the given split terms. If the contract had already been created, its address is returned. This must be called on the original implementation and not a proxy created previously./
function createSplit(Share[] memory shares) public returns (PercentSplitETH splitInstance) { bytes32 salt = keccak256(abi.encode(shares)); address clone = Clones.predictDeterministicAddress(address(this), salt); splitInstance = PercentSplitETH(payable(clone)); if (!clone.isContract()) { emit PercentSplitCreated(clone); Clones.cloneDeterministic(address(this), salt); splitInstance.initialize(shares); } }
14,699,293
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.8.0; import "hardhat/console.sol"; 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); } /** * @notice only contains neessary operations, including absolute value */ library LowGasSafeMath { /// @notice Returns x + y, reverts if sum overflows uint256 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(x == 0 || (z = x * y) / x == y); } // /// @notice Returns x + y, reverts if overflows or underflows // /// @param x The augend // /// @param y The addend // /// @return z The sum of x and y // function add(int256 x, int256 y) internal pure returns (int256 z) { // require((z = x + y) >= x == (y >= 0)); // } // /// @notice Returns x - y, reverts if overflows or underflows // /// @param x The minuend // /// @param y The subtrahend // /// @return z The difference of x and y // function sub(int256 x, int256 y) internal pure returns (int256 z) { // require((z = x - y) <= x == (y >= 0)); // } /// @notice Returns the absolute value of difference of x and y /// @param x The minuend /// @param y The subtrahend /// @return z The absolute difference of x and y function absSub(uint256 x, uint256 y) internal pure returns (uint256) { return x >= y ? (x - y) : (y - x); } } /** * @notice This ERC20 is modified to discourage selling */ abstract contract ERC20 is IERC20 { using LowGasSafeMath for uint256; // Present in ERC777 mapping (address => uint256) internal _balances; // Present in ERC777 mapping (address => mapping (address => uint256)) internal _allowances; // Present in ERC777 uint256 internal _totalSupply; // Present in ERC777 string internal _name; // Present in ERC777 string internal _symbol; // Present in ERC777 uint8 internal _decimals; constructor (string memory name_, string memory symbol_, uint8 decimals_) { _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; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender] .sub(amount)); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender] .sub(subtractedValue)); return true; } 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); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account_, uint256 amount_) internal virtual { require(account_ != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address( this ), account_, amount_); _totalSupply = _totalSupply.add(amount_); _balances[account_] = _balances[account_].add(amount_); emit Transfer(address(0), account_, amount_); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } 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); } function _beforeTokenTransfer( address from_, address to_, uint256 amount_ ) internal virtual { } } /** * @notice For IERC2612Permit. decrement is never being used. */ library Counters { using LowGasSafeMath for uint256; struct Counter { uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { counter._value += 1; } } interface IERC2612Permit { function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function nonces(address owner) external view returns (uint256); } abstract contract ERC20Permit is ERC20, IERC2612Permit { using Counters for Counters.Counter; mapping(address => Counters.Counter) private _nonces; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; bytes32 public DOMAIN_SEPARATOR; constructor() { uint256 chainID; assembly { chainID := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name())), keccak256(bytes("1")), // Version chainID, address(this) ) ); } function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "Permit: expired deadline"); bytes32 hashStruct = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, _nonces[owner].current(), deadline)); bytes32 _hash = keccak256(abi.encodePacked(uint16(0x1901), DOMAIN_SEPARATOR, hashStruct)); address signer = ecrecover(_hash, v, r, s); require(signer != address(0) && signer == owner, "ERC20Permit: Invalid signature"); _nonces[owner].increment(); _approve(owner, spender, amount); } function nonces(address owner) public view override returns (uint256) { return _nonces[owner].current(); } } interface IOwnable { function owner() external view returns (address); function renounceOwnership() external; function transferOwnership( address newOwner_ ) external; } contract Ownable is IOwnable { address internal _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { _owner = msg.sender; emit OwnershipTransferred( address(0), _owner ); } function owner() public view override returns (address) { return _owner; } modifier onlyOwner() { require( _owner == msg.sender, "Ownable: caller is not the owner" ); _; } function renounceOwnership() public virtual override onlyOwner() { emit OwnershipTransferred( _owner, address(0) ); _owner = address(0); } function transferOwnership( address newOwner_ ) public virtual override onlyOwner() { require( newOwner_ != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred( _owner, newOwner_ ); _owner = newOwner_; } } // contract VaultOwned is Ownable { // address internal _vault; // event VaultTransferred(address indexed newVault); // function setVault( address vault_ ) external onlyOwner() { // require(vault_ != address(0), "IA0"); // _vault = vault_; // emit VaultTransferred( _vault ); // } // function vault() public view returns (address) { // return _vault; // } // modifier onlyVault() { // require( _vault == msg.sender, "VaultOwned: caller is not the Vault" ); // _; // } // } /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, 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; } contract FlagshipERC20Token is ERC20Permit, Ownable { using LowGasSafeMath for uint256; /* ========== STATE VARIABLES ========== */ address public immutable _FexP; bool public allTaxOrExempt = false; event TaxedTransfer(address indexed _from, address indexed _to, uint256 _afterTaxedAmount, uint256 _taxes); event TaxExemptTransfer(address indexed _from, address indexed _to, uint256 _amount); struct TransferRecords { uint256 _lastTxnTime; uint256 _numTxnWithinInterval; } // mappping (user => TransferRecords) // only address without flagship unrestricted will be kept in the _transferRecords mapping (address => TransferRecords) internal _transferRecords; /* ========== CONSTRUCTOR ========== */ constructor(address _fuelExchangePermit) ERC20("Flagship Fuel", "FF", 9) { require(_fuelExchangePermit != address(0), "Zero address: fuelExchangePermit"); _FexP = _fuelExchangePermit; } /* ========== TAX FUNCTIONS ========== */ function _transfer(address sender, address recipient, uint256 amount) internal override { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); uint256 taxes; IERC721 fuelExchangePermit = IERC721(_FexP); if (fuelExchangePermit.balanceOf(sender) == 0 && !allTaxOrExempt) { // no fuelExchangePermit, has to be taxed; adjust amount (amount, taxes) = _taxTxn(sender, amount); _burn(sender, taxes); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit TaxedTransfer(sender, recipient, amount, taxes); return; } _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit TaxExemptTransfer(sender, recipient, amount); } function _taxTxn(address _sender, uint256 _amount) internal returns (uint256 _afterTaxedAmount, uint256 _taxes) { _taxes = _checkTransferRecords(_sender, _amount); _taxes = _taxes.add(_checkPortion(_amount)); _afterTaxedAmount = _amount - _taxes; } /** * @notice max: 17% taxAmount */ function _checkTransferRecords(address _sender, uint256 _amount) internal returns (uint256 taxAmount) { // check _transferRecords if (block.timestamp.absSub(_transferRecords[_sender]._lastTxnTime) >= 1 hours) { // one hour time reached; reset _transferRecords[_sender]._numTxnWithinInterval = 1; } else { _transferRecords[_sender]._numTxnWithinInterval++; } _transferRecords[_sender]._lastTxnTime = block.timestamp; // calculate taxAmount // 1 : 1% // 2 ~ 4 : 2%, 4%, 6% // >=5 : 10% if (_transferRecords[_sender]._numTxnWithinInterval >= 2 && _transferRecords[_sender]._numTxnWithinInterval <= 4) { taxAmount = (_amount / 50) * (_transferRecords[_sender]._numTxnWithinInterval.sub(1)); // add 2% for each; } else if (_transferRecords[_sender]._numTxnWithinInterval >= 5) { taxAmount = (_amount / 10); // 10%; } else { taxAmount = _amount / 100; // it is the minimum taxAmount; 1% } } function _checkPortion(uint256 _amount) internal view returns (uint256) { // check percentage of _totalSupply; adjust _amount uint256 one_percentile = _totalSupply / 100; uint256 two_percentile = _totalSupply / 50; uint256 five_percentile = _totalSupply / 20; if (_amount > five_percentile) { return (_amount - five_percentile) / 2; // add 50% of that is more than five_percentile } else if (_amount > two_percentile) { return (_amount - two_percentile) / 5; // add 20% of that is more than five_percentile } else if (_amount > one_percentile) { return (_amount - one_percentile) / 10; // add 10% of that is more than five_percentile } return 0; } /* ========== OTHER FUNCTIONS ========== */ function mint(address account_, uint256 amount_) external onlyOwner() { _mint(account_, amount_); } function burn(uint256 amount) external virtual { _burn(msg.sender, amount); } function burnFrom(address account_, uint256 amount_) external virtual { _burnFrom(account_, amount_); } function _burnFrom(address account_, uint256 amount_) internal virtual { uint256 decreasedAllowance_ = allowance(account_, msg.sender).sub(amount_); _approve(account_, msg.sender, decreasedAllowance_); _burn(account_, amount_); } /* ========== PERMIT FUNCTIONS ========== */ function setallTaxOrExempt(bool _allTaxOrExempt) public onlyOwner() { require(_allTaxOrExempt != allTaxOrExempt, "State will not be changed!"); allTaxOrExempt = _allTaxOrExempt; } /* ========== KILL FUNCTIONS ========== */ function kill() public onlyOwner() { selfdestruct(payable(_owner)); } }
========== PERMIT FUNCTIONS ========== /
function setallTaxOrExempt(bool _allTaxOrExempt) public onlyOwner() { require(_allTaxOrExempt != allTaxOrExempt, "State will not be changed!"); allTaxOrExempt = _allTaxOrExempt; }
12,610,882
pragma solidity 0.4.26; library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { 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; } } 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 transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } } 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); } 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 ); } library ArrayUtils { /** * Replace bytes in an array with bytes in another array, guarded by a bitmask * Efficiency of this function is a bit unpredictable because of the EVM's word-specific model (arrays under 32 bytes will be slower) * * @dev Mask must be the size of the byte array. A nonzero byte means the byte array can be changed. * @param array The original array * @param desired The target array * @param mask The mask specifying which bits can be changed * @return The updated byte array (the parameter will be modified inplace) */ function guardedArrayReplace(bytes memory array, bytes memory desired, bytes memory mask) internal pure { require(array.length == desired.length); require(array.length == mask.length); uint words = array.length / 0x20; uint index = words * 0x20; assert(index / 0x20 == words); uint i; for (i = 0; i < words; i++) { /* Conceptually: array[i] = (!mask[i] && array[i]) || (mask[i] && desired[i]), bitwise in word chunks. */ assembly { let commonIndex := mul(0x20, add(1, i)) let maskValue := mload(add(mask, commonIndex)) mstore(add(array, commonIndex), or(and(not(maskValue), mload(add(array, commonIndex))), and(maskValue, mload(add(desired, commonIndex))))) } } /* Deal with the last section of the byte array. */ if (words > 0) { /* This overlaps with bytes already set but is still more efficient than iterating through each of the remaining bytes individually. */ i = words; assembly { let commonIndex := mul(0x20, add(1, i)) let maskValue := mload(add(mask, commonIndex)) mstore(add(array, commonIndex), or(and(not(maskValue), mload(add(array, commonIndex))), and(maskValue, mload(add(desired, commonIndex))))) } } else { /* If the byte array is shorter than a word, we must unfortunately do the whole thing bytewise. (bounds checks could still probably be optimized away in assembly, but this is a rare case) */ for (i = index; i < array.length; i++) { array[i] = ((mask[i] ^ 0xff) & array[i]) | (mask[i] & desired[i]); } } } /** * Test if two arrays are equal * @param a First array * @param b Second array * @return Whether or not all bytes in the arrays are equal */ function arrayEq(bytes memory a, bytes memory b) internal pure returns (bool) { return keccak256(a) == keccak256(b); } /** * Unsafe write byte array into a memory location * * @param index Memory location * @param source Byte array to write * @return End memory index */ function unsafeWriteBytes(uint index, bytes source) internal pure returns (uint) { if (source.length > 0) { assembly { let length := mload(source) let end := add(source, add(0x20, length)) let arrIndex := add(source, 0x20) let tempIndex := index for { } eq(lt(arrIndex, end), 1) { arrIndex := add(arrIndex, 0x20) tempIndex := add(tempIndex, 0x20) } { mstore(tempIndex, mload(arrIndex)) } index := add(index, length) } } return index; } /** * Unsafe write address into a memory location * * @param index Memory location * @param source Address to write * @return End memory index */ function unsafeWriteAddress(uint index, address source) internal pure returns (uint) { uint conv = uint(source) << 0x60; assembly { mstore(index, conv) index := add(index, 0x14) } return index; } /** * Unsafe write address into a memory location using entire word * * @param index Memory location * @param source uint to write * @return End memory index */ function unsafeWriteAddressWord(uint index, address source) internal pure returns (uint) { assembly { mstore(index, source) index := add(index, 0x20) } return index; } /** * Unsafe write uint into a memory location * * @param index Memory location * @param source uint to write * @return End memory index */ function unsafeWriteUint(uint index, uint source) internal pure returns (uint) { assembly { mstore(index, source) index := add(index, 0x20) } return index; } /** * Unsafe write uint8 into a memory location * * @param index Memory location * @param source uint8 to write * @return End memory index */ function unsafeWriteUint8(uint index, uint8 source) internal pure returns (uint) { assembly { mstore8(index, source) index := add(index, 0x1) } return index; } /** * Unsafe write uint8 into a memory location using entire word * * @param index Memory location * @param source uint to write * @return End memory index */ function unsafeWriteUint8Word(uint index, uint8 source) internal pure returns (uint) { assembly { mstore(index, source) index := add(index, 0x20) } return index; } /** * Unsafe write bytes32 into a memory location using entire word * * @param index Memory location * @param source uint to write * @return End memory index */ function unsafeWriteBytes32(uint index, bytes32 source) internal pure returns (uint) { assembly { mstore(index, source) index := add(index, 0x20) } return index; } } contract ReentrancyGuarded { bool reentrancyLock = false; /* Prevent a contract function from being reentrant-called. */ modifier reentrancyGuard { if (reentrancyLock) { revert(); } reentrancyLock = true; _; reentrancyLock = false; } } contract TokenRecipient { event ReceivedEther(address indexed sender, uint amount); event ReceivedTokens(address indexed from, uint256 value, address indexed token, bytes extraData); /** * @dev Receive tokens and generate a log event * @param from Address from which to transfer tokens * @param value Amount of tokens to transfer * @param token Address of token * @param extraData Additional data to log */ function receiveApproval(address from, uint256 value, address token, bytes extraData) public { ERC20 t = ERC20(token); require(t.transferFrom(from, this, value)); emit ReceivedTokens(from, value, token, extraData); } /** * @dev Receive Ether and generate a log event */ function () payable public { emit ReceivedEther(msg.sender, msg.value); } } contract ExchangeCore is ReentrancyGuarded, Ownable { string public constant name = "StarBlock Exchange Contract"; string public constant version = "1.0"; // NOTE: these hashes are derived and verified in the constructor. bytes32 private constant _EIP_712_DOMAIN_TYPEHASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f; bytes32 private constant _NAME_HASH = 0x908be1d09f2d17dd8812f5561d84e89cc7052e553487116c4cf73793bdba635d; bytes32 private constant _VERSION_HASH = 0xe6bbd6277e1bf288eed5e8d1780f9a50b239e86b153736bceebccf4ea79d90b3; bytes32 private constant _ORDER_TYPEHASH = 0xdba08a88a748f356e8faf8578488343eab21b1741728779c9dcfdc782bc800f8; bytes4 private constant _EIP_1271_MAGIC_VALUE = 0x1626ba7e; // // NOTE: chainId opcode is not supported in solidiy 0.4.x; here we hardcode as 1. // In order to protect against orders that are replayable across forked chains, // either the solidity version needs to be bumped up or it needs to be retrieved // from another contract. uint256 private constant _CHAIN_ID = 1; // Note: the domain separator is derived and verified in the constructor. */ bytes32 public constant DOMAIN_SEPARATOR = _deriveDomainSeparator(); /* The token used to pay exchange fees. */ ERC20 public exchangeToken; /* User registry. */ ProxyRegistry public registry; /* Token transfer proxy. */ TokenTransferProxy public tokenTransferProxy; /* Cancelled / finalized orders, by hash. */ mapping(bytes32 => bool) public cancelledOrFinalized; /* Orders verified by on-chain approval (alternative to ECDSA signatures so that smart contracts can place orders directly). */ /* Note that the maker's nonce at the time of approval **plus one** is stored in the mapping. */ mapping(bytes32 => uint256) private _approvedOrdersByNonce; /* Track per-maker nonces that can be incremented by the maker to cancel orders in bulk. */ // The current nonce for the maker represents the only valid nonce that can be signed by the maker // If a signature was signed with a nonce that's different from the one stored in nonces, it // will fail validation. mapping(address => uint256) public nonces; /* For split fee orders, minimum required protocol maker fee, in basis points. Paid to owner (who can change it). */ uint public minimumMakerProtocolFee = 0; /* For split fee orders, minimum required protocol taker fee, in basis points. Paid to owner (who can change it). */ uint public minimumTakerProtocolFee = 0; /* Recipient of protocol fees. */ address public protocolFeeRecipient; /* Fee method: protocol fee or split fee. */ enum FeeMethod { ProtocolFee, SplitFee } /* Inverse basis point. */ uint public constant INVERSE_BASIS_POINT = 10000; /* An ECDSA signature. */ struct Sig { /* v parameter */ uint8 v; /* r parameter */ bytes32 r; /* s parameter */ bytes32 s; } /* An order on the exchange. */ struct Order { /* Exchange address, intended as a versioning mechanism. */ address exchange; /* Order maker address. */ address maker; /* Order taker address, if specified. */ address taker; /* Maker relayer fee of the order, unused for taker order. */ uint makerRelayerFee; /* Taker relayer fee of the order, or maximum taker fee for a taker order. */ uint takerRelayerFee; /* Maker protocol fee of the order, unused for taker order. */ uint makerProtocolFee; /* Taker protocol fee of the order, or maximum taker fee for a taker order. */ uint takerProtocolFee; /* Order fee recipient or zero address for taker order. */ address feeRecipient; /* Fee method (protocol token or split fee). */ FeeMethod feeMethod; /* Side (buy/sell). */ SaleKindInterface.Side side; /* Kind of sale. */ SaleKindInterface.SaleKind saleKind; /* Target. */ address target; /* HowToCall. */ AuthenticatedProxy.HowToCall howToCall; /* Calldata. */ bytes calldata; /* Calldata replacement pattern, or an empty byte array for no replacement. */ bytes replacementPattern; /* Static call target, zero-address for no static call. */ address staticTarget; /* Static call extra data. */ bytes staticExtradata; /* Token used to pay for the order, or the zero-address as a sentinel value for Ether. */ address paymentToken; /* Base price of the order (in paymentTokens). */ uint basePrice; /* Auction extra parameter - minimum bid increment for English auctions, starting/ending price difference. */ uint extra; /* Listing timestamp. */ uint listingTime; /* Expiration timestamp - 0 for no expiry. */ uint expirationTime; /* Order salt, used to prevent duplicate hashes. */ uint salt; /* NOTE: uint nonce is an additional component of the order but is read from storage */ } event OrderApprovedPartOne (bytes32 indexed hash, address exchange, address indexed maker, address taker, uint makerRelayerFee, uint takerRelayerFee, uint makerProtocolFee, uint takerProtocolFee, address indexed feeRecipient, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, address target); event OrderApprovedPartTwo (bytes32 indexed hash, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, address staticTarget, bytes staticExtradata, address paymentToken, uint basePrice, uint extra, uint listingTime, uint expirationTime, uint salt, bool orderbookInclusionDesired); event OrderCancelled (bytes32 indexed hash); event OrdersMatched (bytes32 buyHash, bytes32 sellHash, address indexed maker, address indexed taker, uint price, bytes32 indexed metadata); event NonceIncremented (address indexed maker, uint newNonce); constructor () public { require(keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)") == _EIP_712_DOMAIN_TYPEHASH); require(keccak256(bytes(name)) == _NAME_HASH); require(keccak256(bytes(version)) == _VERSION_HASH); require(keccak256("Order(address exchange,address maker,address taker,uint256 makerRelayerFee,uint256 takerRelayerFee,uint256 makerProtocolFee,uint256 takerProtocolFee,address feeRecipient,uint8 feeMethod,uint8 side,uint8 saleKind,address target,uint8 howToCall,bytes calldata,bytes replacementPattern,address staticTarget,bytes staticExtradata,address paymentToken,uint256 basePrice,uint256 extra,uint256 listingTime,uint256 expirationTime,uint256 salt,uint256 nonce)") == _ORDER_TYPEHASH); } /** * @dev Derive the domain separator for EIP-712 signatures. * @return The domain separator. */ function _deriveDomainSeparator() private view returns (bytes32) { return keccak256( abi.encode( _EIP_712_DOMAIN_TYPEHASH, // keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)") _NAME_HASH, // keccak256("StarBlock Exchange Contract") _VERSION_HASH, // keccak256(bytes("1.0")) _CHAIN_ID, // NOTE: this is fixed, need to use solidity 0.5+ or make external call to support! address(this) ) ); } /** * Increment a particular maker's nonce, thereby invalidating all orders that were not signed * with the original nonce. */ function incrementNonce() external { uint newNonce = ++nonces[msg.sender]; emit NonceIncremented(msg.sender, newNonce); } function withdrawMoney() external onlyOwner reentrancyGuard { msg.sender.transfer(address(this).balance); } /** * @dev Change the minimum maker fee paid to the protocol (owner only) * @param newMinimumMakerProtocolFee New fee to set in basis points */ function changeMinimumMakerProtocolFee(uint newMinimumMakerProtocolFee) public onlyOwner { minimumMakerProtocolFee = newMinimumMakerProtocolFee; } /** * @dev Change the minimum taker fee paid to the protocol (owner only) * @param newMinimumTakerProtocolFee New fee to set in basis points */ function changeMinimumTakerProtocolFee(uint newMinimumTakerProtocolFee) public onlyOwner { minimumTakerProtocolFee = newMinimumTakerProtocolFee; } /** * @dev Change the protocol fee recipient (owner only) * @param newProtocolFeeRecipient New protocol fee recipient address */ function changeProtocolFeeRecipient(address newProtocolFeeRecipient) public onlyOwner { protocolFeeRecipient = newProtocolFeeRecipient; } /** * @dev Change exchangeToken (owner only) * @param newExchangeToken New exchangeToken */ function changeExchangeToken(ERC20 newExchangeToken) public onlyOwner { exchangeToken = newExchangeToken; } /** * @dev Transfer tokens * @param token Token to transfer * @param from Address to charge fees * @param to Address to receive fees * @param amount Amount of protocol tokens to charge */ function transferTokens(address token, address from, address to, uint amount) internal { if (amount > 0) { require(tokenTransferProxy.transferFrom(token, from, to, amount)); } } /** * @dev Charge a fee in protocol tokens * @param from Address to charge fees * @param to Address to receive fees * @param amount Amount of protocol tokens to charge */ function chargeProtocolFee(address from, address to, uint amount) internal { transferTokens(exchangeToken, from, to, amount); } /** * @dev Execute a STATICCALL (introduced with Ethereum Metropolis, non-state-modifying external call) * @param target Contract to call * @param calldata Calldata (appended to extradata) * @param extradata Base data for STATICCALL (probably function selector and argument encoding) * @return The result of the call (success or failure) */ function staticCall(address target, bytes memory calldata, bytes memory extradata) public view returns (bool result) { bytes memory combined = new bytes(calldata.length + extradata.length); uint index; assembly { index := add(combined, 0x20) } index = ArrayUtils.unsafeWriteBytes(index, extradata); ArrayUtils.unsafeWriteBytes(index, calldata); assembly { result := staticcall(gas, target, add(combined, 0x20), mload(combined), mload(0x40), 0) } return result; } /** * @dev Hash an order, returning the canonical EIP-712 order hash without the domain separator * @param order Order to hash * @param nonce maker nonce to hash * @return Hash of order */ function hashOrder(Order memory order, uint nonce) internal pure returns (bytes32 hash) { /* Unfortunately abi.encodePacked doesn't work here, stack size constraints. */ uint size = 800; bytes memory array = new bytes(size); uint index; assembly { index := add(array, 0x20) } index = ArrayUtils.unsafeWriteBytes32(index, _ORDER_TYPEHASH); index = ArrayUtils.unsafeWriteAddressWord(index, order.exchange); index = ArrayUtils.unsafeWriteAddressWord(index, order.maker); index = ArrayUtils.unsafeWriteAddressWord(index, order.taker); index = ArrayUtils.unsafeWriteUint(index, order.makerRelayerFee); index = ArrayUtils.unsafeWriteUint(index, order.takerRelayerFee); index = ArrayUtils.unsafeWriteUint(index, order.makerProtocolFee); index = ArrayUtils.unsafeWriteUint(index, order.takerProtocolFee); index = ArrayUtils.unsafeWriteAddressWord(index, order.feeRecipient); index = ArrayUtils.unsafeWriteUint8Word(index, uint8(order.feeMethod)); index = ArrayUtils.unsafeWriteUint8Word(index, uint8(order.side)); index = ArrayUtils.unsafeWriteUint8Word(index, uint8(order.saleKind)); index = ArrayUtils.unsafeWriteAddressWord(index, order.target); index = ArrayUtils.unsafeWriteUint8Word(index, uint8(order.howToCall)); index = ArrayUtils.unsafeWriteBytes32(index, keccak256(order.calldata)); index = ArrayUtils.unsafeWriteBytes32(index, keccak256(order.replacementPattern)); index = ArrayUtils.unsafeWriteAddressWord(index, order.staticTarget); index = ArrayUtils.unsafeWriteBytes32(index, keccak256(order.staticExtradata)); index = ArrayUtils.unsafeWriteAddressWord(index, order.paymentToken); index = ArrayUtils.unsafeWriteUint(index, order.basePrice); index = ArrayUtils.unsafeWriteUint(index, order.extra); index = ArrayUtils.unsafeWriteUint(index, order.listingTime); index = ArrayUtils.unsafeWriteUint(index, order.expirationTime); index = ArrayUtils.unsafeWriteUint(index, order.salt); index = ArrayUtils.unsafeWriteUint(index, nonce); assembly { hash := keccak256(add(array, 0x20), size) } return hash; } /** * @dev Hash an order, returning the hash that a client must sign via EIP-712 including the message prefix * @param order Order to hash * @param nonce Nonce to hash * @return Hash of message prefix and order hash per Ethereum format */ function hashToSign(Order memory order, uint nonce) internal pure returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, hashOrder(order, nonce)) ); } /** * @dev Assert an order is valid and return its hash * @param order Order to validate * @param nonce Nonce to validate * @param sig ECDSA signature */ function requireValidOrder(Order memory order, Sig memory sig, uint nonce) internal view returns (bytes32) { bytes32 hash = hashToSign(order, nonce); require(validateOrder(hash, order, sig)); return hash; } /** * @dev Validate order parameters (does *not* check signature validity) * @param order Order to validate */ function validateOrderParameters(Order memory order) internal view returns (bool) { /* Order must be targeted at this protocol version (this Exchange contract). */ if (order.exchange != address(this)) { return false; } /* Order must have a maker. */ if (order.maker == address(0)) { return false; } /* Order must possess valid sale kind parameter combination. */ if (!SaleKindInterface.validateParameters(order.saleKind, order.expirationTime)) { return false; } /* If using the split fee method, order must have sufficient protocol fees. */ if (order.feeMethod == FeeMethod.SplitFee && (order.makerProtocolFee < minimumMakerProtocolFee || order.takerProtocolFee < minimumTakerProtocolFee)) { return false; } return true; } /** * @dev Validate a provided previously approved / signed order, hash, and signature. * @param hash Order hash (already calculated, passed to avoid recalculation) * @param order Order to validate * @param sig ECDSA signature */ function validateOrder(bytes32 hash, Order memory order, Sig memory sig) internal view returns (bool) { /* Not done in an if-conditional to prevent unnecessary ecrecover evaluation, which seems to happen even though it should short-circuit. */ /* Order must have valid parameters. */ if (!validateOrderParameters(order)) { return false; } /* Order must have not been canceled or already filled. */ if (cancelledOrFinalized[hash]) { return false; } /* Return true if order has been previously approved with the current nonce */ uint approvedOrderNoncePlusOne = _approvedOrdersByNonce[hash]; if (approvedOrderNoncePlusOne != 0) { return approvedOrderNoncePlusOne == nonces[order.maker] + 1; } /* Prevent signature malleability and non-standard v values. */ if (uint256(sig.s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return false; } if (sig.v != 27 && sig.v != 28) { return false; } /* recover via ECDSA, signed by maker (already verified as non-zero). */ if (ecrecover(hash, sig.v, sig.r, sig.s) == order.maker) { return true; } /* fallback — attempt EIP-1271 isValidSignature check. */ return _tryContractSignature(order.maker, hash, sig); } function _tryContractSignature(address orderMaker, bytes32 hash, Sig memory sig) internal view returns (bool) { bytes memory isValidSignatureData = abi.encodeWithSelector( _EIP_1271_MAGIC_VALUE, hash, abi.encodePacked(sig.r, sig.s, sig.v) ); bytes4 result; // NOTE: solidity 0.4.x does not support STATICCALL outside of assembly assembly { let success := staticcall( // perform a staticcall gas, // forward all available gas orderMaker, // call the order maker add(isValidSignatureData, 0x20), // calldata offset comes after length mload(isValidSignatureData), // load calldata length 0, // do not use memory for return data 0 // do not use memory for return data ) if iszero(success) { // if the call fails returndatacopy(0, 0, returndatasize) // copy returndata buffer to memory revert(0, returndatasize) // revert + pass through revert data } if eq(returndatasize, 0x20) { // if returndata == 32 (one word) returndatacopy(0, 0, 0x20) // copy return data to memory in scratch space result := mload(0) // load return data from memory to the stack } } return result == _EIP_1271_MAGIC_VALUE; } /** * @dev Determine if an order has been approved. Note that the order may not still * be valid in cases where the maker's nonce has been incremented. * @param hash Hash of the order * @return whether or not the order was approved. */ function approvedOrders(bytes32 hash) public view returns (bool approved) { return _approvedOrdersByNonce[hash] != 0; } /** * @dev Approve an order and optionally mark it for orderbook inclusion. Must be called by the maker of the order * @param order Order to approve * @param orderbookInclusionDesired Whether orderbook providers should include the order in their orderbooks */ function approveOrder(Order memory order, bool orderbookInclusionDesired) internal { /* CHECKS */ /* Assert sender is authorized to approve order. */ require(msg.sender == order.maker); /* Calculate order hash. */ bytes32 hash = hashToSign(order, nonces[order.maker]); /* Assert order has not already been approved. */ require(_approvedOrdersByNonce[hash] == 0); /* EFFECTS */ /* Mark order as approved. */ _approvedOrdersByNonce[hash] = nonces[order.maker] + 1; /* Log approval event. Must be split in two due to Solidity stack size limitations. */ { emit OrderApprovedPartOne(hash, order.exchange, order.maker, order.taker, order.makerRelayerFee, order.takerRelayerFee, order.makerProtocolFee, order.takerProtocolFee, order.feeRecipient, order.feeMethod, order.side, order.saleKind, order.target); } { emit OrderApprovedPartTwo(hash, order.howToCall, order.calldata, order.replacementPattern, order.staticTarget, order.staticExtradata, order.paymentToken, order.basePrice, order.extra, order.listingTime, order.expirationTime, order.salt, orderbookInclusionDesired); } } /** * @dev Cancel an order, preventing it from being matched. Must be called by the maker of the order * @param order Order to cancel * @param nonce Nonce to cancel * @param sig ECDSA signature */ function cancelOrder(Order memory order, Sig memory sig, uint nonce) internal { /* CHECKS */ /* Calculate order hash. */ bytes32 hash = requireValidOrder(order, sig, nonce); /* Assert sender is authorized to cancel order. */ require(msg.sender == order.maker); /* EFFECTS */ /* Mark order as cancelled, preventing it from being matched. */ cancelledOrFinalized[hash] = true; /* Log cancel event. */ emit OrderCancelled(hash); } /** * @dev Calculate the current price of an order (convenience function) * @param order Order to calculate the price of * @return The current price of the order */ function calculateCurrentPrice (Order memory order) internal view returns (uint) { return SaleKindInterface.calculateFinalPrice(order.side, order.saleKind, order.basePrice, order.extra, order.listingTime, order.expirationTime); } /** * @dev Calculate the price two orders would match at, if in fact they would match (otherwise fail) * @param buy Buy-side order * @param sell Sell-side order * @return Match price */ function calculateMatchPrice(Order memory buy, Order memory sell) view internal returns (uint) { /* Calculate sell price. */ uint sellPrice = SaleKindInterface.calculateFinalPrice(sell.side, sell.saleKind, sell.basePrice, sell.extra, sell.listingTime, sell.expirationTime); /* Calculate buy price. */ uint buyPrice = SaleKindInterface.calculateFinalPrice(buy.side, buy.saleKind, buy.basePrice, buy.extra, buy.listingTime, buy.expirationTime); /* Require price cross. */ require(buyPrice >= sellPrice); /* Maker/taker priority. */ return sell.feeRecipient != address(0) ? sellPrice : buyPrice; } /** * @dev Execute all ERC20 token / Ether transfers associated with an order match (fees and buyer => seller transfer) * @param buy Buy-side order * @param sell Sell-side order */ function executeFundsTransfer(Order memory buy, Order memory sell) internal returns (uint) { /* Only payable in the special case of unwrapped Ether. */ if (sell.paymentToken != address(0)) { require(msg.value == 0); } /* Calculate match price. */ uint price = calculateMatchPrice(buy, sell); /* If paying using a token (not Ether), transfer tokens. This is done prior to fee payments to that a seller will have tokens before being charged fees. */ if (price > 0 && sell.paymentToken != address(0)) { transferTokens(sell.paymentToken, buy.maker, sell.maker, price); } /* Amount that will be received by seller (for Ether). */ uint receiveAmount = price; /* Amount that must be sent by buyer (for Ether). */ uint requiredAmount = price; /* Determine maker/taker and charge fees accordingly. */ if (sell.feeRecipient != address(0)) { /* Sell-side order is maker. */ /* Assert taker fee is less than or equal to maximum fee specified by buyer. */ require(sell.takerRelayerFee <= buy.takerRelayerFee); if (sell.feeMethod == FeeMethod.SplitFee) { /* Assert taker fee is less than or equal to maximum fee specified by buyer. */ require(sell.takerProtocolFee <= buy.takerProtocolFee); /* Maker fees are deducted from the token amount that the maker receives. Taker fees are extra tokens that must be paid by the taker. */ if (sell.makerRelayerFee > 0) { uint makerRelayerFee = SafeMath.div(SafeMath.mul(sell.makerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerRelayerFee); sell.feeRecipient.transfer(makerRelayerFee); } else { transferTokens(sell.paymentToken, sell.maker, sell.feeRecipient, makerRelayerFee); } } if (sell.takerRelayerFee > 0) { uint takerRelayerFee = SafeMath.div(SafeMath.mul(sell.takerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerRelayerFee); sell.feeRecipient.transfer(takerRelayerFee); } else { transferTokens(sell.paymentToken, buy.maker, sell.feeRecipient, takerRelayerFee); } } if (sell.makerProtocolFee > 0) { uint makerProtocolFee = SafeMath.div(SafeMath.mul(sell.makerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerProtocolFee); protocolFeeRecipient.transfer(makerProtocolFee); } else { transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, makerProtocolFee); } } if (sell.takerProtocolFee > 0) { uint takerProtocolFee = SafeMath.div(SafeMath.mul(sell.takerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerProtocolFee); protocolFeeRecipient.transfer(takerProtocolFee); } else { transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, takerProtocolFee); } } } else { /* Charge maker fee to seller. */ chargeProtocolFee(sell.maker, sell.feeRecipient, sell.makerRelayerFee); /* Charge taker fee to buyer. */ chargeProtocolFee(buy.maker, sell.feeRecipient, sell.takerRelayerFee); } } else { /* Buy-side order is maker. */ /* Assert taker fee is less than or equal to maximum fee specified by seller. */ require(buy.takerRelayerFee <= sell.takerRelayerFee); if (sell.feeMethod == FeeMethod.SplitFee) { /* The Exchange does not escrow Ether, so direct Ether can only be used to with sell-side maker / buy-side taker orders. */ require(sell.paymentToken != address(0)); /* Assert taker fee is less than or equal to maximum fee specified by seller. */ require(buy.takerProtocolFee <= sell.takerProtocolFee); if (buy.makerRelayerFee > 0) { makerRelayerFee = SafeMath.div(SafeMath.mul(buy.makerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, buy.feeRecipient, makerRelayerFee); } if (buy.takerRelayerFee > 0) { takerRelayerFee = SafeMath.div(SafeMath.mul(buy.takerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, buy.feeRecipient, takerRelayerFee); } if (buy.makerProtocolFee > 0) { makerProtocolFee = SafeMath.div(SafeMath.mul(buy.makerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, makerProtocolFee); } if (buy.takerProtocolFee > 0) { takerProtocolFee = SafeMath.div(SafeMath.mul(buy.takerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, takerProtocolFee); } } else { /* Charge maker fee to buyer. */ chargeProtocolFee(buy.maker, buy.feeRecipient, buy.makerRelayerFee); /* Charge taker fee to seller. */ chargeProtocolFee(sell.maker, buy.feeRecipient, buy.takerRelayerFee); } } if (sell.paymentToken == address(0)) { /* Special-case Ether, order must be matched by buyer. */ require(msg.value >= requiredAmount); sell.maker.transfer(receiveAmount); /* Allow overshoot for variable-price auctions, refund difference. */ uint diff = SafeMath.sub(msg.value, requiredAmount); if (diff > 0) { buy.maker.transfer(diff); } } /* This contract should never hold Ether, however, we cannot assert this, since it is impossible to prevent anyone from sending Ether e.g. with selfdestruct. */ return price; } /** * @dev Return whether or not two orders can be matched with each other by basic parameters (does not check order signatures / calldata or perform static calls) * @param buy Buy-side order * @param sell Sell-side order * @return Whether or not the two orders can be matched */ function ordersCanMatch(Order memory buy, Order memory sell) internal view returns (bool) { return ( /* Must be opposite-side. */ (buy.side == SaleKindInterface.Side.Buy && sell.side == SaleKindInterface.Side.Sell) && /* Must use same fee method. */ (buy.feeMethod == sell.feeMethod) && /* Must use same payment token. */ (buy.paymentToken == sell.paymentToken) && /* Must match maker/taker addresses. */ (sell.taker == address(0) || sell.taker == buy.maker) && (buy.taker == address(0) || buy.taker == sell.maker) && /* One must be maker and the other must be taker (no bool XOR in Solidity). */ ((sell.feeRecipient == address(0) && buy.feeRecipient != address(0)) || (sell.feeRecipient != address(0) && buy.feeRecipient == address(0))) && /* Must match target. */ (buy.target == sell.target) && /* Must match howToCall. */ (buy.howToCall == sell.howToCall) && /* Buy-side order must be settleable. */ SaleKindInterface.canSettleOrder(buy.listingTime, buy.expirationTime) && /* Sell-side order must be settleable. */ SaleKindInterface.canSettleOrder(sell.listingTime, sell.expirationTime) ); } /** * @dev Atomically match two orders, ensuring validity of the match, and execute all associated state transitions. Protected against reentrancy by a contract-global lock. * @param buy Buy-side order * @param buySig Buy-side order signature * @param sell Sell-side order * @param sellSig Sell-side order signature */ function atomicMatch(Order memory buy, Sig memory buySig, Order memory sell, Sig memory sellSig, bytes32 metadata) internal reentrancyGuard { /* CHECKS */ /* Ensure buy order validity and calculate hash if necessary. */ bytes32 buyHash; if (buy.maker == msg.sender) { require(validateOrderParameters(buy)); } else { buyHash = _requireValidOrderWithNonce(buy, buySig); } /* Ensure sell order validity and calculate hash if necessary. */ bytes32 sellHash; if (sell.maker == msg.sender) { require(validateOrderParameters(sell)); } else { sellHash = _requireValidOrderWithNonce(sell, sellSig); } /* Must be matchable. */ require(ordersCanMatch(buy, sell)); /* Target must exist (prevent malicious selfdestructs just prior to order settlement). */ uint size; address target = sell.target; assembly { size := extcodesize(target) } require(size > 0); /* Must match calldata after replacement, if specified. */ if (buy.replacementPattern.length > 0) { ArrayUtils.guardedArrayReplace(buy.calldata, sell.calldata, buy.replacementPattern); } if (sell.replacementPattern.length > 0) { ArrayUtils.guardedArrayReplace(sell.calldata, buy.calldata, sell.replacementPattern); } require(ArrayUtils.arrayEq(buy.calldata, sell.calldata)); /* Retrieve delegateProxy contract. */ OwnableDelegateProxy delegateProxy = registry.proxies(sell.maker); /* Proxy must exist. */ require(delegateProxy != address(0)); /* Access the passthrough AuthenticatedProxy. */ AuthenticatedProxy proxy = AuthenticatedProxy(delegateProxy); /* EFFECTS */ /* Mark previously signed or approved orders as finalized. */ if (msg.sender != buy.maker) { cancelledOrFinalized[buyHash] = true; } if (msg.sender != sell.maker && sell.saleKind != SaleKindInterface.SaleKind.CollectionRandomSale) { cancelledOrFinalized[sellHash] = true; } /* INTERACTIONS */ /* change the baseprice based on the qutity. */ if (sell.saleKind == SaleKindInterface.SaleKind.CollectionRandomSale) { uint256 quantity = getQuantity(buy); if (quantity > 1) { sell.basePrice = SafeMath.mul(sell.basePrice, quantity); buy.basePrice = sell.basePrice; } } /* Execute funds transfer and pay fees. */ uint price = executeFundsTransfer(buy, sell); /* Assert implementation. */ require(delegateProxy.implementation() == registry.delegateProxyImplementation()); /* Execute specified call through proxy. */ require(proxy.proxy(sell.target, sell.howToCall, sell.calldata)); /* Static calls are intentionally done after the effectful call so they can check resulting state. */ /* Handle buy-side static call if specified. */ if (buy.staticTarget != address(0)) { require(staticCall(buy.staticTarget, sell.calldata, buy.staticExtradata)); } /* Handle sell-side static call if specified. */ if (sell.staticTarget != address(0)) { require(staticCall(sell.staticTarget, sell.calldata, sell.staticExtradata)); } /* Log match event. */ emit OrdersMatched(buyHash, sellHash, sell.feeRecipient != address(0) ? sell.maker : buy.maker, sell.feeRecipient != address(0) ? buy.maker : sell.maker, price, metadata); } function _requireValidOrderWithNonce(Order memory order, Sig memory sig) internal view returns (bytes32) { return requireValidOrder(order, sig, nonces[order.maker]); } function getQuantity(Order memory buy) internal pure returns (uint256) { bytes memory quantityBytes = new bytes(2); uint index = SafeMath.sub(buy.calldata.length, 2); uint lastIndex = SafeMath.sub(buy.calldata.length, 1); quantityBytes[0] = buy.calldata[index]; quantityBytes[1] = buy.calldata[lastIndex]; uint256 quantity = bytesToUint(quantityBytes); return quantity; } function bytesToUint(bytes memory b) internal pure returns (uint256) { uint256 number; for(uint i = 0; i< b.length; i++) { uint index = SafeMath.add(i, 1); uint length = SafeMath.sub(b.length, index); uint offset = 2**SafeMath.mul(8, length); uint offsetCount = SafeMath.mul(uint8(b[i]), offset); number = SafeMath.add(number, offsetCount); } return number; } } contract Exchange is ExchangeCore { /** * @dev Call guardedArrayReplace - library function exposed for testing. */ function guardedArrayReplace(bytes array, bytes desired, bytes mask) public pure returns (bytes) { ArrayUtils.guardedArrayReplace(array, desired, mask); return array; } /** * @dev Call calculateFinalPrice - library function exposed for testing. */ function calculateFinalPrice(SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, uint basePrice, uint extra, uint listingTime, uint expirationTime) public view returns (uint) { return SaleKindInterface.calculateFinalPrice(side, saleKind, basePrice, extra, listingTime, expirationTime); } /** * @dev Call hashOrder - Solidity ABI encoding limitation workaround, hopefully temporary. */ function hashOrder_( address[7] addrs, uint[9] uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, bytes staticExtradata) public view returns (bytes32) { return hashOrder( Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, calldata, replacementPattern, addrs[5], staticExtradata, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]), nonces[addrs[1]] ); } /** * @dev Call hashToSign - Solidity ABI encoding limitation workaround, hopefully temporary. */ function hashToSign_( address[7] addrs, uint[9] uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, bytes staticExtradata) public view returns (bytes32) { return hashToSign( Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, calldata, replacementPattern, addrs[5], staticExtradata, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]), nonces[addrs[1]] ); } /** * @dev Call validateOrderParameters - Solidity ABI encoding limitation workaround, hopefully temporary. */ function validateOrderParameters_ ( address[7] addrs, uint[9] uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, bytes staticExtradata) view public returns (bool) { Order memory order = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, calldata, replacementPattern, addrs[5], staticExtradata, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]); return validateOrderParameters( order ); } /** * @dev Call validateOrder - Solidity ABI encoding limitation workaround, hopefully temporary. */ function validateOrder_ ( address[7] addrs, uint[9] uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, bytes staticExtradata, uint8 v, bytes32 r, bytes32 s) view public returns (bool) { Order memory order = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, calldata, replacementPattern, addrs[5], staticExtradata, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]); return validateOrder( hashToSign(order, nonces[order.maker]), order, Sig(v, r, s) ); } /** * @dev Call approveOrder - Solidity ABI encoding limitation workaround, hopefully temporary. */ function approveOrder_ ( address[7] addrs, uint[9] uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, bytes staticExtradata, bool orderbookInclusionDesired) public { Order memory order = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, calldata, replacementPattern, addrs[5], staticExtradata, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]); return approveOrder(order, orderbookInclusionDesired); } /** * @dev Call cancelOrder - Solidity ABI encoding limitation workaround, hopefully temporary. */ function cancelOrder_( address[7] addrs, uint[9] uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, bytes staticExtradata, uint8 v, bytes32 r, bytes32 s) public { Order memory order = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, calldata, replacementPattern, addrs[5], staticExtradata, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]); return cancelOrder( order, Sig(v, r, s), nonces[order.maker] ); } /** * @dev Call cancelOrder, supplying a specific nonce — enables cancelling orders that were signed with nonces greater than the current nonce. */ function cancelOrderWithNonce_( address[7] addrs, uint[9] uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, bytes staticExtradata, uint8 v, bytes32 r, bytes32 s, uint nonce) public { Order memory order = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, calldata, replacementPattern, addrs[5], staticExtradata, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]); return cancelOrder( order, Sig(v, r, s), nonce ); } /** * @dev Call calculateCurrentPrice - Solidity ABI encoding limitation workaround, hopefully temporary. */ function calculateCurrentPrice_( address[7] addrs, uint[9] uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, bytes staticExtradata) public view returns (uint) { return calculateCurrentPrice( Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, calldata, replacementPattern, addrs[5], staticExtradata, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]) ); } /** * @dev Call ordersCanMatch - Solidity ABI encoding limitation workaround, hopefully temporary. */ function ordersCanMatch_( address[14] addrs, uint[18] uints, uint8[8] feeMethodsSidesKindsHowToCalls, bytes calldataBuy, bytes calldataSell, bytes replacementPatternBuy, bytes replacementPatternSell, bytes staticExtradataBuy, bytes staticExtradataSell) public view returns (bool) { Order memory buy = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], FeeMethod(feeMethodsSidesKindsHowToCalls[0]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[1]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[2]), addrs[4], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[3]), calldataBuy, replacementPatternBuy, addrs[5], staticExtradataBuy, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]); Order memory sell = Order(addrs[7], addrs[8], addrs[9], uints[9], uints[10], uints[11], uints[12], addrs[10], FeeMethod(feeMethodsSidesKindsHowToCalls[4]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[5]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[6]), addrs[11], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[7]), calldataSell, replacementPatternSell, addrs[12], staticExtradataSell, ERC20(addrs[13]), uints[13], uints[14], uints[15], uints[16], uints[17]); return ordersCanMatch( buy, sell ); } /** * @dev Return whether or not two orders' calldata specifications can match * @param buyCalldata Buy-side order calldata * @param buyReplacementPattern Buy-side order calldata replacement mask * @param sellCalldata Sell-side order calldata * @param sellReplacementPattern Sell-side order calldata replacement mask * @return Whether the orders' calldata can be matched */ function orderCalldataCanMatch(bytes buyCalldata, bytes buyReplacementPattern, bytes sellCalldata, bytes sellReplacementPattern) public pure returns (bool) { if (buyReplacementPattern.length > 0) { ArrayUtils.guardedArrayReplace(buyCalldata, sellCalldata, buyReplacementPattern); } if (sellReplacementPattern.length > 0) { ArrayUtils.guardedArrayReplace(sellCalldata, buyCalldata, sellReplacementPattern); } return ArrayUtils.arrayEq(buyCalldata, sellCalldata); } /** * @dev Call calculateMatchPrice - Solidity ABI encoding limitation workaround, hopefully temporary. */ function calculateMatchPrice_( address[14] addrs, uint[18] uints, uint8[8] feeMethodsSidesKindsHowToCalls, bytes calldataBuy, bytes calldataSell, bytes replacementPatternBuy, bytes replacementPatternSell, bytes staticExtradataBuy, bytes staticExtradataSell) public view returns (uint) { Order memory buy = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], FeeMethod(feeMethodsSidesKindsHowToCalls[0]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[1]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[2]), addrs[4], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[3]), calldataBuy, replacementPatternBuy, addrs[5], staticExtradataBuy, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]); Order memory sell = Order(addrs[7], addrs[8], addrs[9], uints[9], uints[10], uints[11], uints[12], addrs[10], FeeMethod(feeMethodsSidesKindsHowToCalls[4]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[5]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[6]), addrs[11], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[7]), calldataSell, replacementPatternSell, addrs[12], staticExtradataSell, ERC20(addrs[13]), uints[13], uints[14], uints[15], uints[16], uints[17]); return calculateMatchPrice( buy, sell ); } /** * @dev Call atomicMatch - Solidity ABI encoding limitation workaround, hopefully temporary. */ function atomicMatch_( address[14] addrs, uint[18] uints, uint8[8] feeMethodsSidesKindsHowToCalls, bytes calldataBuy, bytes calldataSell, bytes replacementPatternBuy, bytes replacementPatternSell, bytes staticExtradataBuy, bytes staticExtradataSell, uint8[2] vs, bytes32[5] rssMetadata) public payable callerIsUser { return atomicMatch( Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], FeeMethod(feeMethodsSidesKindsHowToCalls[0]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[1]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[2]), addrs[4], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[3]), calldataBuy, replacementPatternBuy, addrs[5], staticExtradataBuy, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]), Sig(vs[0], rssMetadata[0], rssMetadata[1]), Order(addrs[7], addrs[8], addrs[9], uints[9], uints[10], uints[11], uints[12], addrs[10], FeeMethod(feeMethodsSidesKindsHowToCalls[4]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[5]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[6]), addrs[11], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[7]), calldataSell, replacementPatternSell, addrs[12], staticExtradataSell, ERC20(addrs[13]), uints[13], uints[14], uints[15], uints[16], uints[17]), Sig(vs[1], rssMetadata[2], rssMetadata[3]), rssMetadata[4] ); } modifier callerIsUser() { require(tx.origin == msg.sender, "The caller is another contract"); _; } } contract StarBlockExchange is Exchange { string public constant codename = "Bulk Smash"; /** * @dev Initialize a WyvernExchange instance * @param registryAddress Address of the registry instance which this Exchange instance will use * @param tokenAddress Address of the token used for protocol fees */ constructor (ProxyRegistry registryAddress, TokenTransferProxy tokenTransferProxyAddress, ERC20 tokenAddress, address protocolFeeAddress) public { registry = registryAddress; tokenTransferProxy = tokenTransferProxyAddress; exchangeToken = tokenAddress; protocolFeeRecipient = protocolFeeAddress; owner = msg.sender; } } library SaleKindInterface { /** * Side: buy or sell. */ enum Side { Buy, Sell } /** * Currently supported kinds of sale: fixed price, Dutch auction. * English auctions cannot be supported without stronger escrow guarantees. * Future interesting options: Vickrey auction, nonlinear Dutch auctions. */ enum SaleKind { FixedPrice, DutchAuction, CollectionRandomSale } /** * @dev Check whether the parameters of a sale are valid * @param saleKind Kind of sale * @param expirationTime Order expiration time * @return Whether the parameters were valid */ function validateParameters(SaleKind saleKind, uint expirationTime) pure internal returns (bool) { /* Auctions must have a set expiration date. */ if (expirationTime > 0 ) { return true; }else { if (saleKind == SaleKind.FixedPrice || saleKind == SaleKind.CollectionRandomSale) { return true; } } return false; } /** * @dev Return whether or not an order can be settled * @dev Precondition: parameters have passed validateParameters * @param listingTime Order listing time * @param expirationTime Order expiration time */ function canSettleOrder(uint listingTime, uint expirationTime) view internal returns (bool) { return (listingTime < now) && (expirationTime == 0 || now < expirationTime); } /** * @dev Calculate the settlement price of an order * @dev Precondition: parameters have passed validateParameters. * @param side Order side * @param saleKind Method of sale * @param basePrice Order base price * @param extra Order extra price data * @param listingTime Order listing time * @param expirationTime Order expiration time */ function calculateFinalPrice(Side side, SaleKind saleKind, uint basePrice, uint extra, uint listingTime, uint expirationTime) view internal returns (uint finalPrice) { if (saleKind == SaleKind.FixedPrice || saleKind == SaleKind.CollectionRandomSale) { return basePrice; } else if (saleKind == SaleKind.DutchAuction) { uint diff = SafeMath.div(SafeMath.mul(extra, SafeMath.sub(now, listingTime)), SafeMath.sub(expirationTime, listingTime)); if (side == Side.Sell) { /* Sell-side - start price: basePrice. End price: basePrice - extra. */ return SafeMath.sub(basePrice, diff); } else { /* Buy-side - start price: basePrice. End price: basePrice + extra. */ return SafeMath.add(basePrice, diff); } } } } contract ProxyRegistry is Ownable { /* DelegateProxy implementation contract. Must be initialized. */ address public delegateProxyImplementation; /* Authenticated proxies by user. */ mapping(address => OwnableDelegateProxy) public proxies; /* Contracts pending access. */ mapping(address => uint) public pending; /* Contracts allowed to call those proxies. */ mapping(address => bool) public contracts; /* Delay period for adding an authenticated contract. This mitigates a particular class of potential attack on the Wyvern DAO (which owns this registry) - if at any point the value of assets held by proxy contracts exceeded the value of half the WYV supply (votes in the DAO), a malicious but rational attacker could buy half the Wyvern and grant themselves access to all the proxy contracts. A delay period renders this attack nonthreatening - given two weeks, if that happened, users would have plenty of time to notice and transfer their assets. */ uint public DELAY_PERIOD = 2 weeks; /** * Start the process to enable access for specified contract. Subject to delay period. * * @dev ProxyRegistry owner only * @param addr Address to which to grant permissions */ function startGrantAuthentication (address addr) public onlyOwner { require(!contracts[addr] && pending[addr] == 0); pending[addr] = now; } /** * End the process to nable access for specified contract after delay period has passed. * * @dev ProxyRegistry owner only * @param addr Address to which to grant permissions */ function endGrantAuthentication (address addr) public onlyOwner { require(!contracts[addr] && pending[addr] != 0 && ((pending[addr] + DELAY_PERIOD) < now)); pending[addr] = 0; contracts[addr] = true; } /** * Revoke access for specified contract. Can be done instantly. * * @dev ProxyRegistry owner only * @param addr Address of which to revoke permissions */ function revokeAuthentication (address addr) public onlyOwner { contracts[addr] = false; } /** * Register a proxy contract with this registry * * @dev Must be called by the user which the proxy is for, creates a new AuthenticatedProxy * @return New AuthenticatedProxy contract */ function registerProxy() public returns (OwnableDelegateProxy proxy) { require(proxies[msg.sender] == address(0)); proxy = new OwnableDelegateProxy(msg.sender, delegateProxyImplementation, abi.encodeWithSignature("initialize(address,address)", msg.sender, address(this))); proxies[msg.sender] = proxy; return proxy; } } contract TokenTransferProxy { /* Authentication registry. */ ProxyRegistry public registry; /** * Call ERC20 `transferFrom` * * @dev Authenticated contract only * @param token ERC20 token address * @param from From address * @param to To address * @param amount Transfer amount */ function transferFrom(address token, address from, address to, uint amount) public returns (bool) { require(registry.contracts(msg.sender)); return ERC20(token).transferFrom(from, to, amount); } } contract OwnedUpgradeabilityStorage { // Current implementation address internal _implementation; // Owner of the contract address private _upgradeabilityOwner; /** * @dev Tells the address of the owner * @return the address of the owner */ function upgradeabilityOwner() public view returns (address) { return _upgradeabilityOwner; } /** * @dev Sets the address of the owner */ function setUpgradeabilityOwner(address newUpgradeabilityOwner) internal { _upgradeabilityOwner = newUpgradeabilityOwner; } /** * @dev Tells the address of the current implementation * @return address of the current implementation */ function implementation() public view returns (address) { return _implementation; } /** * @dev Tells the proxy type (EIP 897) * @return Proxy type, 2 for forwarding proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return 2; } } contract AuthenticatedProxy is TokenRecipient, OwnedUpgradeabilityStorage { /* Whether initialized. */ bool initialized = false; /* Address which owns this proxy. */ address public user; /* Associated registry with contract authentication information. */ ProxyRegistry public registry; /* Whether access has been revoked. */ bool public revoked; /* Delegate call could be used to atomically transfer multiple assets owned by the proxy contract with one order. */ enum HowToCall { Call, DelegateCall } /* Event fired when the proxy access is revoked or unrevoked. */ event Revoked(bool revoked); /** * Initialize an AuthenticatedProxy * * @param addrUser Address of user on whose behalf this proxy will act * @param addrRegistry Address of ProxyRegistry contract which will manage this proxy */ function initialize (address addrUser, ProxyRegistry addrRegistry) public { require(!initialized); initialized = true; user = addrUser; registry = addrRegistry; } /** * Set the revoked flag (allows a user to revoke ProxyRegistry access) * * @dev Can be called by the user only * @param revoke Whether or not to revoke access */ function setRevoke(bool revoke) public { require(msg.sender == user); revoked = revoke; emit Revoked(revoke); } /** * Execute a message call from the proxy contract * * @dev Can be called by the user, or by a contract authorized by the registry as long as the user has not revoked access * @param dest Address to which the call will be sent * @param howToCall Which kind of call to make * @param calldata Calldata to send * @return Result of the call (success or failure) */ function proxy(address dest, HowToCall howToCall, bytes calldata) public returns (bool result) { require(msg.sender == user || (!revoked && registry.contracts(msg.sender))); if (howToCall == HowToCall.Call) { result = dest.call(calldata); } else if (howToCall == HowToCall.DelegateCall) { result = dest.delegatecall(calldata); } return result; } /** * Execute a message call and assert success * * @dev Same functionality as `proxy`, just asserts the return value * @param dest Address to which the call will be sent * @param howToCall What kind of call to make * @param calldata Calldata to send */ function proxyAssert(address dest, HowToCall howToCall, bytes calldata) public { require(proxy(dest, howToCall, calldata)); } } contract Proxy { /** * @dev Tells the address of the implementation where every call will be delegated. * @return address of the implementation to which it will be delegated */ function implementation() public view returns (address); /** * @dev Tells the type of proxy (EIP 897) * @return Type of proxy, 2 for upgradeable proxy */ function proxyType() public pure returns (uint256 proxyTypeId); /** * @dev Fallback function allowing to perform a delegatecall to the given implementation. * This function will return whatever the implementation call returns */ function () payable public { address _impl = implementation(); require(_impl != address(0)); assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize) let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0) let size := returndatasize returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } } contract OwnedUpgradeabilityProxy is Proxy, OwnedUpgradeabilityStorage { /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event ProxyOwnershipTransferred(address previousOwner, address newOwner); /** * @dev This event will be emitted every time the implementation gets upgraded * @param implementation representing the address of the upgraded implementation */ event Upgraded(address indexed implementation); /** * @dev Upgrades the implementation address * @param implementation representing the address of the new implementation to be set */ function _upgradeTo(address implementation) internal { require(_implementation != implementation); _implementation = implementation; emit Upgraded(implementation); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyProxyOwner() { require(msg.sender == proxyOwner()); _; } /** * @dev Tells the address of the proxy owner * @return the address of the proxy owner */ function proxyOwner() public view returns (address) { return upgradeabilityOwner(); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferProxyOwnership(address newOwner) public onlyProxyOwner { require(newOwner != address(0)); emit ProxyOwnershipTransferred(proxyOwner(), newOwner); setUpgradeabilityOwner(newOwner); } /** * @dev Allows the upgradeability owner to upgrade the current implementation of the proxy. * @param implementation representing the address of the new implementation to be set. */ function upgradeTo(address implementation) public onlyProxyOwner { _upgradeTo(implementation); } /** * @dev Allows the upgradeability owner to upgrade the current implementation of the proxy * and delegatecall the new implementation for initialization. * @param implementation representing the address of the new implementation to be set. * @param data represents the msg.data to bet sent in the low level call. This parameter may include the function * signature of the implementation to be called with the needed payload */ function upgradeToAndCall(address implementation, bytes data) payable public onlyProxyOwner { upgradeTo(implementation); require(address(this).delegatecall(data)); } } contract OwnableDelegateProxy is OwnedUpgradeabilityProxy { constructor(address owner, address initialImplementation, bytes calldata) public { setUpgradeabilityOwner(owner); _upgradeTo(initialImplementation); require(initialImplementation.delegatecall(calldata)); } }
NOTE: solidity 0.4.x does not support STATICCALL outside of assembly
function _tryContractSignature(address orderMaker, bytes32 hash, Sig memory sig) internal view returns (bool) { bytes memory isValidSignatureData = abi.encodeWithSelector( _EIP_1271_MAGIC_VALUE, hash, abi.encodePacked(sig.r, sig.s, sig.v) ); bytes4 result; assembly { ) } }
251,929
/** *Submitted for verification at Etherscan.io on 2021-09-15 */ // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.8.0; // Sources flattened with hardhat v2.6.2 https://hardhat.org // File contracts/Math/SafeMath.sol /** * @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/FXS/IFxs.sol interface IFxs { function DEFAULT_ADMIN_ROLE() external view returns(bytes32); function FRAXStablecoinAdd() external view returns(address); function FXS_DAO_min() external view returns(uint256); function allowance(address owner, address spender) external view returns(uint256); function approve(address spender, uint256 amount) external returns(bool); function balanceOf(address account) external view returns(uint256); function burn(uint256 amount) external; function burnFrom(address account, uint256 amount) external; function checkpoints(address, uint32) external view returns(uint32 fromBlock, uint96 votes); function decimals() external view returns(uint8); function decreaseAllowance(address spender, uint256 subtractedValue) external returns(bool); function genesis_supply() external view returns(uint256); function getCurrentVotes(address account) external view returns(uint96); function getPriorVotes(address account, uint256 blockNumber) external view returns(uint96); function getRoleAdmin(bytes32 role) external view returns(bytes32); function getRoleMember(bytes32 role, uint256 index) external view returns(address); function getRoleMemberCount(bytes32 role) external view returns(uint256); function grantRole(bytes32 role, address account) external; function hasRole(bytes32 role, address account) external view returns(bool); function increaseAllowance(address spender, uint256 addedValue) external returns(bool); function mint(address to, uint256 amount) external; function name() external view returns(string memory); function numCheckpoints(address) external view returns(uint32); function oracle_address() external view returns(address); function owner_address() external view returns(address); function pool_burn_from(address b_address, uint256 b_amount) external; function pool_mint(address m_address, uint256 m_amount) external; function renounceRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function setFRAXAddress(address frax_contract_address) external; function setFXSMinDAO(uint256 min_FXS) external; function setOracle(address new_oracle) external; function setOwner(address _owner_address) external; function setTimelock(address new_timelock) external; function symbol() external view returns(string memory); function timelock_address() external view returns(address); function toggleVotes() external; function totalSupply() external view returns(uint256); function trackingVotes() external view returns(bool); function transfer(address recipient, uint256 amount) external returns(bool); function transferFrom(address sender, address recipient, uint256 amount) external returns(bool); } // File contracts/Frax/IFrax.sol interface IFrax { function COLLATERAL_RATIO_PAUSER() external view returns (bytes32); function DEFAULT_ADMIN_ADDRESS() external view returns (address); function DEFAULT_ADMIN_ROLE() external view returns (bytes32); function addPool(address pool_address ) external; function allowance(address owner, address spender ) external view returns (uint256); function approve(address spender, uint256 amount ) external returns (bool); function balanceOf(address account ) external view returns (uint256); function burn(uint256 amount ) external; function burnFrom(address account, uint256 amount ) external; function collateral_ratio_paused() external view returns (bool); function controller_address() external view returns (address); function creator_address() external view returns (address); function decimals() external view returns (uint8); function decreaseAllowance(address spender, uint256 subtractedValue ) external returns (bool); function eth_usd_consumer_address() external view returns (address); function eth_usd_price() external view returns (uint256); function frax_eth_oracle_address() external view returns (address); function frax_info() external view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256); function frax_pools(address ) external view returns (bool); function frax_pools_array(uint256 ) external view returns (address); function frax_price() external view returns (uint256); function frax_step() external view returns (uint256); function fxs_address() external view returns (address); function fxs_eth_oracle_address() external view returns (address); function fxs_price() external view returns (uint256); function genesis_supply() external view returns (uint256); function getRoleAdmin(bytes32 role ) external view returns (bytes32); function getRoleMember(bytes32 role, uint256 index ) external view returns (address); function getRoleMemberCount(bytes32 role ) external view returns (uint256); function globalCollateralValue() external view returns (uint256); function global_collateral_ratio() external view returns (uint256); function grantRole(bytes32 role, address account ) external; function hasRole(bytes32 role, address account ) external view returns (bool); function increaseAllowance(address spender, uint256 addedValue ) external returns (bool); function last_call_time() external view returns (uint256); function minting_fee() external view returns (uint256); function name() external view returns (string memory); function owner_address() external view returns (address); function pool_burn_from(address b_address, uint256 b_amount ) external; function pool_mint(address m_address, uint256 m_amount ) external; function price_band() external view returns (uint256); function price_target() external view returns (uint256); function redemption_fee() external view returns (uint256); function refreshCollateralRatio() external; function refresh_cooldown() external view returns (uint256); function removePool(address pool_address ) external; function renounceRole(bytes32 role, address account ) external; function revokeRole(bytes32 role, address account ) external; function setController(address _controller_address ) external; function setETHUSDOracle(address _eth_usd_consumer_address ) external; function setFRAXEthOracle(address _frax_oracle_addr, address _weth_address ) external; function setFXSAddress(address _fxs_address ) external; function setFXSEthOracle(address _fxs_oracle_addr, address _weth_address ) external; function setFraxStep(uint256 _new_step ) external; function setMintingFee(uint256 min_fee ) external; function setOwner(address _owner_address ) external; function setPriceBand(uint256 _price_band ) external; function setPriceTarget(uint256 _new_price_target ) external; function setRedemptionFee(uint256 red_fee ) external; function setRefreshCooldown(uint256 _new_cooldown ) external; function setTimelock(address new_timelock ) external; function symbol() external view returns (string memory); function timelock_address() external view returns (address); function toggleCollateralRatio() external; function totalSupply() external view returns (uint256); function transfer(address recipient, uint256 amount ) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount ) external returns (bool); function weth_address() external view returns (address); } // File contracts/Frax/IFraxAMOMinter.sol // MAY need to be updated interface IFraxAMOMinter { function FRAX() external view returns(address); function FXS() external view returns(address); function acceptOwnership() external; function addAMO(address amo_address, bool sync_too) external; function allAMOAddresses() external view returns(address[] memory); function allAMOsLength() external view returns(uint256); function amos(address) external view returns(bool); function amos_array(uint256) external view returns(address); function burnFraxFromAMO(uint256 frax_amount) external; function burnFxsFromAMO(uint256 fxs_amount) external; function col_idx() external view returns(uint256); function collatDollarBalance() external view returns(uint256); function collatDollarBalanceStored() external view returns(uint256); function collat_borrow_cap() external view returns(int256); function collat_borrowed_balances(address) external view returns(int256); function collat_borrowed_sum() external view returns(int256); function collateral_address() external view returns(address); function collateral_token() external view returns(address); function correction_offsets_amos(address, uint256) external view returns(int256); function custodian_address() external view returns(address); function dollarBalances() external view returns(uint256 frax_val_e18, uint256 collat_val_e18); // function execute(address _to, uint256 _value, bytes _data) external returns(bool, bytes); function fraxDollarBalanceStored() external view returns(uint256); function fraxTrackedAMO(address amo_address) external view returns(int256); function fraxTrackedGlobal() external view returns(int256); function frax_mint_balances(address) external view returns(int256); function frax_mint_cap() external view returns(int256); function frax_mint_sum() external view returns(int256); function fxs_mint_balances(address) external view returns(int256); function fxs_mint_cap() external view returns(int256); function fxs_mint_sum() external view returns(int256); function giveCollatToAMO(address destination_amo, uint256 collat_amount) external; function min_cr() external view returns(uint256); function mintFraxForAMO(address destination_amo, uint256 frax_amount) external; function mintFxsForAMO(address destination_amo, uint256 fxs_amount) external; function missing_decimals() external view returns(uint256); function nominateNewOwner(address _owner) external; function nominatedOwner() external view returns(address); function oldPoolCollectAndGive(address destination_amo) external; function oldPoolRedeem(uint256 frax_amount) external; function old_pool() external view returns(address); function owner() external view returns(address); function pool() external view returns(address); function receiveCollatFromAMO(uint256 usdc_amount) external; function recoverERC20(address tokenAddress, uint256 tokenAmount) external; function removeAMO(address amo_address, bool sync_too) external; function setAMOCorrectionOffsets(address amo_address, int256 frax_e18_correction, int256 collat_e18_correction) external; function setCollatBorrowCap(uint256 _collat_borrow_cap) external; function setCustodian(address _custodian_address) external; function setFraxMintCap(uint256 _frax_mint_cap) external; function setFraxPool(address _pool_address) external; function setFxsMintCap(uint256 _fxs_mint_cap) external; function setMinimumCollateralRatio(uint256 _min_cr) external; function setTimelock(address new_timelock) external; function syncDollarBalances() external; function timelock_address() external view returns(address); } // File contracts/Common/Context.sol /* * @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 payable(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/ERC20/IERC20.sol /** * @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/Utils/Address.sol /** * @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/ERC20/ERC20.sol /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory __name, string memory __symbol) public { _name = __name; _symbol = __symbol; _decimals = 18; } /** * @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. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * 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 See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view 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.approve(address spender, uint256 amount) */ 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); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); 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].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 virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); 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 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); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _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 virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @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 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(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); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @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 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 Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal virtual { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } /** * @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 to 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:using-hooks.adoc[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File contracts/Uniswap/Interfaces/IUniswapV2Factory.sol interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // File contracts/Uniswap/Interfaces/IUniswapV2Pair.sol 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; } // File contracts/Math/Babylonian.sol // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { 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; } // else z = 0 } } // File contracts/Math/FixedPoint.sol // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint _x; } uint8 private constant RESOLUTION = 112; uint private constant Q112 = uint(1) << RESOLUTION; uint private constant Q224 = Q112 << RESOLUTION; // encode a uint112 as a UQ112x112 function encode(uint112 x) internal pure returns (uq112x112 memory) { return uq112x112(uint224(x) << RESOLUTION); } // encodes a uint144 as a UQ144x112 function encode144(uint144 x) internal pure returns (uq144x112 memory) { return uq144x112(uint256(x) << RESOLUTION); } // divide a UQ112x112 by a uint112, returning a UQ112x112 function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) { require(x != 0, 'FixedPoint: DIV_BY_ZERO'); return uq112x112(self._x / uint224(x)); } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { uint z; require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW"); return uq144x112(z); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // equivalent to encode(numerator).div(denominator) function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, "FixedPoint: DIV_BY_ZERO"); return uq112x112((uint224(numerator) << RESOLUTION) / denominator); } // decode a UQ112x112 into a uint112 by truncating after the radix point function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } // decode a UQ144x112 into a uint144 by truncating after the radix point function decode144(uq144x112 memory self) internal pure returns (uint144) { return uint144(self._x >> RESOLUTION); } // take the reciprocal of a UQ112x112 function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) { require(self._x != 0, 'FixedPoint: ZERO_RECIPROCAL'); return uq112x112(uint224(Q224 / self._x)); } // square root of a UQ112x112 function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { return uq112x112(uint224(Babylonian.sqrt(uint256(self._x)) << 56)); } } // File contracts/Uniswap/UniswapV2OracleLibrary.sol // library with helper methods for oracles that are concerned with computing average prices library UniswapV2OracleLibrary { using FixedPoint for *; // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] function currentBlockTimestamp() internal view returns (uint32) { return uint32(block.timestamp % 2 ** 32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function currentCumulativePrices( address pair ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) { blockTimestamp = currentBlockTimestamp(); price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast(); price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } } } // File contracts/Uniswap/UniswapV2Library.sol 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'); } // Less efficient than the CREATE2 method below function pairFor(address factory, address tokenA, address tokenB) internal view returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = IUniswapV2Factory(factory).getPair(token0, token1); } // calculates the CREATE2 address for a pair without making any external calls function pairForCreate2(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint160(bytes20(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash ))))); // this matches the CREATE2 in UniswapV2Factory.createPair } // 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; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i = 0; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // File contracts/Staking/Owned.sol // https://docs.synthetix.io/contracts/Owned contract Owned { address public owner; address public nominatedOwner; constructor (address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { require(msg.sender == owner, "Only the contract owner may perform this action"); _; } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } // File contracts/Oracle/UniswapPairOracle.sol // Fixed window oracle that recomputes the average price for the entire period once every period // Note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period contract UniswapPairOracle is Owned { using FixedPoint for *; address timelock_address; uint public PERIOD = 3600; // 1 hour TWAP (time-weighted average price) uint public CONSULT_LENIENCY = 120; // Used for being able to consult past the period end bool public ALLOW_STALE_CONSULTS = false; // If false, consult() will fail if the TWAP is stale IUniswapV2Pair public immutable pair; address public immutable token0; address public immutable token1; uint public price0CumulativeLast; uint public price1CumulativeLast; uint32 public blockTimestampLast; FixedPoint.uq112x112 public price0Average; FixedPoint.uq112x112 public price1Average; modifier onlyByOwnGov() { require(msg.sender == owner || msg.sender == timelock_address, "You are not an owner or the governance timelock"); _; } constructor (address factory, address tokenA, address tokenB, address _owner_address, address _timelock_address) public Owned(_owner_address) { IUniswapV2Pair _pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, tokenA, tokenB)); pair = _pair; token0 = _pair.token0(); token1 = _pair.token1(); price0CumulativeLast = _pair.price0CumulativeLast(); // Fetch the current accumulated price value (1 / 0) price1CumulativeLast = _pair.price1CumulativeLast(); // Fetch the current accumulated price value (0 / 1) uint112 reserve0; uint112 reserve1; (reserve0, reserve1, blockTimestampLast) = _pair.getReserves(); require(reserve0 != 0 && reserve1 != 0, 'UniswapPairOracle: NO_RESERVES'); // Ensure that there's liquidity in the pair timelock_address = _timelock_address; } function setTimelock(address _timelock_address) external onlyByOwnGov { timelock_address = _timelock_address; } function setPeriod(uint _period) external onlyByOwnGov { PERIOD = _period; } function setConsultLeniency(uint _consult_leniency) external onlyByOwnGov { CONSULT_LENIENCY = _consult_leniency; } function setAllowStaleConsults(bool _allow_stale_consults) external onlyByOwnGov { ALLOW_STALE_CONSULTS = _allow_stale_consults; } // Check if update() can be called instead of wasting gas calling it function canUpdate() public view returns (bool) { uint32 blockTimestamp = UniswapV2OracleLibrary.currentBlockTimestamp(); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired return (timeElapsed >= PERIOD); } function update() external { (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(address(pair)); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired // Ensure that at least one full period has passed since the last update require(timeElapsed >= PERIOD, 'UniswapPairOracle: PERIOD_NOT_ELAPSED'); // Overflow is desired, casting never truncates // Cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed price0Average = FixedPoint.uq112x112(uint224((price0Cumulative - price0CumulativeLast) / timeElapsed)); price1Average = FixedPoint.uq112x112(uint224((price1Cumulative - price1CumulativeLast) / timeElapsed)); price0CumulativeLast = price0Cumulative; price1CumulativeLast = price1Cumulative; blockTimestampLast = blockTimestamp; } // Note this will always return 0 before update has been called successfully for the first time. function consult(address token, uint amountIn) external view returns (uint amountOut) { uint32 blockTimestamp = UniswapV2OracleLibrary.currentBlockTimestamp(); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired // Ensure that the price is not stale require((timeElapsed < (PERIOD + CONSULT_LENIENCY)) || ALLOW_STALE_CONSULTS, 'UniswapPairOracle: PRICE_IS_STALE_NEED_TO_CALL_UPDATE'); if (token == token0) { amountOut = price0Average.mul(amountIn).decode144(); } else { require(token == token1, 'UniswapPairOracle: INVALID_TOKEN'); amountOut = price1Average.mul(amountIn).decode144(); } } } // File contracts/Uniswap/TransferHelper.sol // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, 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'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_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/Misc_AMOs/aave/IAAVELendingPool_Partial.sol // Original at https://etherscan.io/address/0xc6845a5c768bf8d7681249f8927877efda425baf#code // Address [0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9] used is a proxy // Some functions were omitted for brevity. See the contract for details interface IAAVELendingPool_Partial is IERC20 { /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external returns (uint256); } // File contracts/Misc_AMOs/aave/IAAVE_aFRAX.sol // Address [0xd4937682df3c8aef4fe912a96a74121c0829e664] used is a proxy // Some functions were omitted for brevity. See the contract for details interface IAAVE_aFRAX is IERC20 { function ATOKEN_REVISION() external view returns (uint256); function DOMAIN_SEPARATOR() external view returns (bytes32); function EIP712_REVISION() external view returns (bytes memory); function PERMIT_TYPEHASH() external view returns (bytes32); function POOL() external view returns (address); function RESERVE_TREASURY_ADDRESS() external view returns (address); function UINT_MAX_VALUE() external view returns (uint256); function UNDERLYING_ASSET_ADDRESS() external view returns (address); function _nonces(address) external view returns (uint256); function burn(address user, address receiverOfUnderlying, uint256 amount, uint256 index) external; function decimals() external view returns (uint8); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256); function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function mint(address user, uint256 amount, uint256 index) external returns (bool); function mintToTreasury(uint256 amount, uint256 index) external; function name() external view returns (string memory); function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; function scaledBalanceOf(address user) external view returns (uint256); function scaledTotalSupply() external view returns (uint256); function symbol() external view returns (string memory); function transferOnLiquidation(address from, address to, uint256 value) external; function transferUnderlyingTo(address target, uint256 amount) external returns (uint256); } // File contracts/ERC20/IERC20_Detailed.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20_Detailed { function _name() external view returns (string memory); function _symbol() external view returns (string memory); function _decimals() external view returns (uint8); /** * @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/Misc_AMOs/aave/IStakedAave.sol interface IStakedAave is IERC20_Detailed { function COOLDOWN_SECONDS() external view returns (uint256); function getTotalRewardsBalance(address staker) external view returns (uint256); function stakersCooldowns(address staker) external view returns (uint256); function stake(address to, uint256 amount) external; function redeem(address to, uint256 amount) external; function cooldown() external; function claimRewards(address to, uint256 amount) external; } // File contracts/Misc_AMOs/aave/IAaveIncentivesControllerPartial.sol interface IAaveIncentivesControllerPartial { /** * @dev Returns the total of rewards of an user, already accrued + not yet accrued * @param user The address of the user * @return The rewards **/ function getRewardsBalance(address[] calldata assets, address user) external view returns (uint256); /** * @dev Claims reward for an user, on all the assets of the lending pool, accumulating the pending rewards * @param amount Amount of rewards to claim * @param to Address that will be receiving the rewards * @return Rewards claimed **/ function claimRewards( address[] calldata assets, uint256 amount, address to ) external returns (uint256); /** * @dev Claims reward for an user on behalf, on all the assets of the lending pool, accumulating the pending rewards. The caller must * be whitelisted via "allowClaimOnBehalf" function by the RewardsAdmin role manager * @param amount Amount of rewards to claim * @param user Address to check and claim rewards * @param to Address that will be receiving the rewards * @return Rewards claimed **/ function claimRewardsOnBehalf( address[] calldata assets, uint256 amount, address user, address to ) external returns (uint256); /** * @dev returns the unclaimed rewards of the user * @param user the address of the user * @return the unclaimed user rewards */ function getUserUnclaimedRewards(address user) external view returns (uint256); /** * @dev for backward compatibility with previous implementation of the Incentives controller */ function REWARD_TOKEN() external view returns (address); } // File contracts/Misc_AMOs/AaveAMO.sol // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ============================= AaveAMO ============================== // ==================================================================== // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Jason Huan: https://github.com/jasonhuan // Travis Moore: https://github.com/FortisFortuna // Reviewer(s) / Contributor(s) // Sam Kazemian: https://github.com/samkazemian contract AaveAMO is Owned { using SafeMath for uint256; // SafeMath automatically included in Solidity >= 8.0.0 /* ========== STATE VARIABLES ========== */ IFrax private FRAX = IFrax(0x853d955aCEf822Db058eb8505911ED77F175b99e); IFxs private FXS = IFxs(0x3432B6A60D23Ca0dFCa7761B7ab56459D9C964D0); IFraxAMOMinter private amo_minter; // Pools and vaults IAAVELendingPool_Partial private aaveFRAX_Pool = IAAVELendingPool_Partial(0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9); IAAVE_aFRAX private aaveFRAX_Token = IAAVE_aFRAX(0xd4937682df3C8aEF4FE912A96A74121C0829E664); // Reward Tokens ERC20 private AAVE = ERC20(0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9); IStakedAave private stkAAVE = IStakedAave(0x4da27a545c0c5B758a6BA100e3a049001de870f5); IAaveIncentivesControllerPartial private AAVEIncentivesController = IAaveIncentivesControllerPartial(0xd784927Ff2f95ba542BfC824c8a8a98F3495f6b5); address public timelock_address; address public custodian_address; uint256 private constant PRICE_PRECISION = 1e6; /* ========== CONSTRUCTOR ========== */ constructor ( address _owner_address, address _amo_minter_address ) Owned(_owner_address) { amo_minter = IFraxAMOMinter(_amo_minter_address); // Get the custodian and timelock addresses from the minter custodian_address = amo_minter.custodian_address(); timelock_address = amo_minter.timelock_address(); } /* ========== MODIFIERS ========== */ modifier onlyByOwnGov() { require(msg.sender == timelock_address || msg.sender == owner, "Not owner or timelock"); _; } modifier onlyByOwnGovCust() { require(msg.sender == timelock_address || msg.sender == owner || msg.sender == custodian_address, "Not owner, tlck, or custd"); _; } modifier onlyByMinter() { require(msg.sender == address(amo_minter), "Not minter"); _; } /* ========== VIEWS ========== */ function showAllocations() public view returns (uint256[3] memory allocations) { // All numbers given are in FRAX unless otherwise stated allocations[0] = FRAX.balanceOf(address(this)); // Unallocated FRAX allocations[1] = aaveFRAX_Token.balanceOf(address(this)); // AAVE uint256 sum_frax = allocations[0] + allocations[1]; allocations[2] = sum_frax; // Total FRAX possessed in various forms } function dollarBalances() public view returns (uint256 frax_val_e18, uint256 collat_val_e18) { frax_val_e18 = showAllocations()[2]; collat_val_e18 = (frax_val_e18).mul(FRAX.global_collateral_ratio()).div(PRICE_PRECISION); } // For potential Aave incentives in the future function showRewards() external view returns (uint256[2] memory rewards) { rewards[0] = stkAAVE.balanceOf(address(this)); // stkAAVE rewards[1] = AAVE.balanceOf(address(this)); // AAVE } // Backwards compatibility function mintedBalance() public view returns (int256) { return amo_minter.frax_mint_balances(address(this)); } /* ========== AAVE V2 + stkAAVE ========== */ function aaveDepositFRAX(uint256 frax_amount) public onlyByOwnGovCust { FRAX.approve(address(aaveFRAX_Pool), frax_amount); aaveFRAX_Pool.deposit(address(FRAX), frax_amount, address(this), 0); } // E18 function aaveWithdrawFRAX(uint256 aFRAX_amount) public onlyByOwnGovCust { aaveFRAX_Pool.withdraw(address(FRAX), aFRAX_amount, address(this)); } // Collect stkAAVE function aaveCollect_stkAAVE(bool withdraw_too) public onlyByOwnGovCust { address[] memory the_assets = new address[](1); the_assets[0] = address(aaveFRAX_Token); uint256 rewards_balance = AAVEIncentivesController.getRewardsBalance(the_assets, address(this)); AAVEIncentivesController.claimRewards(the_assets, rewards_balance, address(this)); if (withdraw_too){ withdrawRewards(); } } /* ========== Burns and givebacks ========== */ // Burn unneeded or excess FRAX. Goes through the minter function burnFRAX(uint256 frax_amount) public onlyByOwnGovCust { FRAX.approve(address(amo_minter), frax_amount); amo_minter.burnFraxFromAMO(frax_amount); } // Burn unneeded FXS. Goes through the minter function burnFXS(uint256 fxs_amount) public onlyByOwnGovCust { FXS.approve(address(amo_minter), fxs_amount); amo_minter.burnFxsFromAMO(fxs_amount); } /* ========== Rewards ========== */ function withdrawRewards() public onlyByOwnGovCust { stkAAVE.transfer(msg.sender, stkAAVE.balanceOf(address(this))); AAVE.transfer(msg.sender, AAVE.balanceOf(address(this))); } /* ========== RESTRICTED GOVERNANCE FUNCTIONS ========== */ function setAMOMinter(address _amo_minter_address) external onlyByOwnGov { amo_minter = IFraxAMOMinter(_amo_minter_address); // Get the custodian and timelock addresses from the minter custodian_address = amo_minter.custodian_address(); timelock_address = amo_minter.timelock_address(); // Make sure the new addresses are not address(0) require(custodian_address != address(0) && timelock_address != address(0), "Invalid custodian or timelock"); } function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov { TransferHelper.safeTransfer(address(tokenAddress), msg.sender, tokenAmount); } // Generic proxy function execute( address _to, uint256 _value, bytes calldata _data ) external onlyByOwnGov returns (bool, bytes memory) { (bool success, bytes memory result) = _to.call{value:_value}(_data); return (success, result); } }
All numbers given are in FRAX unless otherwise stated
function showAllocations() public view returns (uint256[3] memory allocations) { uint256 sum_frax = allocations[0] + allocations[1]; }
2,318,920
./full_match/44787/0xc89d26630Dd47C067715Dac81Cc98a704278aC04/sources/contracts/RimedoNFT.sol
mints a new token after the auction is finished. 75% are offsetted 20% (or 4/5 of the remainders) of the remainders are distributed equally per existing token holders 5% to the artist Existing token holders receive their fair share rounding remainders are added to the offset finally we offset on behalf of the buyer artist is payed and give the minter the token
function mint() external returns (uint256) { require(started, "minting not yet allowed"); require(totalSupply < MAX_SUPPLY, "the maximum number of tokens have been minted"); carbonToken.safeTransferFrom(msg.sender, address(this), price); uint256 _offsetPart = price / 20 * 15; uint256 _remainders = price - _offsetPart; uint256 _distributionPart = _remainders / 5 * 4; uint256 _artistFee = _remainders - _distributionPart; uint256 _distributionPartPerHolder = _distributionPart / totalSupply; tokenDistributions[tokenId] = distributionsPerToken; _offsetPart += _distributionPart; carbonToken.offsetOnBehalfOf(msg.sender, _offsetPart); carbonToken.safeTransfer(artistAddress, _artistFee); uint256 mintedTokenId = _rawMint(msg.sender); return mintedTokenId; }
13,263,923
./partial_match/80001/0x7C682dd6E5d569C2e38EA148032098B839B11c9F/sources/contracts/interfaces/callback/IAlgebraSwapCallback.sol
Callback for IAlgebraPoolActionsswap Any contract that calls IAlgebraPoolActionsswap must implement this interface Credit to Uniswap Labs under GPL-2.0-or-later license: https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraSwapCallback { function algebraSwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata data) external; pragma solidity >=0.5.0; }
8,801,313
./full_match/1/0x151301d8De53c2E7F5D9B10FCe36bd1fCf332bC6/sources/contracts/ethereum/core/CrowdFundHYPCPoolV2.sol
/unassign token and redeem it.
@dev This function is needed to redeem c_HyPC for HyPC after a proposal has been completed. This allows a user with a deposit to reclaim their original deposited HyPC. function redeemTokens( uint256 proposalIndex, uint256 tokensToRedeem ) external nonReentrant validIndex(proposalIndex) { ContractProposal memory proposalData = proposals[proposalIndex]; if (proposalData.status != Term.COMPLETED) { revert ProposalMustBeCompleted(); revert RedeemingTooManyTokens(); } uint256 _i; for (_i = 0; _i < tokensToRedeem; _i++) { uint256 tokenId = proposalData.tokenIds[proposalData.tokenIds.length - _i - 1]; proposals[proposalIndex].tokenIds.pop(); hypcNFT.assign(tokenId, ''); hypcNFT.approve(address(swapContract), tokenId); swapContract.redeem(tokenId); } emit TokensRedeemed(msg.sender, proposalIndex, tokensToRedeem); } backing HyPC. Users who have deposited can then withdraw their deposits with the withdrawDeposit
9,809,131
// SPDX-License-Identifier: MIT pragma solidity ^0.8.6; pragma experimental ABIEncoderV2; import "./ownable.sol"; import "./variables.sol"; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "./events.sol"; import "./interfaces.sol"; import "./helpers.sol"; contract InteropBetaImplementation is Variables // Initializable, // Helpers, // Events { // ListInterface public immutable list; // IndexInterface public immutable instaIndex; // constructor( // address _instaIndex // ) { // instaIndex = IndexInterface(_instaIndex); // list = ListInterface(IndexInterface(_instaIndex).list()); // } // function initialize(address owner_) public initializer { // _owner = owner_; // } // function submitAction( // Position memory position, // address sourceDsaSender, // string memory actionId, // uint64 targetDsaId, // uint256 targetChainId, // bytes memory metadata // ) external { // uint256 sourceChainId = getChainID(); // address dsaAddr = msg.sender; // uint256 sourceDsaId = list.accountID(dsaAddr); // require(sourceDsaId != 0, "msg.sender-not-dsa"); // bytes32 key = keccak256(abi.encode(sourceChainId, targetChainId, vnonce)); // emit LogSubmit( // position, // actionId, // keccak256(abi.encodePacked(actionId)), // sourceDsaSender, // sourceDsaId, // targetDsaId, // sourceChainId, // targetChainId, // vnonce, // metadata // ); // actionDsaAddress[key] = dsaAddr; // vnonce++; // } // function submitSystemAction( // string memory systemActionId, // Position memory position, // bytes memory metadata // ) external { // uint256 sourceChainId = getChainID(); // require(IGnosisSafe(owner()).isOwner(msg.sender), "not-gnosis-safe-owner"); // bytes32 key = keccak256(abi.encode(sourceChainId, vnonce)); // emit LogSubmitSystem( // position, // systemActionId, // keccak256(abi.encodePacked(systemActionId)), // owner(), // msg.sender, // vnonce, // metadata // ); // vnonce++; // } // function submitRevertAction( // Position memory position, // address sourceDsaSender, // string memory actionId, // uint64 sourceDsaId, // uint64 targetDsaId, // uint256 targetChainId, // uint256 _vnonce, // bytes memory metadata // ) external { // uint256 sourceChainId = getChainID(); // address sourceDsaAddr = list.accountAddr(sourceDsaId); // require(sourceDsaAddr != address(0), "dsa-not-valid"); // bytes32 key = keccak256(abi.encode(sourceChainId, targetChainId, _vnonce)); // require(IGnosisSafe(owner()).isOwner(msg.sender), "not-gnosis-safe-owner"); // if (executeMapping[key] == false) executeMapping[key] = false; // emit LogRevert( // position, // actionId, // keccak256(abi.encodePacked(actionId)), // sourceDsaSender, // sourceDsaId, // targetDsaId, // sourceChainId, // targetChainId, // _vnonce, // metadata // ); // } // /** // * @dev cast sourceAction // */ // function sourceAction( // Spell[] memory sourceSpells, // Position memory position, // string memory actionId, // address sourceDsaSender, // uint64 sourceDsaId, // uint64 targetDsaId, // uint256 sourceChainId, // uint256 targetChainId, // uint256 _vnonce, // bytes memory metadata // ) // external // onlyOwner // { // ActionVariables memory s; // s.key = keccak256(abi.encode(sourceChainId, targetChainId, _vnonce)); // require(executeMapping[s.key] == false, "already-executed"); // s.dsa = AccountInterface(list.accountAddr(sourceDsaId)); // require(address(s.dsa) != address(0), "dsa-not-valid"); // sendSourceTokens(position.withdraw, address(s.dsa)); // s.success = cast(s.dsa, sourceSpells); // if (s.success) { // executeMapping[s.key] = true; // emit LogValidate( // sourceSpells, // position, // actionId, // keccak256(abi.encodePacked(actionId)), // sourceDsaSender, // sourceDsaId, // targetDsaId, // sourceChainId, // targetChainId, // _vnonce, // metadata // ); // } else { // revert ErrorSourceFailed({ // vnonce: vnonce, // sourceChainId: sourceChainId, // targetChainId: targetChainId // }); // } // require(s.dsa.isAuth(sourceDsaSender), "source-dsa-sender-not-auth"); // } // function sourceSystemAction( // string memory systemActionId, // Position memory position, // uint256 _vnonce, // bytes memory metadata // ) external onlyOwner { // uint256 sourceChainId = getChainID(); // bytes32 key = keccak256(abi.encode(sourceChainId, _vnonce)); // require(executeMapping[key] == false, "already-executed"); // executeMapping[key] = true; // sendSourceTokens(position.withdraw, address(owner())); // emit LogRebalanceSystem( // position, // systemActionId, // keccak256(abi.encodePacked(systemActionId)), // owner(), // msg.sender, // _vnonce, // metadata // ); // } // /** // * @dev cast sourceActionRevert // */ // function sourceRevertAction( // Spell[] memory sourceSpells, // Spell[] memory sourceRevertSpells, // Position memory position, // string memory actionId, // address sourceDsaSender, // uint64 sourceDsaId, // uint64 targetDsaId, // uint256 sourceChainId, // uint256 targetChainId, // uint256 _vnonce, // bytes memory metadata // ) // external // onlyOwner // { // ActionVariables memory s; // bool revertSpells = sourceRevertSpells.length > 0; // s.key = keccak256(abi.encode(sourceChainId, targetChainId, _vnonce)); // require((revertSpells && executeMapping[s.key] == true) || executeMapping[s.key] == false, "revertSpells || executeMapping[s.key] == false"); // s.dsa = AccountInterface(list.accountAddr(sourceDsaId)); // require(address(s.dsa) != address(0), "invalid-dsa"); // sendSourceTokens(position.supply, address(s.dsa)); // if (revertSpells) { // s.success = cast(s.dsa, sourceRevertSpells); // if (s.success) { // emit LogSourceRevert( // sourceSpells, // sourceRevertSpells, // position, // actionId, // keccak256(abi.encodePacked(actionId)), // sourceDsaSender, // sourceDsaId, // targetDsaId, // sourceChainId, // targetChainId, // _vnonce, // metadata // ); // } else { // revert(); // } // } else { // executeMapping[s.key] = true; // } // require(s.dsa.isAuth(sourceDsaSender), "source-dsa-sender-not-auth"); // } // /** // * @dev cast targetAction // */ // function targetAction( // Spell[] memory sourceSpells, // Spell[] memory targetSpells, // Position memory position, // string memory actionId, // address sourceDsaSender, // uint64 sourceDsaId, // uint64 targetDsaId, // uint256 sourceChainId, // uint256 targetChainId, // uint256 _vnonce, // bytes memory metadata // ) // external // onlyOwner // { // ActionVariables memory t; // t.key = keccak256(abi.encode(sourceChainId, targetChainId, _vnonce)); // require(executeMapping[t.key] == false, "already-executed"); // if (targetDsaId == 0) targetDsaId = uint64(list.accounts()); // t.dsa = AccountInterface(list.accountAddr(targetDsaId)); // require(address(t.dsa) != address(0), "invalid-dsa"); // sendTargetTokens(position.supply, address(t.dsa)); // { // t.success = cast(t.dsa, targetSpells); // if (t.success) { // executeMapping[t.key] = true; // emit LogExecute( // sourceSpells, // targetSpells, // position, // actionId, // keccak256(abi.encodePacked(actionId)), // sourceDsaSender, // sourceDsaId, // targetDsaId, // sourceChainId, // targetChainId, // _vnonce, // metadata // ); // } else { // revert ErrorTargetFailed({ // vnonce: vnonce, // sourceChainId: sourceChainId, // targetChainId: targetChainId // }); // } // } // require(t.dsa.isAuth(sourceDsaSender), "source-dsa-sender-not-auth"); // } // /** // * @dev cast targetRevertAction // */ // function targetRevertAction( // Spell[] memory sourceSpells, // Position memory position, // string memory actionId, // address sourceDsaSender, // uint64 sourceDsaId, // uint64 targetDsaId, // uint256 sourceChainId, // uint256 targetChainId, // uint256 _vnonce, // bytes memory metadata // ) // external // onlyOwner // { // ActionVariables memory t; // t.key = keccak256(abi.encode(sourceChainId, targetChainId, _vnonce)); // require(executeMapping[t.key] == false, "already-executed"); // executeMapping[t.key] = true; // emit LogTargetRevert( // sourceSpells, // position, // actionId, // keccak256(abi.encodePacked(actionId)), // sourceDsaSender, // sourceDsaId, // targetDsaId, // sourceChainId, // targetChainId, // _vnonce, // metadata // ); // } function changeOwner(address nextOwner) public { _owner = nextOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.6; import { Variables } from "./variables.sol"; abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return payable(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; } } abstract contract Ownable is Context, Variables { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { 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 { 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 virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.6; contract Variables { address internal _owner; mapping(bytes32 => bool) public executeMapping; mapping(bytes32 => address) public actionDsaAddress; uint256 public vnonce; } // SPDX-License-Identifier: MIT 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; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.6; pragma abicoder v2; import "./helpers.sol"; contract Events is Helpers { event LogSubmit( Position position, string actionId, bytes32 indexed actionIdHashHash, address sourceDsaSender, uint256 sourceDsaId, uint256 targetDsaId, uint256 sourceChainId, uint256 targetChainId, uint256 indexed vnonce, bytes metadata ); event LogSubmitSystem( Position position, string systemActionId, bytes32 indexed systemActionIdHash, address gnosisSafe, address indexed sender, uint256 indexed vnonceSystem, bytes metadata ); event LogRebalanceSystem( Position position, string systemActionId, bytes32 indexed systemActionIdHash, address gnosisSafe, address indexed sender, uint256 indexed vnonceSystem, bytes metadata ); event LogRevert( Position position, string actionId, bytes32 indexed actionIdHashHash, address sourceDsaSender, uint256 sourceDsaId, uint256 targetDsaId, uint256 sourceChainId, uint256 targetChainId, uint256 indexed vnonce, bytes metadata ); event LogValidate( Spell[] sourceSpells, Position position, string actionId, bytes32 indexed actionIdHash, address sourceDsaSender, uint256 sourceDsaId, uint256 targetDsaId, uint256 sourceChainId, uint256 targetChainId, uint256 indexed vnonce, bytes metadata ); event LogSourceRevert( Spell[] sourceSpells, Spell[] sourceRevertSpells, Position position, string actionId, bytes32 indexed actionIdHash, address sourceDsaSender, uint256 sourceDsaId, uint256 targetDsaId, uint256 sourceChainId, uint256 targetChainId, uint256 indexed vnonce, bytes metadata ); event LogExecute( Spell[] sourceSpells, Spell[] targetSpells, Position position, string actionId, bytes32 indexed actionIdHash, address sourceDsaSender, uint256 sourceDsaId, uint256 targetDsaId, uint256 sourceChainId, uint256 targetChainId, uint256 indexed vnonce, bytes metadata ); event LogTargetRevert( Spell[] sourceSpells, Position position, string actionId, bytes32 indexed actionIdHash, address sourceDsaSender, uint256 sourceDsaId, uint256 targetDsaId, uint256 sourceChainId, uint256 targetChainId, uint256 indexed vnonce, bytes metadata ); error ErrorSourceFailed(uint256 vnonce, uint256 sourceChainId, uint256 targetChainId); error ErrorTargetFailed(uint256 vnonce, uint256 sourceChainId, uint256 targetChainId); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.6; pragma abicoder v2; interface IndexInterface { function list() external view returns (address); } interface ListInterface { struct UserLink { uint64 first; uint64 last; uint64 count; } struct UserList { uint64 prev; uint64 next; } struct AccountLink { address first; address last; uint64 count; } struct AccountList { address prev; address next; } function accounts() external view returns (uint); function accountID(address) external view returns (uint64); function accountAddr(uint64) external view returns (address); function userLink(address) external view returns (UserLink memory); function userList(address, uint64) external view returns (UserList memory); function accountLink(uint64) external view returns (AccountLink memory); function accountList(uint64, address) external view returns (AccountList memory); } interface AccountInterface { function version() external view returns (uint); function cast( string[] calldata _targetNames, bytes[] calldata _datas, address _origin ) external payable returns (bytes32); function isAuth(address) external view returns (bool); } interface IGnosisSafe { function isOwner(address) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.6; pragma abicoder v2; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./ownable.sol"; import "./interfaces.sol"; contract Helpers is Ownable { using SafeERC20 for IERC20; struct ActionVariables { bytes32 key; AccountInterface dsa; string[] connectors; bytes[] callData; bool success; } struct Spell { string connector; bytes data; } struct TokenInfo { address sourceToken; address targetToken; uint256 amount; } struct Position { TokenInfo[] supply; TokenInfo[] withdraw; } address constant internal nativeToken = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /** * @dev Return chain Id */ function getChainID() internal view returns (uint256) { return block.chainid; } function sendSourceTokens(TokenInfo[] memory tokens, address dsa) internal onlyOwner { for (uint256 i = 0; i < tokens.length; i++) { IERC20 token = IERC20(tokens[i].sourceToken); uint256 amount = tokens[i].amount; if (address(token) == nativeToken) { Address.sendValue(payable(dsa), amount); } else { token.safeTransfer(dsa, amount); } } } function sendTargetTokens(TokenInfo[] memory tokens, address dsa) internal onlyOwner { for (uint256 i = 0; i < tokens.length; i++) { IERC20 token = IERC20(tokens[i].targetToken); uint256 amount = tokens[i].amount; if (address(token) == nativeToken) { Address.sendValue(payable(dsa), amount); } else { token.safeTransfer(dsa, amount); } } } function cast(AccountInterface dsa, Spell[] memory spells) internal onlyOwner returns (bool success) { string[] memory connectors = new string[](spells.length); bytes[] memory callData = new bytes[](spells.length); for (uint256 i = 0; i < spells.length; i++) { connectors[i] = spells[i].connector; callData[i] = spells[i].data; } (success, ) = address(dsa).call( abi.encodeWithSignature( "cast(string[],bytes[],address)", connectors, callData, address(this) ) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; 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' 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) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _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 require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT 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); } } } }
Initializable, Helpers, Events ListInterface public immutable list; IndexInterface public immutable instaIndex; constructor( address _instaIndex ) { instaIndex = IndexInterface(_instaIndex); list = ListInterface(IndexInterface(_instaIndex).list()); } function initialize(address owner_) public initializer { _owner = owner_; } function submitAction( Position memory position, address sourceDsaSender, string memory actionId, uint64 targetDsaId, uint256 targetChainId, bytes memory metadata ) external { uint256 sourceChainId = getChainID(); address dsaAddr = msg.sender; uint256 sourceDsaId = list.accountID(dsaAddr); require(sourceDsaId != 0, "msg.sender-not-dsa"); bytes32 key = keccak256(abi.encode(sourceChainId, targetChainId, vnonce)); emit LogSubmit( position, actionId, keccak256(abi.encodePacked(actionId)), sourceDsaSender, sourceDsaId, targetDsaId, sourceChainId, targetChainId, vnonce, metadata ); actionDsaAddress[key] = dsaAddr; vnonce++; } function submitSystemAction( string memory systemActionId, Position memory position, bytes memory metadata ) external { uint256 sourceChainId = getChainID(); require(IGnosisSafe(owner()).isOwner(msg.sender), "not-gnosis-safe-owner"); bytes32 key = keccak256(abi.encode(sourceChainId, vnonce)); emit LogSubmitSystem( position, systemActionId, keccak256(abi.encodePacked(systemActionId)), owner(), msg.sender, vnonce, metadata ); vnonce++; } function submitRevertAction( Position memory position, address sourceDsaSender, string memory actionId, uint64 sourceDsaId, uint64 targetDsaId, uint256 targetChainId, uint256 _vnonce, bytes memory metadata ) external { uint256 sourceChainId = getChainID(); address sourceDsaAddr = list.accountAddr(sourceDsaId); require(sourceDsaAddr != address(0), "dsa-not-valid"); bytes32 key = keccak256(abi.encode(sourceChainId, targetChainId, _vnonce)); require(IGnosisSafe(owner()).isOwner(msg.sender), "not-gnosis-safe-owner"); if (executeMapping[key] == false) executeMapping[key] = false; emit LogRevert( position, actionId, keccak256(abi.encodePacked(actionId)), sourceDsaSender, sourceDsaId, targetDsaId, sourceChainId, targetChainId, _vnonce, metadata ); } / cast sourceAction / function sourceAction( Spell[] memory sourceSpells, Position memory position, string memory actionId, address sourceDsaSender, uint64 sourceDsaId, uint64 targetDsaId, uint256 sourceChainId, uint256 targetChainId, uint256 _vnonce, bytes memory metadata ) external onlyOwner { ActionVariables memory s; s.key = keccak256(abi.encode(sourceChainId, targetChainId, _vnonce)); require(executeMapping[s.key] == false, "already-executed"); s.dsa = AccountInterface(list.accountAddr(sourceDsaId)); require(address(s.dsa) != address(0), "dsa-not-valid"); sendSourceTokens(position.withdraw, address(s.dsa)); s.success = cast(s.dsa, sourceSpells); if (s.success) { executeMapping[s.key] = true; emit LogValidate( sourceSpells, position, actionId, keccak256(abi.encodePacked(actionId)), sourceDsaSender, sourceDsaId, targetDsaId, sourceChainId, targetChainId, _vnonce, metadata ); } else { revert ErrorSourceFailed({ vnonce: vnonce, sourceChainId: sourceChainId, targetChainId: targetChainId }); } require(s.dsa.isAuth(sourceDsaSender), "source-dsa-sender-not-auth"); } function sourceSystemAction( string memory systemActionId, Position memory position, uint256 _vnonce, bytes memory metadata ) external onlyOwner { uint256 sourceChainId = getChainID(); bytes32 key = keccak256(abi.encode(sourceChainId, _vnonce)); require(executeMapping[key] == false, "already-executed"); executeMapping[key] = true; sendSourceTokens(position.withdraw, address(owner())); emit LogRebalanceSystem( position, systemActionId, keccak256(abi.encodePacked(systemActionId)), owner(), msg.sender, _vnonce, metadata ); } / cast sourceActionRevert / function sourceRevertAction( Spell[] memory sourceSpells, Spell[] memory sourceRevertSpells, Position memory position, string memory actionId, address sourceDsaSender, uint64 sourceDsaId, uint64 targetDsaId, uint256 sourceChainId, uint256 targetChainId, uint256 _vnonce, bytes memory metadata ) external onlyOwner { ActionVariables memory s; bool revertSpells = sourceRevertSpells.length > 0; s.key = keccak256(abi.encode(sourceChainId, targetChainId, _vnonce)); require((revertSpells && executeMapping[s.key] == true) || executeMapping[s.key] == false, "revertSpells || executeMapping[s.key] == false"); s.dsa = AccountInterface(list.accountAddr(sourceDsaId)); require(address(s.dsa) != address(0), "invalid-dsa"); sendSourceTokens(position.supply, address(s.dsa)); if (revertSpells) { s.success = cast(s.dsa, sourceRevertSpells); if (s.success) { emit LogSourceRevert( sourceSpells, sourceRevertSpells, position, actionId, keccak256(abi.encodePacked(actionId)), sourceDsaSender, sourceDsaId, targetDsaId, sourceChainId, targetChainId, _vnonce, metadata ); } else { revert(); } } else { executeMapping[s.key] = true; } require(s.dsa.isAuth(sourceDsaSender), "source-dsa-sender-not-auth"); } / cast targetAction / function targetAction( Spell[] memory sourceSpells, Spell[] memory targetSpells, Position memory position, string memory actionId, address sourceDsaSender, uint64 sourceDsaId, uint64 targetDsaId, uint256 sourceChainId, uint256 targetChainId, uint256 _vnonce, bytes memory metadata ) external onlyOwner { ActionVariables memory t; t.key = keccak256(abi.encode(sourceChainId, targetChainId, _vnonce)); require(executeMapping[t.key] == false, "already-executed"); if (targetDsaId == 0) targetDsaId = uint64(list.accounts()); t.dsa = AccountInterface(list.accountAddr(targetDsaId)); require(address(t.dsa) != address(0), "invalid-dsa"); sendTargetTokens(position.supply, address(t.dsa)); { t.success = cast(t.dsa, targetSpells); if (t.success) { executeMapping[t.key] = true; emit LogExecute( sourceSpells, targetSpells, position, actionId, keccak256(abi.encodePacked(actionId)), sourceDsaSender, sourceDsaId, targetDsaId, sourceChainId, targetChainId, _vnonce, metadata ); } else { revert ErrorTargetFailed({ vnonce: vnonce, sourceChainId: sourceChainId, targetChainId: targetChainId }); } } require(t.dsa.isAuth(sourceDsaSender), "source-dsa-sender-not-auth"); } / cast targetRevertAction / function targetRevertAction( Spell[] memory sourceSpells, Position memory position, string memory actionId, address sourceDsaSender, uint64 sourceDsaId, uint64 targetDsaId, uint256 sourceChainId, uint256 targetChainId, uint256 _vnonce, bytes memory metadata ) external onlyOwner { ActionVariables memory t; t.key = keccak256(abi.encode(sourceChainId, targetChainId, _vnonce)); require(executeMapping[t.key] == false, "already-executed"); executeMapping[t.key] = true; emit LogTargetRevert( sourceSpells, position, actionId, keccak256(abi.encodePacked(actionId)), sourceDsaSender, sourceDsaId, targetDsaId, sourceChainId, targetChainId, _vnonce, metadata ); }
{ pragma solidity ^0.8.6; function changeOwner(address nextOwner) public { _owner = nextOwner; } }
11,797,059
// SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {BridgeRouter} from "./BridgeRouter.sol"; import {IWeth} from "../../interfaces/bridge/IWeth.sol"; // ============ External Imports ============ import {TypeCasts} from "@celo-org/optics-sol/contracts/XAppConnectionManager.sol"; contract ETHHelper { // ============ Immutables ============ // wrapped Ether contract IWeth public immutable weth; // bridge router contract BridgeRouter public immutable bridge; // ============ Constructor ============ constructor(address _weth, address _bridge) { weth = IWeth(_weth); bridge = BridgeRouter(_bridge); IWeth(_weth).approve(_bridge, uint256(-1)); } // ============ External Functions ============ /** * @notice Sends ETH over the Optics Bridge. Sends to a full-width Optics * identifer on the other side. * @dev As with all bridges, improper use may result in loss of funds. * @param _domain The domain to send funds to. * @param _to The 32-byte identifier of the recipient */ function sendTo(uint32 _domain, bytes32 _to) public payable { weth.deposit{value: msg.value}(); bridge.send(address(weth), msg.value, _domain, _to); } /** * @notice Sends ETH over the Optics Bridge. Sends to the same address on * the other side. * @dev WARNING: This function should only be used when sending TO an * EVM-like domain. As with all bridges, improper use may result in loss of * funds. * @param _domain The domain to send funds to */ function send(uint32 _domain) external payable { sendTo(_domain, TypeCasts.addressToBytes32(msg.sender)); } /** * @notice Sends ETH over the Optics Bridge. Sends to a specified EVM * address on the other side. * @dev This function should only be used when sending TO an EVM-like * domain. As with all bridges, improper use may result in loss of funds * @param _domain The domain to send funds to. * @param _to The EVM address of the recipient */ function sendToEVMLike(uint32 _domain, address _to) external payable { sendTo(_domain, TypeCasts.addressToBytes32(_to)); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {TokenRegistry} from "./TokenRegistry.sol"; import {Router} from "../Router.sol"; import {XAppConnectionClient} from "../XAppConnectionClient.sol"; import {IBridgeToken} from "../../interfaces/bridge/IBridgeToken.sol"; import {BridgeMessage} from "./BridgeMessage.sol"; // ============ External Imports ============ import {Home} from "@celo-org/optics-sol/contracts/Home.sol"; import {Version0} from "@celo-org/optics-sol/contracts/Version0.sol"; import {TypeCasts} from "@celo-org/optics-sol/contracts/XAppConnectionManager.sol"; import {TypedMemView} from "@summa-tx/memview-sol/contracts/TypedMemView.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /** * @title BridgeRouter */ contract BridgeRouter is Version0, Router, TokenRegistry { // ============ Libraries ============ using TypedMemView for bytes; using TypedMemView for bytes29; using BridgeMessage for bytes29; using SafeERC20 for IERC20; // ============ Constants ============ // 5 bps (0.05%) hardcoded fast liquidity fee. Can be changed by contract upgrade uint256 public constant PRE_FILL_FEE_NUMERATOR = 9995; uint256 public constant PRE_FILL_FEE_DENOMINATOR = 10000; // ============ Public Storage ============ // token transfer prefill ID => LP that pre-filled message to provide fast liquidity mapping(bytes32 => address) public liquidityProvider; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[49] private __GAP; // ======== Events ========= /** * @notice emitted when tokens are sent from this domain to another domain * @param token the address of the token contract * @param from the address sending tokens * @param toDomain the domain of the chain the tokens are being sent to * @param toId the bytes32 address of the recipient of the tokens * @param amount the amount of tokens sent */ event Send( address indexed token, address indexed from, uint32 indexed toDomain, bytes32 toId, uint256 amount ); // ======== Initializer ======== function initialize(address _tokenBeacon, address _xAppConnectionManager) public initializer { __TokenRegistry_initialize(_tokenBeacon); __XAppConnectionClient_initialize(_xAppConnectionManager); } // ======== External: Handle ========= /** * @notice Handles an incoming message * @param _origin The origin domain * @param _sender The sender address * @param _message The message */ function handle( uint32 _origin, bytes32 _sender, bytes memory _message ) external override onlyReplica onlyRemoteRouter(_origin, _sender) { // parse tokenId and action from message bytes29 _msg = _message.ref(0).mustBeMessage(); bytes29 _tokenId = _msg.tokenId(); bytes29 _action = _msg.action(); // handle message based on the intended action if (_action.isTransfer()) { _handleTransfer(_tokenId, _action); } else if (_action.isDetails()) { _handleDetails(_tokenId, _action); } else if (_action.isRequestDetails()) { _handleRequestDetails(_origin, _sender, _tokenId); } else { require(false, "!valid action"); } } // ======== External: Request Token Details ========= /** * @notice Request updated token metadata from another chain * @dev This is only owner to prevent abuse and spam. Requesting details * should be done automatically on token instantiation * @param _domain The domain where that token is native * @param _id The token id on that domain */ function requestDetails(uint32 _domain, bytes32 _id) external onlyOwner { bytes29 _tokenId = BridgeMessage.formatTokenId(_domain, _id); _requestDetails(_tokenId); } // ======== External: Send Token ========= /** * @notice Send tokens to a recipient on a remote chain * @param _token The token address * @param _amount The token amount * @param _destination The destination domain * @param _recipient The recipient address */ function send( address _token, uint256 _amount, uint32 _destination, bytes32 _recipient ) external { require(_amount > 0, "!amnt"); require(_recipient != bytes32(0), "!recip"); // get remote BridgeRouter address; revert if not found bytes32 _remote = _mustHaveRemote(_destination); // remove tokens from circulation on this chain IERC20 _bridgeToken = IERC20(_token); if (_isLocalOrigin(_bridgeToken)) { // if the token originates on this chain, hold the tokens in escrow // in the Router _bridgeToken.safeTransferFrom(msg.sender, address(this), _amount); } else { // if the token originates on a remote chain, burn the // representation tokens on this chain _downcast(_bridgeToken).burn(msg.sender, _amount); } // format Transfer Tokens action bytes29 _action = BridgeMessage.formatTransfer(_recipient, _amount); // send message to remote chain via Optics Home(xAppConnectionManager.home()).dispatch( _destination, _remote, BridgeMessage.formatMessage(_formatTokenId(_token), _action) ); // emit Send event to record token sender emit Send( address(_bridgeToken), msg.sender, _destination, _recipient, _amount ); } // ======== External: Fast Liquidity ========= /** * @notice Allows a liquidity provider to give an * end user fast liquidity by pre-filling an * incoming transfer message. * Transfers tokens from the liquidity provider to the end recipient, minus the LP fee; * Records the liquidity provider, who receives * the full token amount when the transfer message is handled. * @dev fast liquidity can only be provided for ONE token transfer * with the same (recipient, amount) at a time. * in the case that multiple token transfers with the same (recipient, amount) * @param _message The incoming transfer message to pre-fill */ function preFill(bytes calldata _message) external { // parse tokenId and action from message bytes29 _msg = _message.ref(0).mustBeMessage(); bytes29 _tokenId = _msg.tokenId().mustBeTokenId(); bytes29 _action = _msg.action().mustBeTransfer(); // calculate prefill ID bytes32 _id = _preFillId(_tokenId, _action); // require that transfer has not already been pre-filled require(liquidityProvider[_id] == address(0), "!unfilled"); // record liquidity provider liquidityProvider[_id] = msg.sender; // transfer tokens from liquidity provider to token recipient IERC20 _token = _mustHaveToken(_tokenId); _token.safeTransferFrom( msg.sender, _action.evmRecipient(), _applyPreFillFee(_action.amnt()) ); } // ======== External: Custom Tokens ========= /** * @notice Enroll a custom token. This allows projects to work with * governance to specify a custom representation. * @dev This is done by inserting the custom representation into the token * lookup tables. It is permissioned to the owner (governance) and can * potentially break token representations. It must be used with extreme * caution. * After the token is inserted, new mint instructions will be sent to the * custom token. The default representation (and old custom representations) * may still be burnt. Until all users have explicitly called migrate, both * representations will continue to exist. * The custom representation MUST be trusted, and MUST allow the router to * both mint AND burn tokens at will. * @param _id the canonical ID of the Token to enroll, as a byte vector * @param _custom the address of the custom implementation to use. */ function enrollCustom( uint32 _domain, bytes32 _id, address _custom ) external onlyOwner { // Sanity check. Ensures that human error doesn't cause an // unpermissioned contract to be enrolled. IBridgeToken(_custom).mint(address(this), 1); IBridgeToken(_custom).burn(address(this), 1); // update mappings with custom token bytes29 _tokenId = BridgeMessage.formatTokenId(_domain, _id); representationToCanonical[_custom].domain = _tokenId.domain(); representationToCanonical[_custom].id = _tokenId.id(); bytes32 _idHash = _tokenId.keccak(); canonicalToRepresentation[_idHash] = _custom; } /** * @notice Migrate all tokens in a previous representation to the latest * custom representation. This works by looking up local mappings and then * burning old tokens and minting new tokens. * @dev This is explicitly opt-in to allow dapps to decide when and how to * upgrade to the new representation. * @param _oldRepr The address of the old token to migrate */ function migrate(address _oldRepr) external { // get the token ID for the old token contract TokenId memory _id = representationToCanonical[_oldRepr]; require(_id.domain != 0, "!repr"); // ensure that new token & old token are different IBridgeToken _old = IBridgeToken(_oldRepr); IBridgeToken _new = _representationForCanonical(_id); require(_new != _old, "!different"); // burn the old tokens & mint the new ones uint256 _bal = _old.balanceOf(msg.sender); _old.burn(msg.sender, _bal); _new.mint(msg.sender, _bal); } // ============ Internal: Send / UpdateDetails ============ /** * @notice Given a tokenAddress, format the tokenId * identifier for the message. * @param _token The token address * @param _tokenId The bytes-encoded tokenId */ function _formatTokenId(address _token) internal view returns (bytes29 _tokenId) { TokenId memory _tokId = _tokenIdFor(_token); _tokenId = BridgeMessage.formatTokenId(_tokId.domain, _tokId.id); } // ============ Internal: Handle ============ /** * @notice Handles an incoming Transfer message. * * If the token is of local origin, the amount is sent from escrow. * Otherwise, a representation token is minted. * * @param _tokenId The token ID * @param _action The action */ function _handleTransfer(bytes29 _tokenId, bytes29 _action) internal { // get the token contract for the given tokenId on this chain; // (if the token is of remote origin and there is // no existing representation token contract, the TokenRegistry will // deploy a new one) IERC20 _token = _ensureToken(_tokenId); address _recipient = _action.evmRecipient(); // If an LP has prefilled this token transfer, // send the tokens to the LP instead of the recipient bytes32 _id = _preFillId(_tokenId, _action); address _lp = liquidityProvider[_id]; if (_lp != address(0)) { _recipient = _lp; delete liquidityProvider[_id]; } // send the tokens into circulation on this chain if (_isLocalOrigin(_token)) { // if the token is of local origin, the tokens have been held in // escrow in this contract // while they have been circulating on remote chains; // transfer the tokens to the recipient _token.safeTransfer(_recipient, _action.amnt()); } else { // if the token is of remote origin, mint the tokens to the // recipient on this chain _downcast(_token).mint(_recipient, _action.amnt()); } } /** * @notice Handles an incoming Details message. * @param _tokenId The token ID * @param _action The action */ function _handleDetails(bytes29 _tokenId, bytes29 _action) internal { // get the token contract deployed on this chain // revert if no token contract exists IERC20 _token = _mustHaveToken(_tokenId); // require that the token is of remote origin // (otherwise, the BridgeRouter did not deploy the token contract, // and therefore cannot update its metadata) require(!_isLocalOrigin(_token), "!remote origin"); // update the token metadata _downcast(_token).setDetails( TypeCasts.coerceString(_action.name()), TypeCasts.coerceString(_action.symbol()), _action.decimals() ); } /** * @notice Handles an incoming RequestDetails message by sending an * UpdateDetails message to the remote chain * @dev The origin and remote are pre-checked by the handle function * `onlyRemoteRouter` modifier and can be used without additional check * @param _messageOrigin The domain from which the message arrived * @param _messageRemoteRouter The remote router that sent the message * @param _tokenId The token ID */ function _handleRequestDetails( uint32 _messageOrigin, bytes32 _messageRemoteRouter, bytes29 _tokenId ) internal { // get token & ensure is of local origin address _token = _tokenId.evmId(); require(_isLocalOrigin(_token), "!local origin"); IBridgeToken _bridgeToken = IBridgeToken(_token); // format Update Details message bytes29 _updateDetailsAction = BridgeMessage.formatDetails( TypeCasts.coerceBytes32(_bridgeToken.name()), TypeCasts.coerceBytes32(_bridgeToken.symbol()), _bridgeToken.decimals() ); // send message to remote chain via Optics Home(xAppConnectionManager.home()).dispatch( _messageOrigin, _messageRemoteRouter, BridgeMessage.formatMessage(_tokenId, _updateDetailsAction) ); } // ============ Internal: Transfer ============ function _ensureToken(bytes29 _tokenId) internal returns (IERC20) { address _local = _getTokenAddress(_tokenId); if (_local == address(0)) { // Representation does not exist yet; // deploy representation contract _local = _deployToken(_tokenId); // message the origin domain // to request the token details _requestDetails(_tokenId); } return IERC20(_local); } // ============ Internal: Request Details ============ /** * @notice Handles an incoming Details message. * @param _tokenId The token ID */ function _requestDetails(bytes29 _tokenId) internal { uint32 _destination = _tokenId.domain(); // get remote BridgeRouter address; revert if not found bytes32 _remote = remotes[_destination]; if (_remote == bytes32(0)) { return; } // format Request Details message bytes29 _action = BridgeMessage.formatRequestDetails(); // send message to remote chain via Optics Home(xAppConnectionManager.home()).dispatch( _destination, _remote, BridgeMessage.formatMessage(_tokenId, _action) ); } // ============ Internal: Fast Liquidity ============ /** * @notice Calculate the token amount after * taking a 5 bps (0.05%) liquidity provider fee * @param _amnt The token amount before the fee is taken * @return _amtAfterFee The token amount after the fee is taken */ function _applyPreFillFee(uint256 _amnt) internal pure returns (uint256 _amtAfterFee) { // overflow only possible if (2**256 / 9995) tokens sent once // in which case, probably not a real token _amtAfterFee = (_amnt * PRE_FILL_FEE_NUMERATOR) / PRE_FILL_FEE_DENOMINATOR; } /** * @notice get the prefillId used to identify * fast liquidity provision for incoming token send messages * @dev used to identify a token/transfer pair in the prefill LP mapping. * NOTE: This approach has a weakness: a user can receive >1 batch of tokens of * the same size, but only 1 will be eligible for fast liquidity. The * other may only be filled at regular speed. This is because the messages * will have identical `tokenId` and `action` fields. This seems fine, * tbqh. A delay of a few hours on a corner case is acceptable in v1. * @param _tokenId The token ID * @param _action The action */ function _preFillId(bytes29 _tokenId, bytes29 _action) internal view returns (bytes32) { bytes29[] memory _views = new bytes29[](2); _views[0] = _tokenId; _views[1] = _action; return TypedMemView.joinKeccak(_views); } /** * @dev explicit override for compiler inheritance * @dev explicit override for compiler inheritance * @return domain of chain on which the contract is deployed */ function _localDomain() internal view override(TokenRegistry, XAppConnectionClient) returns (uint32) { return XAppConnectionClient._localDomain(); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; interface IWeth { function deposit() external payable; function approve(address _who, uint256 _wad) external; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {Home} from "./Home.sol"; import {Replica} from "./Replica.sol"; import {TypeCasts} from "../libs/TypeCasts.sol"; // ============ External Imports ============ import {ECDSA} from "@openzeppelin/contracts/cryptography/ECDSA.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; /** * @title XAppConnectionManager * @author Celo Labs Inc. * @notice Manages a registry of local Replica contracts * for remote Home domains. Accepts Watcher signatures * to un-enroll Replicas attached to fraudulent remote Homes */ contract XAppConnectionManager is Ownable { // ============ Public Storage ============ // Home contract Home public home; // local Replica address => remote Home domain mapping(address => uint32) public replicaToDomain; // remote Home domain => local Replica address mapping(uint32 => address) public domainToReplica; // watcher address => replica remote domain => has/doesn't have permission mapping(address => mapping(uint32 => bool)) private watcherPermissions; // ============ Events ============ /** * @notice Emitted when a new Replica is enrolled / added * @param domain the remote domain of the Home contract for the Replica * @param replica the address of the Replica */ event ReplicaEnrolled(uint32 indexed domain, address replica); /** * @notice Emitted when a new Replica is un-enrolled / removed * @param domain the remote domain of the Home contract for the Replica * @param replica the address of the Replica */ event ReplicaUnenrolled(uint32 indexed domain, address replica); /** * @notice Emitted when Watcher permissions are changed * @param domain the remote domain of the Home contract for the Replica * @param watcher the address of the Watcher * @param access TRUE if the Watcher was given permissions, FALSE if permissions were removed */ event WatcherPermissionSet( uint32 indexed domain, address watcher, bool access ); // ============ Modifiers ============ modifier onlyReplica() { require(isReplica(msg.sender), "!replica"); _; } // ============ Constructor ============ // solhint-disable-next-line no-empty-blocks constructor() Ownable() {} // ============ External Functions ============ /** * @notice Un-Enroll a replica contract * in the case that fraud was detected on the Home * @dev in the future, if fraud occurs on the Home contract, * the Watcher will submit their signature directly to the Home * and it can be relayed to all remote chains to un-enroll the Replicas * @param _domain the remote domain of the Home contract for the Replica * @param _updater the address of the Updater for the Home contract (also stored on Replica) * @param _signature signature of watcher on (domain, replica address, updater address) */ function unenrollReplica( uint32 _domain, bytes32 _updater, bytes memory _signature ) external { // ensure that the replica is currently set address _replica = domainToReplica[_domain]; require(_replica != address(0), "!replica exists"); // ensure that the signature is on the proper updater require( Replica(_replica).updater() == TypeCasts.bytes32ToAddress(_updater), "!current updater" ); // get the watcher address from the signature // and ensure that the watcher has permission to un-enroll this replica address _watcher = _recoverWatcherFromSig( _domain, TypeCasts.addressToBytes32(_replica), _updater, _signature ); require(watcherPermissions[_watcher][_domain], "!valid watcher"); // remove the replica from mappings _unenrollReplica(_replica); } /** * @notice Set the address of the local Home contract * @param _home the address of the local Home contract */ function setHome(address _home) external onlyOwner { home = Home(_home); } /** * @notice Allow Owner to enroll Replica contract * @param _replica the address of the Replica * @param _domain the remote domain of the Home contract for the Replica */ function ownerEnrollReplica(address _replica, uint32 _domain) external onlyOwner { // un-enroll any existing replica _unenrollReplica(_replica); // add replica and domain to two-way mapping replicaToDomain[_replica] = _domain; domainToReplica[_domain] = _replica; emit ReplicaEnrolled(_domain, _replica); } /** * @notice Allow Owner to un-enroll Replica contract * @param _replica the address of the Replica */ function ownerUnenrollReplica(address _replica) external onlyOwner { _unenrollReplica(_replica); } /** * @notice Allow Owner to set Watcher permissions for a Replica * @param _watcher the address of the Watcher * @param _domain the remote domain of the Home contract for the Replica * @param _access TRUE to give the Watcher permissions, FALSE to remove permissions */ function setWatcherPermission( address _watcher, uint32 _domain, bool _access ) external onlyOwner { watcherPermissions[_watcher][_domain] = _access; emit WatcherPermissionSet(_domain, _watcher, _access); } /** * @notice Query local domain from Home * @return local domain */ function localDomain() external view returns (uint32) { return home.localDomain(); } /** * @notice Get access permissions for the watcher on the domain * @param _watcher the address of the watcher * @param _domain the domain to check for watcher permissions * @return TRUE iff _watcher has permission to un-enroll replicas on _domain */ function watcherPermission(address _watcher, uint32 _domain) external view returns (bool) { return watcherPermissions[_watcher][_domain]; } // ============ Public Functions ============ /** * @notice Check whether _replica is enrolled * @param _replica the replica to check for enrollment * @return TRUE iff _replica is enrolled */ function isReplica(address _replica) public view returns (bool) { return replicaToDomain[_replica] != 0; } // ============ Internal Functions ============ /** * @notice Remove the replica from the two-way mappings * @param _replica replica to un-enroll */ function _unenrollReplica(address _replica) internal { uint32 _currentDomain = replicaToDomain[_replica]; domainToReplica[_currentDomain] = address(0); replicaToDomain[_replica] = 0; emit ReplicaUnenrolled(_currentDomain, _replica); } /** * @notice Get the Watcher address from the provided signature * @return address of watcher that signed */ function _recoverWatcherFromSig( uint32 _domain, bytes32 _replica, bytes32 _updater, bytes memory _signature ) internal view returns (address) { bytes32 _homeDomainHash = Replica(TypeCasts.bytes32ToAddress(_replica)) .homeDomainHash(); bytes32 _digest = keccak256( abi.encodePacked(_homeDomainHash, _domain, _updater) ); _digest = ECDSA.toEthSignedMessageHash(_digest); return ECDSA.recover(_digest, _signature); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {BridgeMessage} from "./BridgeMessage.sol"; import {Encoding} from "./Encoding.sol"; import {IBridgeToken} from "../../interfaces/bridge/IBridgeToken.sol"; import {XAppConnectionClient} from "../XAppConnectionClient.sol"; // ============ External Imports ============ import {TypeCasts} from "@celo-org/optics-sol/contracts/XAppConnectionManager.sol"; import {UpgradeBeaconProxy} from "@celo-org/optics-sol/contracts/upgrade/UpgradeBeaconProxy.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {TypedMemView} from "@summa-tx/memview-sol/contracts/TypedMemView.sol"; import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /** * @title TokenRegistry * @notice manages a registry of token contracts on this chain * - * We sort token types as "representation token" or "locally originating token". * Locally originating - a token contract that was originally deployed on the local chain * Representation (repr) - a token that was originally deployed on some other chain * - * When the router handles an incoming message, it determines whether the * transfer is for an asset of local origin. If not, it checks for an existing * representation contract. If no such representation exists, it deploys a new * representation contract. It then stores the relationship in the * "reprToCanonical" and "canonicalToRepr" mappings to ensure we can always * perform a lookup in either direction * Note that locally originating tokens should NEVER be represented in these lookup tables. */ abstract contract TokenRegistry is Initializable { // ============ Libraries ============ using TypedMemView for bytes; using TypedMemView for bytes29; using BridgeMessage for bytes29; // ============ Structs ============ // Tokens are identified by a TokenId: // domain - 4 byte chain ID of the chain from which the token originates // id - 32 byte identifier of the token address on the origin chain, in that chain's address format struct TokenId { uint32 domain; bytes32 id; } // ============ Public Storage ============ // UpgradeBeacon from which new token proxies will get their implementation address public tokenBeacon; // local representation token address => token ID mapping(address => TokenId) public representationToCanonical; // hash of the tightly-packed TokenId => local representation token address // If the token is of local origin, this MUST map to address(0). mapping(bytes32 => address) public canonicalToRepresentation; // ============ Events ============ event TokenDeployed( uint32 indexed domain, bytes32 indexed id, address indexed representation ); // ======== Initializer ========= /** * @notice Initialize the TokenRegistry with UpgradeBeaconController and * XappConnectionManager. * @dev This method deploys two new contracts, and may be expensive to call. * @param _tokenBeacon The address of the upgrade beacon for bridge token * proxies */ function __TokenRegistry_initialize(address _tokenBeacon) internal initializer { tokenBeacon = _tokenBeacon; } // ======== External: Token Lookup Convenience ========= /** * @notice Looks up the canonical identifier for a local representation. * @dev If no such canonical ID is known, this instead returns (0, bytes32(0)) * @param _local The local address of the representation */ function getCanonicalAddress(address _local) external view returns (uint32 _domain, bytes32 _id) { TokenId memory _canonical = representationToCanonical[_local]; _domain = _canonical.domain; _id = _canonical.id; } /** * @notice Looks up the local address corresponding to a domain/id pair. * @dev If the token is local, it will return the local address. * If the token is non-local and no local representation exists, this * will return `address(0)`. * @param _domain the domain of the canonical version. * @param _id the identifier of the canonical version in its domain. * @return _token the local address of the token contract */ function getLocalAddress(uint32 _domain, address _id) external view returns (address _token) { _token = getLocalAddress(_domain, TypeCasts.addressToBytes32(_id)); } // ======== Public: Token Lookup Convenience ========= /** * @notice Looks up the local address corresponding to a domain/id pair. * @dev If the token is local, it will return the local address. * If the token is non-local and no local representation exists, this * will return `address(0)`. * @param _domain the domain of the canonical version. * @param _id the identifier of the canonical version in its domain. * @return _token the local address of the token contract */ function getLocalAddress(uint32 _domain, bytes32 _id) public view returns (address _token) { _token = _getTokenAddress(BridgeMessage.formatTokenId(_domain, _id)); } // ======== Internal Functions ========= function _localDomain() internal view virtual returns (uint32); /** * @notice Get default name and details for a token * Sets name to "optics.[domain].[id]" * and symbol to * @param _tokenId the tokenId for the token */ function _defaultDetails(bytes29 _tokenId) internal pure returns (string memory _name, string memory _symbol) { // get the first and second half of the token ID (, uint256 _secondHalfId) = Encoding.encodeHex(uint256(_tokenId.id())); // encode the default token name: "[decimal domain].[hex 4 bytes of ID]" _name = string( abi.encodePacked( Encoding.decimalUint32(_tokenId.domain()), // 10 ".", // 1 uint32(_secondHalfId) // 4 ) ); // allocate the memory for a new 32-byte string _symbol = new string(10 + 1 + 4); assembly { mstore(add(_symbol, 0x20), mload(add(_name, 0x20))) } } /** * @notice Deploy and initialize a new token contract * @dev Each token contract is a proxy which * points to the token upgrade beacon * @return _token the address of the token contract */ function _deployToken(bytes29 _tokenId) internal returns (address _token) { // deploy and initialize the token contract _token = address(new UpgradeBeaconProxy(tokenBeacon, "")); // initialize the token separately from the IBridgeToken(_token).initialize(); // set the default token name & symbol string memory _name; string memory _symbol; (_name, _symbol) = _defaultDetails(_tokenId); IBridgeToken(_token).setDetails(_name, _symbol, 18); // store token in mappings representationToCanonical[_token].domain = _tokenId.domain(); representationToCanonical[_token].id = _tokenId.id(); canonicalToRepresentation[_tokenId.keccak()] = _token; // emit event upon deploying new token emit TokenDeployed(_tokenId.domain(), _tokenId.id(), _token); } /** * @notice Get the local token address * for the canonical token represented by tokenID * Returns address(0) if canonical token is of remote origin * and no representation token has been deployed locally * @param _tokenId the token id of the canonical token * @return _local the local token address */ function _getTokenAddress(bytes29 _tokenId) internal view returns (address _local) { if (_tokenId.domain() == _localDomain()) { // Token is of local origin _local = _tokenId.evmId(); } else { // Token is a representation of a token of remote origin _local = canonicalToRepresentation[_tokenId.keccak()]; } } /** * @notice Return the local token contract for the * canonical tokenId; revert if there is no local token * @param _tokenId the token id of the canonical token * @return the IERC20 token contract */ function _mustHaveToken(bytes29 _tokenId) internal view returns (IERC20) { address _local = _getTokenAddress(_tokenId); require(_local != address(0), "!token"); return IERC20(_local); } /** * @notice Return tokenId for a local token address * @param _token local token address (representation or canonical) * @return _id local token address (representation or canonical) */ function _tokenIdFor(address _token) internal view returns (TokenId memory _id) { _id = representationToCanonical[_token]; if (_id.domain == 0) { _id.domain = _localDomain(); _id.id = TypeCasts.addressToBytes32(_token); } } /** * @notice Determine if token is of local origin * @return TRUE if token is locally originating */ function _isLocalOrigin(IERC20 _token) internal view returns (bool) { return _isLocalOrigin(address(_token)); } /** * @notice Determine if token is of local origin * @return TRUE if token is locally originating */ function _isLocalOrigin(address _token) internal view returns (bool) { // If the contract WAS deployed by the TokenRegistry, // it will be stored in this mapping. // If so, it IS NOT of local origin if (representationToCanonical[_token].domain != 0) { return false; } // If the contract WAS NOT deployed by the TokenRegistry, // and the contract exists, then it IS of local origin // Return true if code exists at _addr uint256 _codeSize; // solhint-disable-next-line no-inline-assembly assembly { _codeSize := extcodesize(_token) } return _codeSize != 0; } /** * @notice Get the local representation contract for a canonical token * @dev Returns contract with null address if tokenId has no representation * @param _tokenId the tokenId of the canonical token * @return representation token contract */ function _representationForCanonical(bytes29 _tokenId) internal view returns (IBridgeToken) { return IBridgeToken(canonicalToRepresentation[_tokenId.keccak()]); } /** * @notice Get the local representation contract for a canonical token * @dev Returns contract with null address if tokenId has no representation * @param _tokenId the tokenId of the canonical token * @return representation token contract */ function _representationForCanonical(TokenId memory _tokenId) internal view returns (IBridgeToken) { return _representationForCanonical(_serializeId(_tokenId)); } /** * @notice downcast an IERC20 to an IBridgeToken * @dev Unsafe. Please know what you're doing * @param _token the IERC20 contract * @return the IBridgeToken contract */ function _downcast(IERC20 _token) internal pure returns (IBridgeToken) { return IBridgeToken(address(_token)); } /** * @notice serialize a TokenId struct into a bytes view * @param _id the tokenId * @return serialized bytes of tokenId */ function _serializeId(TokenId memory _id) internal pure returns (bytes29) { return BridgeMessage.formatTokenId(_id.domain, _id.id); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {XAppConnectionClient} from "./XAppConnectionClient.sol"; // ============ External Imports ============ import {IMessageRecipient} from "@celo-org/optics-sol/interfaces/IMessageRecipient.sol"; abstract contract Router is XAppConnectionClient, IMessageRecipient { // ============ Mutable Storage ============ mapping(uint32 => bytes32) public remotes; uint256[49] private __GAP; // gap for upgrade safety // ============ Modifiers ============ /** * @notice Only accept messages from a remote Router contract * @param _origin The domain the message is coming from * @param _router The address the message is coming from */ modifier onlyRemoteRouter(uint32 _origin, bytes32 _router) { require(_isRemoteRouter(_origin, _router), "!remote router"); _; } // ============ External functions ============ /** * @notice Register the address of a Router contract for the same xApp on a remote chain * @param _domain The domain of the remote xApp Router * @param _router The address of the remote xApp Router */ function enrollRemoteRouter(uint32 _domain, bytes32 _router) external onlyOwner { remotes[_domain] = _router; } // ============ Virtual functions ============ function handle( uint32 _origin, bytes32 _sender, bytes memory _message ) external virtual override; // ============ Internal functions ============ /** * @notice Return true if the given domain / router is the address of a remote xApp Router * @param _domain The domain of the potential remote xApp Router * @param _router The address of the potential remote xApp Router */ function _isRemoteRouter(uint32 _domain, bytes32 _router) internal view returns (bool) { return remotes[_domain] == _router; } /** * @notice Assert that the given domain has a xApp Router registered and return its address * @param _domain The domain of the chain for which to get the xApp Router * @return _remote The address of the remote xApp Router on _domain */ function _mustHaveRemote(uint32 _domain) internal view returns (bytes32 _remote) { _remote = remotes[_domain]; require(_remote != bytes32(0), "!remote"); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ External Imports ============ import {Home} from "@celo-org/optics-sol/contracts/Home.sol"; import {XAppConnectionManager} from "@celo-org/optics-sol/contracts/XAppConnectionManager.sol"; import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; abstract contract XAppConnectionClient is OwnableUpgradeable { // ============ Mutable Storage ============ XAppConnectionManager public xAppConnectionManager; uint256[49] private __GAP; // gap for upgrade safety // ============ Modifiers ============ /** * @notice Only accept messages from an Optics Replica contract */ modifier onlyReplica() { require(_isReplica(msg.sender), "!replica"); _; } // ======== Initializer ========= function __XAppConnectionClient_initialize(address _xAppConnectionManager) internal initializer { xAppConnectionManager = XAppConnectionManager(_xAppConnectionManager); __Ownable_init(); } // ============ External functions ============ /** * @notice Modify the contract the xApp uses to validate Replica contracts * @param _xAppConnectionManager The address of the xAppConnectionManager contract */ function setXAppConnectionManager(address _xAppConnectionManager) external onlyOwner { xAppConnectionManager = XAppConnectionManager(_xAppConnectionManager); } // ============ Internal functions ============ /** * @notice Get the local Home contract from the xAppConnectionManager * @return The local Home contract */ function _home() internal view returns (Home) { return xAppConnectionManager.home(); } /** * @notice Determine whether _potentialReplcia is an enrolled Replica from the xAppConnectionManager * @return True if _potentialReplica is an enrolled Replica */ function _isReplica(address _potentialReplica) internal view returns (bool) { return xAppConnectionManager.isReplica(_potentialReplica); } /** * @notice Get the local domain from the xAppConnectionManager * @return The local domain */ function _localDomain() internal view virtual returns (uint32) { return xAppConnectionManager.localDomain(); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; interface IBridgeToken { function initialize() external; function name() external returns (string memory); function balanceOf(address _account) external view returns (uint256); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function burn(address _from, uint256 _amnt) external; function mint(address _to, uint256 _amnt) external; function setDetails( string calldata _name, string calldata _symbol, uint8 _decimals ) external; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ External Imports ============ import {TypedMemView} from "@summa-tx/memview-sol/contracts/TypedMemView.sol"; library BridgeMessage { // ============ Libraries ============ using TypedMemView for bytes; using TypedMemView for bytes29; // ============ Enums ============ // WARNING: do NOT re-write the numbers / order // of message types in an upgrade; // will cause in-flight messages to be mis-interpreted enum Types { Invalid, // 0 TokenId, // 1 Message, // 2 Transfer, // 3 Details, // 4 RequestDetails // 5 } // ============ Constants ============ uint256 private constant TOKEN_ID_LEN = 36; // 4 bytes domain + 32 bytes id uint256 private constant IDENTIFIER_LEN = 1; uint256 private constant TRANSFER_LEN = 65; // 1 byte identifier + 32 bytes recipient + 32 bytes amount uint256 private constant DETAILS_LEN = 66; // 1 byte identifier + 32 bytes name + 32 bytes symbol + 1 byte decimals uint256 private constant REQUEST_DETAILS_LEN = 1; // 1 byte identifier // ============ Modifiers ============ /** * @notice Asserts a message is of type `_t` * @param _view The message * @param _t The expected type */ modifier typeAssert(bytes29 _view, Types _t) { _view.assertType(uint40(_t)); _; } // ============ Internal Functions ============ /** * @notice Checks that Action is valid type * @param _action The action * @return TRUE if action is valid */ function isValidAction(bytes29 _action) internal pure returns (bool) { return isDetails(_action) || isRequestDetails(_action) || isTransfer(_action); } /** * @notice Checks that view is a valid message length * @param _view The bytes string * @return TRUE if message is valid */ function isValidMessageLength(bytes29 _view) internal pure returns (bool) { uint256 _len = _view.len(); return _len == TOKEN_ID_LEN + TRANSFER_LEN || _len == TOKEN_ID_LEN + DETAILS_LEN || _len == TOKEN_ID_LEN + REQUEST_DETAILS_LEN; } /** * @notice Formats an action message * @param _tokenId The token ID * @param _action The action * @return The formatted message */ function formatMessage(bytes29 _tokenId, bytes29 _action) internal view typeAssert(_tokenId, Types.TokenId) returns (bytes memory) { require(isValidAction(_action), "!action"); bytes29[] memory _views = new bytes29[](2); _views[0] = _tokenId; _views[1] = _action; return TypedMemView.join(_views); } /** * @notice Returns the type of the message * @param _view The message * @return The type of the message */ function messageType(bytes29 _view) internal pure returns (Types) { return Types(uint8(_view.typeOf())); } /** * @notice Checks that the message is of type Transfer * @param _action The message * @return True if the message is of type Transfer */ function isTransfer(bytes29 _action) internal pure returns (bool) { return actionType(_action) == uint8(Types.Transfer) && messageType(_action) == Types.Transfer; } /** * @notice Checks that the message is of type Details * @param _action The message * @return True if the message is of type Details */ function isDetails(bytes29 _action) internal pure returns (bool) { return actionType(_action) == uint8(Types.Details) && messageType(_action) == Types.Details; } /** * @notice Checks that the message is of type Details * @param _action The message * @return True if the message is of type Details */ function isRequestDetails(bytes29 _action) internal pure returns (bool) { return actionType(_action) == uint8(Types.RequestDetails) && messageType(_action) == Types.RequestDetails; } /** * @notice Formats Transfer * @param _to The recipient address as bytes32 * @param _amnt The transfer amount * @return */ function formatTransfer(bytes32 _to, uint256 _amnt) internal pure returns (bytes29) { return mustBeTransfer(abi.encodePacked(Types.Transfer, _to, _amnt).ref(0)); } /** * @notice Formats Details * @param _name The name * @param _symbol The symbol * @param _decimals The decimals * @return The Details message */ function formatDetails( bytes32 _name, bytes32 _symbol, uint8 _decimals ) internal pure returns (bytes29) { return mustBeDetails( abi.encodePacked(Types.Details, _name, _symbol, _decimals).ref( 0 ) ); } /** * @notice Formats Request Details * @return The Request Details message */ function formatRequestDetails() internal pure returns (bytes29) { return mustBeRequestDetails(abi.encodePacked(Types.RequestDetails).ref(0)); } /** * @notice Formats the Token ID * @param _domain The domain * @param _id The ID * @return The formatted Token ID */ function formatTokenId(uint32 _domain, bytes32 _id) internal pure returns (bytes29) { return mustBeTokenId(abi.encodePacked(_domain, _id).ref(0)); } /** * @notice Retrieves the domain from a TokenID * @param _tokenId The message * @return The domain */ function domain(bytes29 _tokenId) internal pure typeAssert(_tokenId, Types.TokenId) returns (uint32) { return uint32(_tokenId.indexUint(0, 4)); } /** * @notice Retrieves the ID from a TokenID * @param _tokenId The message * @return The ID */ function id(bytes29 _tokenId) internal pure typeAssert(_tokenId, Types.TokenId) returns (bytes32) { // before = 4 bytes domain return _tokenId.index(4, 32); } /** * @notice Retrieves the EVM ID * @param _tokenId The message * @return The EVM ID */ function evmId(bytes29 _tokenId) internal pure typeAssert(_tokenId, Types.TokenId) returns (address) { // before = 4 bytes domain + 12 bytes empty to trim for address return _tokenId.indexAddress(16); } /** * @notice Retrieves the action identifier from message * @param _message The action * @return The message type */ function msgType(bytes29 _message) internal pure returns (uint8) { return uint8(_message.indexUint(TOKEN_ID_LEN, 1)); } /** * @notice Retrieves the identifier from action * @param _action The action * @return The action type */ function actionType(bytes29 _action) internal pure returns (uint8) { return uint8(_action.indexUint(0, 1)); } /** * @notice Retrieves the recipient from a Transfer * @param _transferAction The message * @return The recipient address as bytes32 */ function recipient(bytes29 _transferAction) internal pure typeAssert(_transferAction, Types.Transfer) returns (bytes32) { // before = 1 byte identifier return _transferAction.index(1, 32); } /** * @notice Retrieves the EVM Recipient from a Transfer * @param _transferAction The message * @return The EVM Recipient */ function evmRecipient(bytes29 _transferAction) internal pure typeAssert(_transferAction, Types.Transfer) returns (address) { // before = 1 byte identifier + 12 bytes empty to trim for address return _transferAction.indexAddress(13); } /** * @notice Retrieves the amount from a Transfer * @param _transferAction The message * @return The amount */ function amnt(bytes29 _transferAction) internal pure typeAssert(_transferAction, Types.Transfer) returns (uint256) { // before = 1 byte identifier + 32 bytes ID return _transferAction.indexUint(33, 32); } /** * @notice Retrieves the name from Details * @param _detailsAction The message * @return The name */ function name(bytes29 _detailsAction) internal pure typeAssert(_detailsAction, Types.Details) returns (bytes32) { // before = 1 byte identifier return _detailsAction.index(1, 32); } /** * @notice Retrieves the symbol from Details * @param _detailsAction The message * @return The symbol */ function symbol(bytes29 _detailsAction) internal pure typeAssert(_detailsAction, Types.Details) returns (bytes32) { // before = 1 byte identifier + 32 bytes name return _detailsAction.index(33, 32); } /** * @notice Retrieves the decimals from Details * @param _detailsAction The message * @return The decimals */ function decimals(bytes29 _detailsAction) internal pure typeAssert(_detailsAction, Types.Details) returns (uint8) { // before = 1 byte identifier + 32 bytes name + 32 bytes symbol return uint8(_detailsAction.indexUint(65, 1)); } /** * @notice Retrieves the token ID from a Message * @param _message The message * @return The ID */ function tokenId(bytes29 _message) internal pure typeAssert(_message, Types.Message) returns (bytes29) { return _message.slice(0, TOKEN_ID_LEN, uint40(Types.TokenId)); } /** * @notice Retrieves the action data from a Message * @param _message The message * @return The action */ function action(bytes29 _message) internal pure typeAssert(_message, Types.Message) returns (bytes29) { uint256 _actionLen = _message.len() - TOKEN_ID_LEN; uint40 _type = uint40(msgType(_message)); return _message.slice(TOKEN_ID_LEN, _actionLen, _type); } /** * @notice Converts to a Transfer * @param _action The message * @return The newly typed message */ function tryAsTransfer(bytes29 _action) internal pure returns (bytes29) { if (_action.len() == TRANSFER_LEN) { return _action.castTo(uint40(Types.Transfer)); } return TypedMemView.nullView(); } /** * @notice Converts to a Details * @param _action The message * @return The newly typed message */ function tryAsDetails(bytes29 _action) internal pure returns (bytes29) { if (_action.len() == DETAILS_LEN) { return _action.castTo(uint40(Types.Details)); } return TypedMemView.nullView(); } /** * @notice Converts to a Details * @param _action The message * @return The newly typed message */ function tryAsRequestDetails(bytes29 _action) internal pure returns (bytes29) { if (_action.len() == REQUEST_DETAILS_LEN) { return _action.castTo(uint40(Types.RequestDetails)); } return TypedMemView.nullView(); } /** * @notice Converts to a TokenID * @param _tokenId The message * @return The newly typed message */ function tryAsTokenId(bytes29 _tokenId) internal pure returns (bytes29) { if (_tokenId.len() == TOKEN_ID_LEN) { return _tokenId.castTo(uint40(Types.TokenId)); } return TypedMemView.nullView(); } /** * @notice Converts to a Message * @param _message The message * @return The newly typed message */ function tryAsMessage(bytes29 _message) internal pure returns (bytes29) { if (isValidMessageLength(_message)) { return _message.castTo(uint40(Types.Message)); } return TypedMemView.nullView(); } /** * @notice Asserts that the message is of type Transfer * @param _view The message * @return The message */ function mustBeTransfer(bytes29 _view) internal pure returns (bytes29) { return tryAsTransfer(_view).assertValid(); } /** * @notice Asserts that the message is of type Details * @param _view The message * @return The message */ function mustBeDetails(bytes29 _view) internal pure returns (bytes29) { return tryAsDetails(_view).assertValid(); } /** * @notice Asserts that the message is of type Details * @param _view The message * @return The message */ function mustBeRequestDetails(bytes29 _view) internal pure returns (bytes29) { return tryAsRequestDetails(_view).assertValid(); } /** * @notice Asserts that the message is of type TokenID * @param _view The message * @return The message */ function mustBeTokenId(bytes29 _view) internal pure returns (bytes29) { return tryAsTokenId(_view).assertValid(); } /** * @notice Asserts that the message is of type Message * @param _view The message * @return The message */ function mustBeMessage(bytes29 _view) internal pure returns (bytes29) { return tryAsMessage(_view).assertValid(); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {Version0} from "./Version0.sol"; import {Common} from "./Common.sol"; import {QueueLib} from "../libs/Queue.sol"; import {MerkleLib} from "../libs/Merkle.sol"; import {Message} from "../libs/Message.sol"; import {MerkleTreeManager} from "./Merkle.sol"; import {QueueManager} from "./Queue.sol"; import {IUpdaterManager} from "../interfaces/IUpdaterManager.sol"; // ============ External Imports ============ import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; /** * @title Home * @author Celo Labs Inc. * @notice Accepts messages to be dispatched to remote chains, * constructs a Merkle tree of the messages, * and accepts signatures from a bonded Updater * which notarize the Merkle tree roots. * Accepts submissions of fraudulent signatures * by the Updater and slashes the Updater in this case. */ contract Home is Version0, QueueManager, MerkleTreeManager, Common, OwnableUpgradeable { // ============ Libraries ============ using QueueLib for QueueLib.Queue; using MerkleLib for MerkleLib.Tree; // ============ Constants ============ // Maximum bytes per message = 2 KiB // (somewhat arbitrarily set to begin) uint256 public constant MAX_MESSAGE_BODY_BYTES = 2 * 2**10; // ============ Public Storage Variables ============ // domain => next available nonce for the domain mapping(uint32 => uint32) public nonces; // contract responsible for Updater bonding, slashing and rotation IUpdaterManager public updaterManager; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[48] private __GAP; // ============ Events ============ /** * @notice Emitted when a new message is dispatched via Optics * @param leafIndex Index of message's leaf in merkle tree * @param destinationAndNonce Destination and destination-specific * nonce combined in single field ((destination << 32) & nonce) * @param messageHash Hash of message; the leaf inserted to the Merkle tree for the message * @param committedRoot the latest notarized root submitted in the last signed Update * @param message Raw bytes of message */ event Dispatch( bytes32 indexed messageHash, uint256 indexed leafIndex, uint64 indexed destinationAndNonce, bytes32 committedRoot, bytes message ); /** * @notice Emitted when proof of an improper update is submitted, * which sets the contract to FAILED state * @param oldRoot Old root of the improper update * @param newRoot New root of the improper update * @param signature Signature on `oldRoot` and `newRoot */ event ImproperUpdate(bytes32 oldRoot, bytes32 newRoot, bytes signature); /** * @notice Emitted when the Updater is slashed * (should be paired with ImproperUpdater or DoubleUpdate event) * @param updater The address of the updater * @param reporter The address of the entity that reported the updater misbehavior */ event UpdaterSlashed(address indexed updater, address indexed reporter); /** * @notice Emitted when Updater is rotated by the UpdaterManager * @param updater The address of the new updater */ event NewUpdater(address updater); /** * @notice Emitted when the UpdaterManager contract is changed * @param updaterManager The address of the new updaterManager */ event NewUpdaterManager(address updaterManager); // ============ Constructor ============ constructor(uint32 _localDomain) Common(_localDomain) {} // solhint-disable-line no-empty-blocks // ============ Initializer ============ function initialize(IUpdaterManager _updaterManager) public initializer { // initialize owner & queue __Ownable_init(); __QueueManager_initialize(); // set Updater Manager contract and initialize Updater _setUpdaterManager(_updaterManager); address _updater = updaterManager.updater(); __Common_initialize(_updater); emit NewUpdater(_updater); } // ============ Modifiers ============ /** * @notice Ensures that function is called by the UpdaterManager contract */ modifier onlyUpdaterManager() { require(msg.sender == address(updaterManager), "!updaterManager"); _; } // ============ External: Updater & UpdaterManager Configuration ============ /** * @notice Set a new Updater * @param _updater the new Updater */ function setUpdater(address _updater) external onlyUpdaterManager { _setUpdater(_updater); } /** * @notice Set a new UpdaterManager contract * @dev Home(s) will initially be initialized using a trusted UpdaterManager contract; * we will progressively decentralize by swapping the trusted contract with a new implementation * that implements Updater bonding & slashing, and rules for Updater selection & rotation * @param _updaterManager the new UpdaterManager contract */ function setUpdaterManager(address _updaterManager) external onlyOwner { _setUpdaterManager(IUpdaterManager(_updaterManager)); } // ============ External Functions ============ /** * @notice Dispatch the message it to the destination domain & recipient * @dev Format the message, insert its hash into Merkle tree, * enqueue the new Merkle root, and emit `Dispatch` event with message information. * @param _destinationDomain Domain of destination chain * @param _recipientAddress Address of recipient on destination chain as bytes32 * @param _messageBody Raw bytes content of message */ function dispatch( uint32 _destinationDomain, bytes32 _recipientAddress, bytes memory _messageBody ) external notFailed { require(_messageBody.length <= MAX_MESSAGE_BODY_BYTES, "msg too long"); // get the next nonce for the destination domain, then increment it uint32 _nonce = nonces[_destinationDomain]; nonces[_destinationDomain] = _nonce + 1; // format the message into packed bytes bytes memory _message = Message.formatMessage( localDomain, bytes32(uint256(uint160(msg.sender))), _nonce, _destinationDomain, _recipientAddress, _messageBody ); // insert the hashed message into the Merkle tree bytes32 _messageHash = keccak256(_message); tree.insert(_messageHash); // enqueue the new Merkle root after inserting the message queue.enqueue(root()); // Emit Dispatch event with message information // note: leafIndex is count() - 1 since new leaf has already been inserted emit Dispatch( _messageHash, count() - 1, _destinationAndNonce(_destinationDomain, _nonce), committedRoot, _message ); } /** * @notice Submit a signature from the Updater "notarizing" a root, * which updates the Home contract's `committedRoot`, * and publishes the signature which will be relayed to Replica contracts * @dev emits Update event * @dev If _newRoot is not contained in the queue, * the Update is a fraudulent Improper Update, so * the Updater is slashed & Home is set to FAILED state * @param _committedRoot Current updated merkle root which the update is building off of * @param _newRoot New merkle root to update the contract state to * @param _signature Updater signature on `_committedRoot` and `_newRoot` */ function update( bytes32 _committedRoot, bytes32 _newRoot, bytes memory _signature ) external notFailed { // check that the update is not fraudulent; // if fraud is detected, Updater is slashed & Home is set to FAILED state if (improperUpdate(_committedRoot, _newRoot, _signature)) return; // clear all of the intermediate roots contained in this update from the queue while (true) { bytes32 _next = queue.dequeue(); if (_next == _newRoot) break; } // update the Home state with the latest signed root & emit event committedRoot = _newRoot; emit Update(localDomain, _committedRoot, _newRoot, _signature); } /** * @notice Suggest an update for the Updater to sign and submit. * @dev If queue is empty, null bytes returned for both * (No update is necessary because no messages have been dispatched since the last update) * @return _committedRoot Latest root signed by the Updater * @return _new Latest enqueued Merkle root */ function suggestUpdate() external view returns (bytes32 _committedRoot, bytes32 _new) { if (queue.length() != 0) { _committedRoot = committedRoot; _new = queue.lastItem(); } } // ============ Public Functions ============ /** * @notice Hash of Home domain concatenated with "OPTICS" */ function homeDomainHash() public view override returns (bytes32) { return _homeDomainHash(localDomain); } /** * @notice Check if an Update is an Improper Update; * if so, slash the Updater and set the contract to FAILED state. * * An Improper Update is an update building off of the Home's `committedRoot` * for which the `_newRoot` does not currently exist in the Home's queue. * This would mean that message(s) that were not truly * dispatched on Home were falsely included in the signed root. * * An Improper Update will only be accepted as valid by the Replica * If an Improper Update is attempted on Home, * the Updater will be slashed immediately. * If an Improper Update is submitted to the Replica, * it should be relayed to the Home contract using this function * in order to slash the Updater with an Improper Update. * * An Improper Update submitted to the Replica is only valid * while the `_oldRoot` is still equal to the `committedRoot` on Home; * if the `committedRoot` on Home has already been updated with a valid Update, * then the Updater should be slashed with a Double Update. * @dev Reverts (and doesn't slash updater) if signature is invalid or * update not current * @param _oldRoot Old merkle tree root (should equal home's committedRoot) * @param _newRoot New merkle tree root * @param _signature Updater signature on `_oldRoot` and `_newRoot` * @return TRUE if update was an Improper Update (implying Updater was slashed) */ function improperUpdate( bytes32 _oldRoot, bytes32 _newRoot, bytes memory _signature ) public notFailed returns (bool) { require( _isUpdaterSignature(_oldRoot, _newRoot, _signature), "!updater sig" ); require(_oldRoot == committedRoot, "not a current update"); // if the _newRoot is not currently contained in the queue, // slash the Updater and set the contract to FAILED state if (!queue.contains(_newRoot)) { _fail(); emit ImproperUpdate(_oldRoot, _newRoot, _signature); return true; } // if the _newRoot is contained in the queue, // this is not an improper update return false; } // ============ Internal Functions ============ /** * @notice Set the UpdaterManager * @param _updaterManager Address of the UpdaterManager */ function _setUpdaterManager(IUpdaterManager _updaterManager) internal { require( Address.isContract(address(_updaterManager)), "!contract updaterManager" ); updaterManager = IUpdaterManager(_updaterManager); emit NewUpdaterManager(address(_updaterManager)); } /** * @notice Set the Updater * @param _updater Address of the Updater */ function _setUpdater(address _updater) internal { updater = _updater; emit NewUpdater(_updater); } /** * @notice Slash the Updater and set contract state to FAILED * @dev Called when fraud is proven (Improper Update or Double Update) */ function _fail() internal override { // set contract to FAILED _setFailed(); // slash Updater updaterManager.slashUpdater(msg.sender); emit UpdaterSlashed(updater, msg.sender); } /** * @notice Internal utility function that combines * `_destination` and `_nonce`. * @dev Both destination and nonce should be less than 2^32 - 1 * @param _destination Domain of destination chain * @param _nonce Current nonce for given destination chain * @return Returns (`_destination` << 32) & `_nonce` */ function _destinationAndNonce(uint32 _destination, uint32 _nonce) internal pure returns (uint64) { return (uint64(_destination) << 32) | _nonce; } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; /** * @title Version0 * @notice Version getter for contracts **/ contract Version0 { uint8 public constant VERSION = 0; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.5.10; import {SafeMath} from "./SafeMath.sol"; library TypedMemView { using SafeMath for uint256; // Why does this exist? // the solidity `bytes memory` type has a few weaknesses. // 1. You can't index ranges effectively // 2. You can't slice without copying // 3. The underlying data may represent any type // 4. Solidity never deallocates memory, and memory costs grow // superlinearly // By using a memory view instead of a `bytes memory` we get the following // advantages: // 1. Slices are done on the stack, by manipulating the pointer // 2. We can index arbitrary ranges and quickly convert them to stack types // 3. We can insert type info into the pointer, and typecheck at runtime // This makes `TypedMemView` a useful tool for efficient zero-copy // algorithms. // Why bytes29? // We want to avoid confusion between views, digests, and other common // types so we chose a large and uncommonly used odd number of bytes // // Note that while bytes are left-aligned in a word, integers and addresses // are right-aligned. This means when working in assembly we have to // account for the 3 unused bytes on the righthand side // // First 5 bytes are a type flag. // - ff_ffff_fffe is reserved for unknown type. // - ff_ffff_ffff is reserved for invalid types/errors. // next 12 are memory address // next 12 are len // bottom 3 bytes are empty // Assumptions: // - non-modification of memory. // - No Solidity updates // - - wrt free mem point // - - wrt bytes representation in memory // - - wrt memory addressing in general // Usage: // - create type constants // - use `assertType` for runtime type assertions // - - unfortunately we can't do this at compile time yet :( // - recommended: implement modifiers that perform type checking // - - e.g. // - - `uint40 constant MY_TYPE = 3;` // - - ` modifer onlyMyType(bytes29 myView) { myView.assertType(MY_TYPE); }` // - instantiate a typed view from a bytearray using `ref` // - use `index` to inspect the contents of the view // - use `slice` to create smaller views into the same memory // - - `slice` can increase the offset // - - `slice can decrease the length` // - - must specify the output type of `slice` // - - `slice` will return a null view if you try to overrun // - - make sure to explicitly check for this with `notNull` or `assertType` // - use `equal` for typed comparisons. // The null view bytes29 public constant NULL = hex"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; uint256 constant LOW_12_MASK = 0xffffffffffffffffffffffff; uint8 constant TWELVE_BYTES = 96; /** * @notice Returns the encoded hex character that represents the lower 4 bits of the argument. * @param _b The byte * @return char - The encoded hex character */ function nibbleHex(uint8 _b) internal pure returns (uint8 char) { // This can probably be done more efficiently, but it's only in error // paths, so we don't really care :) uint8 _nibble = _b | 0xf0; // set top 4, keep bottom 4 if (_nibble == 0xf0) {return 0x30;} // 0 if (_nibble == 0xf1) {return 0x31;} // 1 if (_nibble == 0xf2) {return 0x32;} // 2 if (_nibble == 0xf3) {return 0x33;} // 3 if (_nibble == 0xf4) {return 0x34;} // 4 if (_nibble == 0xf5) {return 0x35;} // 5 if (_nibble == 0xf6) {return 0x36;} // 6 if (_nibble == 0xf7) {return 0x37;} // 7 if (_nibble == 0xf8) {return 0x38;} // 8 if (_nibble == 0xf9) {return 0x39;} // 9 if (_nibble == 0xfa) {return 0x61;} // a if (_nibble == 0xfb) {return 0x62;} // b if (_nibble == 0xfc) {return 0x63;} // c if (_nibble == 0xfd) {return 0x64;} // d if (_nibble == 0xfe) {return 0x65;} // e if (_nibble == 0xff) {return 0x66;} // f } /** * @notice Returns a uint16 containing the hex-encoded byte. * @param _b The byte * @return encoded - The hex-encoded byte */ function byteHex(uint8 _b) internal pure returns (uint16 encoded) { encoded |= nibbleHex(_b >> 4); // top 4 bits encoded <<= 8; encoded |= nibbleHex(_b); // lower 4 bits } /** * @notice Encodes the uint256 to hex. `first` contains the encoded top 16 bytes. * `second` contains the encoded lower 16 bytes. * * @param _b The 32 bytes as uint256 * @return first - The top 16 bytes * @return second - The bottom 16 bytes */ function encodeHex(uint256 _b) internal pure returns (uint256 first, uint256 second) { for (uint8 i = 31; i > 15; i -= 1) { uint8 _byte = uint8(_b >> (i * 8)); first |= byteHex(_byte); if (i != 16) { first <<= 16; } } // abusing underflow here =_= for (uint8 i = 15; i < 255 ; i -= 1) { uint8 _byte = uint8(_b >> (i * 8)); second |= byteHex(_byte); if (i != 0) { second <<= 16; } } } /** * @notice Changes the endianness of a uint256. * @dev https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel * @param _b The unsigned integer to reverse * @return v - The reversed value */ function reverseUint256(uint256 _b) internal pure returns (uint256 v) { v = _b; // swap bytes v = ((v >> 8) & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) | ((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8); // swap 2-byte long pairs v = ((v >> 16) & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) | ((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16); // swap 4-byte long pairs v = ((v >> 32) & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) | ((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32); // swap 8-byte long pairs v = ((v >> 64) & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) | ((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64); // swap 16-byte long pairs v = (v >> 128) | (v << 128); } /** * @notice Create a mask with the highest `_len` bits set. * @param _len The length * @return mask - The mask */ function leftMask(uint8 _len) private pure returns (uint256 mask) { // ugly. redo without assembly? assembly { // solium-disable-previous-line security/no-inline-assembly mask := sar( sub(_len, 1), 0x8000000000000000000000000000000000000000000000000000000000000000 ) } } /** * @notice Return the null view. * @return bytes29 - The null view */ function nullView() internal pure returns (bytes29) { return NULL; } /** * @notice Check if the view is null. * @return bool - True if the view is null */ function isNull(bytes29 memView) internal pure returns (bool) { return memView == NULL; } /** * @notice Check if the view is not null. * @return bool - True if the view is not null */ function notNull(bytes29 memView) internal pure returns (bool) { return !isNull(memView); } /** * @notice Check if the view is of a valid type and points to a valid location * in memory. * @dev We perform this check by examining solidity's unallocated memory * pointer and ensuring that the view's upper bound is less than that. * @param memView The view * @return ret - True if the view is valid */ function isValid(bytes29 memView) internal pure returns (bool ret) { if (typeOf(memView) == 0xffffffffff) {return false;} uint256 _end = end(memView); assembly { // solium-disable-previous-line security/no-inline-assembly ret := not(gt(_end, mload(0x40))) } } /** * @notice Require that a typed memory view be valid. * @dev Returns the view for easy chaining. * @param memView The view * @return bytes29 - The validated view */ function assertValid(bytes29 memView) internal pure returns (bytes29) { require(isValid(memView), "Validity assertion failed"); return memView; } /** * @notice Return true if the memview is of the expected type. Otherwise false. * @param memView The view * @param _expected The expected type * @return bool - True if the memview is of the expected type */ function isType(bytes29 memView, uint40 _expected) internal pure returns (bool) { return typeOf(memView) == _expected; } /** * @notice Require that a typed memory view has a specific type. * @dev Returns the view for easy chaining. * @param memView The view * @param _expected The expected type * @return bytes29 - The view with validated type */ function assertType(bytes29 memView, uint40 _expected) internal pure returns (bytes29) { if (!isType(memView, _expected)) { (, uint256 g) = encodeHex(uint256(typeOf(memView))); (, uint256 e) = encodeHex(uint256(_expected)); string memory err = string( abi.encodePacked( "Type assertion failed. Got 0x", uint80(g), ". Expected 0x", uint80(e) ) ); revert(err); } return memView; } /** * @notice Return an identical view with a different type. * @param memView The view * @param _newType The new type * @return newView - The new view with the specified type */ function castTo(bytes29 memView, uint40 _newType) internal pure returns (bytes29 newView) { // then | in the new type assembly { // solium-disable-previous-line security/no-inline-assembly // shift off the top 5 bytes newView := or(newView, shr(40, shl(40, memView))) newView := or(newView, shl(216, _newType)) } } /** * @notice Unsafe raw pointer construction. This should generally not be called * directly. Prefer `ref` wherever possible. * @dev Unsafe raw pointer construction. This should generally not be called * directly. Prefer `ref` wherever possible. * @param _type The type * @param _loc The memory address * @param _len The length * @return newView - The new view with the specified type, location and length */ function unsafeBuildUnchecked(uint256 _type, uint256 _loc, uint256 _len) private pure returns (bytes29 newView) { assembly { // solium-disable-previous-line security/no-inline-assembly newView := shl(96, or(newView, _type)) // insert type newView := shl(96, or(newView, _loc)) // insert loc newView := shl(24, or(newView, _len)) // empty bottom 3 bytes } } /** * @notice Instantiate a new memory view. This should generally not be called * directly. Prefer `ref` wherever possible. * @dev Instantiate a new memory view. This should generally not be called * directly. Prefer `ref` wherever possible. * @param _type The type * @param _loc The memory address * @param _len The length * @return newView - The new view with the specified type, location and length */ function build(uint256 _type, uint256 _loc, uint256 _len) internal pure returns (bytes29 newView) { uint256 _end = _loc.add(_len); assembly { // solium-disable-previous-line security/no-inline-assembly if gt(_end, mload(0x40)) { _end := 0 } } if (_end == 0) { return NULL; } newView = unsafeBuildUnchecked(_type, _loc, _len); } /** * @notice Instantiate a memory view from a byte array. * @dev Note that due to Solidity memory representation, it is not possible to * implement a deref, as the `bytes` type stores its len in memory. * @param arr The byte array * @param newType The type * @return bytes29 - The memory view */ function ref(bytes memory arr, uint40 newType) internal pure returns (bytes29) { uint256 _len = arr.length; uint256 _loc; assembly { // solium-disable-previous-line security/no-inline-assembly _loc := add(arr, 0x20) // our view is of the data, not the struct } return build(newType, _loc, _len); } /** * @notice Return the associated type information. * @param memView The memory view * @return _type - The type associated with the view */ function typeOf(bytes29 memView) internal pure returns (uint40 _type) { assembly { // solium-disable-previous-line security/no-inline-assembly // 216 == 256 - 40 _type := shr(216, memView) // shift out lower 24 bytes } } /** * @notice Optimized type comparison. Checks that the 5-byte type flag is equal. * @param left The first view * @param right The second view * @return bool - True if the 5-byte type flag is equal */ function sameType(bytes29 left, bytes29 right) internal pure returns (bool) { return (left ^ right) >> (2 * TWELVE_BYTES) == 0; } /** * @notice Return the memory address of the underlying bytes. * @param memView The view * @return _loc - The memory address */ function loc(bytes29 memView) internal pure returns (uint96 _loc) { uint256 _mask = LOW_12_MASK; // assembly can't use globals assembly { // solium-disable-previous-line security/no-inline-assembly // 120 bits = 12 bytes (the encoded loc) + 3 bytes (empty low space) _loc := and(shr(120, memView), _mask) } } /** * @notice The number of memory words this memory view occupies, rounded up. * @param memView The view * @return uint256 - The number of memory words */ function words(bytes29 memView) internal pure returns (uint256) { return uint256(len(memView)).add(32) / 32; } /** * @notice The in-memory footprint of a fresh copy of the view. * @param memView The view * @return uint256 - The in-memory footprint of a fresh copy of the view. */ function footprint(bytes29 memView) internal pure returns (uint256) { return words(memView) * 32; } /** * @notice The number of bytes of the view. * @param memView The view * @return _len - The length of the view */ function len(bytes29 memView) internal pure returns (uint96 _len) { uint256 _mask = LOW_12_MASK; // assembly can't use globals assembly { // solium-disable-previous-line security/no-inline-assembly _len := and(shr(24, memView), _mask) } } /** * @notice Returns the endpoint of `memView`. * @param memView The view * @return uint256 - The endpoint of `memView` */ function end(bytes29 memView) internal pure returns (uint256) { return loc(memView) + len(memView); } /** * @notice Safe slicing without memory modification. * @param memView The view * @param _index The start index * @param _len The length * @param newType The new type * @return bytes29 - The new view */ function slice(bytes29 memView, uint256 _index, uint256 _len, uint40 newType) internal pure returns (bytes29) { uint256 _loc = loc(memView); // Ensure it doesn't overrun the view if (_loc.add(_index).add(_len) > end(memView)) { return NULL; } _loc = _loc.add(_index); return build(newType, _loc, _len); } /** * @notice Shortcut to `slice`. Gets a view representing the first `_len` bytes. * @param memView The view * @param _len The length * @param newType The new type * @return bytes29 - The new view */ function prefix(bytes29 memView, uint256 _len, uint40 newType) internal pure returns (bytes29) { return slice(memView, 0, _len, newType); } /** * @notice Shortcut to `slice`. Gets a view representing the last `_len` byte. * @param memView The view * @param _len The length * @param newType The new type * @return bytes29 - The new view */ function postfix(bytes29 memView, uint256 _len, uint40 newType) internal pure returns (bytes29) { return slice(memView, uint256(len(memView)).sub(_len), _len, newType); } /** * @notice Construct an error message for an indexing overrun. * @param _loc The memory address * @param _len The length * @param _index The index * @param _slice The slice where the overrun occurred * @return err - The err */ function indexErrOverrun( uint256 _loc, uint256 _len, uint256 _index, uint256 _slice ) internal pure returns (string memory err) { (, uint256 a) = encodeHex(_loc); (, uint256 b) = encodeHex(_len); (, uint256 c) = encodeHex(_index); (, uint256 d) = encodeHex(_slice); err = string( abi.encodePacked( "TypedMemView/index - Overran the view. Slice is at 0x", uint48(a), " with length 0x", uint48(b), ". Attempted to index at offset 0x", uint48(c), " with length 0x", uint48(d), "." ) ); } /** * @notice Load up to 32 bytes from the view onto the stack. * @dev Returns a bytes32 with only the `_bytes` highest bytes set. * This can be immediately cast to a smaller fixed-length byte array. * To automatically cast to an integer, use `indexUint`. * @param memView The view * @param _index The index * @param _bytes The bytes * @return result - The 32 byte result */ function index(bytes29 memView, uint256 _index, uint8 _bytes) internal pure returns (bytes32 result) { if (_bytes == 0) {return bytes32(0);} if (_index.add(_bytes) > len(memView)) { revert(indexErrOverrun(loc(memView), len(memView), _index, uint256(_bytes))); } require(_bytes <= 32, "TypedMemView/index - Attempted to index more than 32 bytes"); uint8 bitLength = _bytes * 8; uint256 _loc = loc(memView); uint256 _mask = leftMask(bitLength); assembly { // solium-disable-previous-line security/no-inline-assembly result := and(mload(add(_loc, _index)), _mask) } } /** * @notice Parse an unsigned integer from the view at `_index`. * @dev Requires that the view have >= `_bytes` bytes following that index. * @param memView The view * @param _index The index * @param _bytes The bytes * @return result - The unsigned integer */ function indexUint(bytes29 memView, uint256 _index, uint8 _bytes) internal pure returns (uint256 result) { return uint256(index(memView, _index, _bytes)) >> ((32 - _bytes) * 8); } /** * @notice Parse an unsigned integer from LE bytes. * @param memView The view * @param _index The index * @param _bytes The bytes * @return result - The unsigned integer */ function indexLEUint(bytes29 memView, uint256 _index, uint8 _bytes) internal pure returns (uint256 result) { return reverseUint256(uint256(index(memView, _index, _bytes))); } /** * @notice Parse an address from the view at `_index`. Requires that the view have >= 20 bytes * following that index. * @param memView The view * @param _index The index * @return address - The address */ function indexAddress(bytes29 memView, uint256 _index) internal pure returns (address) { return address(uint160(indexUint(memView, _index, 20))); } /** * @notice Return the keccak256 hash of the underlying memory * @param memView The view * @return digest - The keccak256 hash of the underlying memory */ function keccak(bytes29 memView) internal pure returns (bytes32 digest) { uint256 _loc = loc(memView); uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly digest := keccak256(_loc, _len) } } /** * @notice Return the sha2 digest of the underlying memory. * @dev We explicitly deallocate memory afterwards. * @param memView The view * @return digest - The sha2 hash of the underlying memory */ function sha2(bytes29 memView) internal view returns (bytes32 digest) { uint256 _loc = loc(memView); uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly let ptr := mload(0x40) pop(staticcall(gas(), 2, _loc, _len, ptr, 0x20)) // sha2 #1 digest := mload(ptr) } } /** * @notice Implements bitcoin's hash160 (rmd160(sha2())) * @param memView The pre-image * @return digest - the Digest */ function hash160(bytes29 memView) internal view returns (bytes20 digest) { uint256 _loc = loc(memView); uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly let ptr := mload(0x40) pop(staticcall(gas(), 2, _loc, _len, ptr, 0x20)) // sha2 pop(staticcall(gas(), 3, ptr, 0x20, ptr, 0x20)) // rmd160 digest := mload(add(ptr, 0xc)) // return value is 0-prefixed. } } /** * @notice Implements bitcoin's hash256 (double sha2) * @param memView A view of the preimage * @return digest - the Digest */ function hash256(bytes29 memView) internal view returns (bytes32 digest) { uint256 _loc = loc(memView); uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly let ptr := mload(0x40) pop(staticcall(gas(), 2, _loc, _len, ptr, 0x20)) // sha2 #1 pop(staticcall(gas(), 2, ptr, 0x20, ptr, 0x20)) // sha2 #2 digest := mload(ptr) } } /** * @notice Return true if the underlying memory is equal. Else false. * @param left The first view * @param right The second view * @return bool - True if the underlying memory is equal */ function untypedEqual(bytes29 left, bytes29 right) internal pure returns (bool) { return (loc(left) == loc(right) && len(left) == len(right)) || keccak(left) == keccak(right); } /** * @notice Return false if the underlying memory is equal. Else true. * @param left The first view * @param right The second view * @return bool - False if the underlying memory is equal */ function untypedNotEqual(bytes29 left, bytes29 right) internal pure returns (bool) { return !untypedEqual(left, right); } /** * @notice Compares type equality. * @dev Shortcuts if the pointers are identical, otherwise compares type and digest. * @param left The first view * @param right The second view * @return bool - True if the types are the same */ function equal(bytes29 left, bytes29 right) internal pure returns (bool) { return left == right || (typeOf(left) == typeOf(right) && keccak(left) == keccak(right)); } /** * @notice Compares type inequality. * @dev Shortcuts if the pointers are identical, otherwise compares type and digest. * @param left The first view * @param right The second view * @return bool - True if the types are not the same */ function notEqual(bytes29 left, bytes29 right) internal pure returns (bool) { return !equal(left, right); } /** * @notice Copy the view to a location, return an unsafe memory reference * @dev Super Dangerous direct memory access. * * This reference can be overwritten if anything else modifies memory (!!!). * As such it MUST be consumed IMMEDIATELY. * This function is private to prevent unsafe usage by callers. * @param memView The view * @param _newLoc The new location * @return written - the unsafe memory reference */ function unsafeCopyTo(bytes29 memView, uint256 _newLoc) private view returns (bytes29 written) { require(notNull(memView), "TypedMemView/copyTo - Null pointer deref"); require(isValid(memView), "TypedMemView/copyTo - Invalid pointer deref"); uint256 _len = len(memView); uint256 _oldLoc = loc(memView); uint256 ptr; assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // revert if we're writing in occupied memory if gt(ptr, _newLoc) { revert(0x60, 0x20) // empty revert message } // use the identity precompile to copy // guaranteed not to fail, so pop the success pop(staticcall(gas(), 4, _oldLoc, _len, _newLoc, _len)) } written = unsafeBuildUnchecked(typeOf(memView), _newLoc, _len); } /** * @notice Copies the referenced memory to a new loc in memory, returning a `bytes` pointing to * the new memory * @dev Shortcuts if the pointers are identical, otherwise compares type and digest. * @param memView The view * @return ret - The view pointing to the new memory */ function clone(bytes29 memView) internal view returns (bytes memory ret) { uint256 ptr; uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // load unused memory pointer ret := ptr } unsafeCopyTo(memView, ptr + 0x20); assembly { // solium-disable-previous-line security/no-inline-assembly mstore(0x40, add(add(ptr, _len), 0x20)) // write new unused pointer mstore(ptr, _len) // write len of new array (in bytes) } } /** * @notice Join the views in memory, return an unsafe reference to the memory. * @dev Super Dangerous direct memory access. * * This reference can be overwritten if anything else modifies memory (!!!). * As such it MUST be consumed IMMEDIATELY. * This function is private to prevent unsafe usage by callers. * @param memViews The views * @return unsafeView - The conjoined view pointing to the new memory */ function unsafeJoin(bytes29[] memory memViews, uint256 _location) private view returns (bytes29 unsafeView) { assembly { // solium-disable-previous-line security/no-inline-assembly let ptr := mload(0x40) // revert if we're writing in occupied memory if gt(ptr, _location) { revert(0x60, 0x20) // empty revert message } } uint256 _offset = 0; for (uint256 i = 0; i < memViews.length; i ++) { bytes29 memView = memViews[i]; unsafeCopyTo(memView, _location + _offset); _offset += len(memView); } unsafeView = unsafeBuildUnchecked(0, _location, _offset); } /** * @notice Produce the keccak256 digest of the concatenated contents of multiple views. * @param memViews The views * @return bytes32 - The keccak256 digest */ function joinKeccak(bytes29[] memory memViews) internal view returns (bytes32) { uint256 ptr; assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // load unused memory pointer } return keccak(unsafeJoin(memViews, ptr)); } /** * @notice Produce the sha256 digest of the concatenated contents of multiple views. * @param memViews The views * @return bytes32 - The sha256 digest */ function joinSha2(bytes29[] memory memViews) internal view returns (bytes32) { uint256 ptr; assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // load unused memory pointer } return sha2(unsafeJoin(memViews, ptr)); } /** * @notice copies all views, joins them into a new bytearray. * @param memViews The views * @return ret - The new byte array */ function join(bytes29[] memory memViews) internal view returns (bytes memory ret) { uint256 ptr; assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // load unused memory pointer } bytes29 _newView = unsafeJoin(memViews, ptr + 0x20); uint256 _written = len(_newView); uint256 _footprint = footprint(_newView); assembly { // solium-disable-previous-line security/no-inline-assembly // store the legnth mstore(ptr, _written) // new pointer is old + 0x20 + the footprint of the body mstore(0x40, add(add(ptr, _footprint), 0x20)) ret := ptr } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using 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"); } } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; library Encoding { // ============ Constants ============ bytes private constant NIBBLE_LOOKUP = "0123456789abcdef"; // ============ Internal Functions ============ /** * @notice Encode a uint32 in its DECIMAL representation, with leading * zeroes. * @param _num The number to encode * @return _encoded The encoded number, suitable for use in abi. * encodePacked */ function decimalUint32(uint32 _num) internal pure returns (uint80 _encoded) { uint80 ASCII_0 = 0x30; // all over/underflows are impossible // this will ALWAYS produce 10 decimal characters for (uint8 i = 0; i < 10; i += 1) { _encoded |= ((_num % 10) + ASCII_0) << (i * 8); _num = _num / 10; } } /** * @notice Encodes the uint256 to hex. `first` contains the encoded top 16 bytes. * `second` contains the encoded lower 16 bytes. * @param _bytes The 32 bytes as uint256 * @return _firstHalf The top 16 bytes * @return _secondHalf The bottom 16 bytes */ function encodeHex(uint256 _bytes) internal pure returns (uint256 _firstHalf, uint256 _secondHalf) { for (uint8 i = 31; i > 15; i -= 1) { uint8 _b = uint8(_bytes >> (i * 8)); _firstHalf |= _byteHex(_b); if (i != 16) { _firstHalf <<= 16; } } // abusing underflow here =_= for (uint8 i = 15; i < 255; i -= 1) { uint8 _b = uint8(_bytes >> (i * 8)); _secondHalf |= _byteHex(_b); if (i != 0) { _secondHalf <<= 16; } } } /** * @notice Returns the encoded hex character that represents the lower 4 bits of the argument. * @param _byte The byte * @return _char The encoded hex character */ function _nibbleHex(uint8 _byte) private pure returns (uint8 _char) { uint8 _nibble = _byte & 0x0f; // keep bottom 4, 0 top 4 _char = uint8(NIBBLE_LOOKUP[_nibble]); } /** * @notice Returns a uint16 containing the hex-encoded byte. * @param _byte The byte * @return _encoded The hex-encoded byte */ function _byteHex(uint8 _byte) private pure returns (uint16 _encoded) { _encoded |= _nibbleHex(_byte >> 4); // top 4 bits _encoded <<= 8; _encoded |= _nibbleHex(_byte); // lower 4 bits } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; // ============ External Imports ============ import {Address} from "@openzeppelin/contracts/utils/Address.sol"; /** * @title UpgradeBeaconProxy * @notice * Proxy contract which delegates all logic, including initialization, * to an implementation contract. * The implementation contract is stored within an Upgrade Beacon contract; * the implementation contract can be changed by performing an upgrade on the Upgrade Beacon contract. * The Upgrade Beacon contract for this Proxy is immutably specified at deployment. * @dev This implementation combines the gas savings of keeping the UpgradeBeacon address outside of contract storage * found in 0age's implementation: * https://github.com/dharma-eng/dharma-smart-wallet/blob/master/contracts/proxies/smart-wallet/UpgradeBeaconProxyV1.sol * With the added safety checks that the UpgradeBeacon and implementation are contracts at time of deployment * found in OpenZeppelin's implementation: * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/proxy/beacon/BeaconProxy.sol */ contract UpgradeBeaconProxy { // ============ Immutables ============ // Upgrade Beacon address is immutable (therefore not kept in contract storage) address private immutable upgradeBeacon; // ============ Constructor ============ /** * @notice Validate that the Upgrade Beacon is a contract, then set its * address immutably within this contract. * Validate that the implementation is also a contract, * Then call the initialization function defined at the implementation. * The deployment will revert and pass along the * revert reason if the initialization function reverts. * @param _upgradeBeacon Address of the Upgrade Beacon to be stored immutably in the contract * @param _initializationCalldata Calldata supplied when calling the initialization function */ constructor(address _upgradeBeacon, bytes memory _initializationCalldata) payable { // Validate the Upgrade Beacon is a contract require(Address.isContract(_upgradeBeacon), "beacon !contract"); // set the Upgrade Beacon upgradeBeacon = _upgradeBeacon; // Validate the implementation is a contract address _implementation = _getImplementation(_upgradeBeacon); require( Address.isContract(_implementation), "beacon implementation !contract" ); // Call the initialization function on the implementation if (_initializationCalldata.length > 0) { _initialize(_implementation, _initializationCalldata); } } // ============ External Functions ============ /** * @notice Forwards all calls with data to _fallback() * No public functions are declared on the contract, so all calls hit fallback */ fallback() external payable { _fallback(); } /** * @notice Forwards all calls with no data to _fallback() */ receive() external payable { _fallback(); } // ============ Private Functions ============ /** * @notice Call the initialization function on the implementation * Used at deployment to initialize the proxy * based on the logic for initialization defined at the implementation * @param _implementation - Contract to which the initalization is delegated * @param _initializationCalldata - Calldata supplied when calling the initialization function */ function _initialize( address _implementation, bytes memory _initializationCalldata ) private { // Delegatecall into the implementation, supplying initialization calldata. (bool _ok, ) = _implementation.delegatecall(_initializationCalldata); // Revert and include revert data if delegatecall to implementation reverts. if (!_ok) { assembly { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } } /** * @notice Delegates function calls to the implementation contract returned by the Upgrade Beacon */ function _fallback() private { _delegate(_getImplementation()); } /** * @notice Delegate function execution to the implementation contract * @dev This is a low level function that doesn't return to its internal * call site. It will return whatever is returned by the implementation to the * external caller, reverting and returning the revert data if implementation * reverts. * @param _implementation - Address to which the function execution is delegated */ function _delegate(address _implementation) private { 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()) // Delegatecall to the implementation, supplying calldata and gas. // Out and outsize are set to zero - instead, use the return buffer. let result := delegatecall( gas(), _implementation, 0, calldatasize(), 0, 0 ) // Copy the returned data from the return buffer. returndatacopy(0, 0, returndatasize()) switch result // Delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @notice Call the Upgrade Beacon to get the current implementation contract address * @return _implementation Address of the current implementation. */ function _getImplementation() private view returns (address _implementation) { _implementation = _getImplementation(upgradeBeacon); } /** * @notice Call the Upgrade Beacon to get the current implementation contract address * @dev _upgradeBeacon is passed as a parameter so that * we can also use this function in the constructor, * where we can't access immutable variables. * @param _upgradeBeacon Address of the UpgradeBeacon storing the current implementation * @return _implementation Address of the current implementation. */ function _getImplementation(address _upgradeBeacon) private view returns (address _implementation) { // Get the current implementation address from the upgrade beacon. (bool _ok, bytes memory _returnData) = _upgradeBeacon.staticcall(""); // Revert and pass along revert message if call to upgrade beacon reverts. require(_ok, string(_returnData)); // Set the implementation to the address returned from the upgrade beacon. _implementation = abi.decode(_returnData, (address)); } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @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 {UpgradeableProxy-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 || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.10; /* The MIT License (MIT) Copyright (c) 2016 Smart Contract Solutions, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @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; require(c / _a == _b, "Overflow during multiplication."); 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) { require(_b <= _a, "Underflow during subtraction."); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; require(c >= _a, "Overflow during addition."); return c; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @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 initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), 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 { 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 virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {Message} from "../libs/Message.sol"; // ============ External Imports ============ import {ECDSA} from "@openzeppelin/contracts/cryptography/ECDSA.sol"; import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /** * @title Common * @author Celo Labs Inc. * @notice Shared utilities between Home and Replica. */ abstract contract Common is Initializable { // ============ Enums ============ // States: // 0 - UnInitialized - before initialize function is called // note: the contract is initialized at deploy time, so it should never be in this state // 1 - Active - as long as the contract has not become fraudulent // 2 - Failed - after a valid fraud proof has been submitted; // contract will no longer accept updates or new messages enum States { UnInitialized, Active, Failed } // ============ Immutable Variables ============ // Domain of chain on which the contract is deployed uint32 public immutable localDomain; // ============ Public Variables ============ // Address of bonded Updater address public updater; // Current state of contract States public state; // The latest root that has been signed by the Updater bytes32 public committedRoot; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[47] private __GAP; // ============ Events ============ /** * @notice Emitted when update is made on Home * or unconfirmed update root is submitted on Replica * @param homeDomain Domain of home contract * @param oldRoot Old merkle root * @param newRoot New merkle root * @param signature Updater's signature on `oldRoot` and `newRoot` */ event Update( uint32 indexed homeDomain, bytes32 indexed oldRoot, bytes32 indexed newRoot, bytes signature ); /** * @notice Emitted when proof of a double update is submitted, * which sets the contract to FAILED state * @param oldRoot Old root shared between two conflicting updates * @param newRoot Array containing two conflicting new roots * @param signature Signature on `oldRoot` and `newRoot`[0] * @param signature2 Signature on `oldRoot` and `newRoot`[1] */ event DoubleUpdate( bytes32 oldRoot, bytes32[2] newRoot, bytes signature, bytes signature2 ); // ============ Modifiers ============ /** * @notice Ensures that contract state != FAILED when the function is called */ modifier notFailed() { require(state != States.Failed, "failed state"); _; } // ============ Constructor ============ constructor(uint32 _localDomain) { localDomain = _localDomain; } // ============ Initializer ============ function __Common_initialize(address _updater) internal initializer { updater = _updater; state = States.Active; } // ============ External Functions ============ /** * @notice Called by external agent. Checks that signatures on two sets of * roots are valid and that the new roots conflict with each other. If both * cases hold true, the contract is failed and a `DoubleUpdate` event is * emitted. * @dev When `fail()` is called on Home, updater is slashed. * @param _oldRoot Old root shared between two conflicting updates * @param _newRoot Array containing two conflicting new roots * @param _signature Signature on `_oldRoot` and `_newRoot`[0] * @param _signature2 Signature on `_oldRoot` and `_newRoot`[1] */ function doubleUpdate( bytes32 _oldRoot, bytes32[2] calldata _newRoot, bytes calldata _signature, bytes calldata _signature2 ) external notFailed { if ( Common._isUpdaterSignature(_oldRoot, _newRoot[0], _signature) && Common._isUpdaterSignature(_oldRoot, _newRoot[1], _signature2) && _newRoot[0] != _newRoot[1] ) { _fail(); emit DoubleUpdate(_oldRoot, _newRoot, _signature, _signature2); } } // ============ Public Functions ============ /** * @notice Hash of Home domain concatenated with "OPTICS" */ function homeDomainHash() public view virtual returns (bytes32); // ============ Internal Functions ============ /** * @notice Hash of Home domain concatenated with "OPTICS" * @param _homeDomain the Home domain to hash */ function _homeDomainHash(uint32 _homeDomain) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_homeDomain, "OPTICS")); } /** * @notice Set contract state to FAILED * @dev Called when a valid fraud proof is submitted */ function _setFailed() internal { state = States.Failed; } /** * @notice Moves the contract into failed state * @dev Called when fraud is proven * (Double Update is submitted on Home or Replica, * or Improper Update is submitted on Home) */ function _fail() internal virtual; /** * @notice Checks that signature was signed by Updater * @param _oldRoot Old merkle root * @param _newRoot New merkle root * @param _signature Signature on `_oldRoot` and `_newRoot` * @return TRUE iff signature is valid signed by updater **/ function _isUpdaterSignature( bytes32 _oldRoot, bytes32 _newRoot, bytes memory _signature ) internal view returns (bool) { bytes32 _digest = keccak256( abi.encodePacked(homeDomainHash(), _oldRoot, _newRoot) ); _digest = ECDSA.toEthSignedMessageHash(_digest); return (ECDSA.recover(_digest, _signature) == updater); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; /** * @title QueueLib * @author Celo Labs Inc. * @notice Library containing queue struct and operations for queue used by * Home and Replica. **/ library QueueLib { /** * @notice Queue struct * @dev Internally keeps track of the `first` and `last` elements through * indices and a mapping of indices to enqueued elements. **/ struct Queue { uint128 first; uint128 last; mapping(uint256 => bytes32) queue; } /** * @notice Initializes the queue * @dev Empty state denoted by _q.first > q._last. Queue initialized * with _q.first = 1 and _q.last = 0. **/ function initialize(Queue storage _q) internal { if (_q.first == 0) { _q.first = 1; } } /** * @notice Enqueues a single new element * @param _item New element to be enqueued * @return _last Index of newly enqueued element **/ function enqueue(Queue storage _q, bytes32 _item) internal returns (uint128 _last) { _last = _q.last + 1; _q.last = _last; if (_item != bytes32(0)) { // saves gas if we're queueing 0 _q.queue[_last] = _item; } } /** * @notice Dequeues element at front of queue * @dev Removes dequeued element from storage * @return _item Dequeued element **/ function dequeue(Queue storage _q) internal returns (bytes32 _item) { uint128 _last = _q.last; uint128 _first = _q.first; require(_length(_last, _first) != 0, "Empty"); _item = _q.queue[_first]; if (_item != bytes32(0)) { // saves gas if we're dequeuing 0 delete _q.queue[_first]; } _q.first = _first + 1; } /** * @notice Batch enqueues several elements * @param _items Array of elements to be enqueued * @return _last Index of last enqueued element **/ function enqueue(Queue storage _q, bytes32[] memory _items) internal returns (uint128 _last) { _last = _q.last; for (uint256 i = 0; i < _items.length; i += 1) { _last += 1; bytes32 _item = _items[i]; if (_item != bytes32(0)) { _q.queue[_last] = _item; } } _q.last = _last; } /** * @notice Batch dequeues `_number` elements * @dev Reverts if `_number` > queue length * @param _number Number of elements to dequeue * @return Array of dequeued elements **/ function dequeue(Queue storage _q, uint256 _number) internal returns (bytes32[] memory) { uint128 _last = _q.last; uint128 _first = _q.first; // Cannot underflow unless state is corrupted require(_length(_last, _first) >= _number, "Insufficient"); bytes32[] memory _items = new bytes32[](_number); for (uint256 i = 0; i < _number; i++) { _items[i] = _q.queue[_first]; delete _q.queue[_first]; _first++; } _q.first = _first; return _items; } /** * @notice Returns true if `_item` is in the queue and false if otherwise * @dev Linearly scans from _q.first to _q.last looking for `_item` * @param _item Item being searched for in queue * @return True if `_item` currently exists in queue, false if otherwise **/ function contains(Queue storage _q, bytes32 _item) internal view returns (bool) { for (uint256 i = _q.first; i <= _q.last; i++) { if (_q.queue[i] == _item) { return true; } } return false; } /// @notice Returns last item in queue /// @dev Returns bytes32(0) if queue empty function lastItem(Queue storage _q) internal view returns (bytes32) { return _q.queue[_q.last]; } /// @notice Returns element at front of queue without removing element /// @dev Reverts if queue is empty function peek(Queue storage _q) internal view returns (bytes32 _item) { require(!isEmpty(_q), "Empty"); _item = _q.queue[_q.first]; } /// @notice Returns true if queue is empty and false if otherwise function isEmpty(Queue storage _q) internal view returns (bool) { return _q.last < _q.first; } /// @notice Returns number of elements in queue function length(Queue storage _q) internal view returns (uint256) { uint128 _last = _q.last; uint128 _first = _q.first; // Cannot underflow unless state is corrupted return _length(_last, _first); } /// @notice Returns number of elements between `_last` and `_first` (used internally) function _length(uint128 _last, uint128 _first) internal pure returns (uint256) { return uint256(_last + 1 - _first); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // work based on eth2 deposit contract, which is used under CC0-1.0 /** * @title MerkleLib * @author Celo Labs Inc. * @notice An incremental merkle tree modeled on the eth2 deposit contract. **/ library MerkleLib { uint256 internal constant TREE_DEPTH = 32; uint256 internal constant MAX_LEAVES = 2**TREE_DEPTH - 1; /** * @notice Struct representing incremental merkle tree. Contains current * branch and the number of inserted leaves in the tree. **/ struct Tree { bytes32[TREE_DEPTH] branch; uint256 count; } /** * @notice Inserts `_node` into merkle tree * @dev Reverts if tree is full * @param _node Element to insert into tree **/ function insert(Tree storage _tree, bytes32 _node) internal { require(_tree.count < MAX_LEAVES, "merkle tree full"); _tree.count += 1; uint256 size = _tree.count; for (uint256 i = 0; i < TREE_DEPTH; i++) { if ((size & 1) == 1) { _tree.branch[i] = _node; return; } _node = keccak256(abi.encodePacked(_tree.branch[i], _node)); size /= 2; } // As the loop should always end prematurely with the `return` statement, // this code should be unreachable. We assert `false` just to be safe. assert(false); } /** * @notice Calculates and returns`_tree`'s current root given array of zero * hashes * @param _zeroes Array of zero hashes * @return _current Calculated root of `_tree` **/ function rootWithCtx(Tree storage _tree, bytes32[TREE_DEPTH] memory _zeroes) internal view returns (bytes32 _current) { uint256 _index = _tree.count; for (uint256 i = 0; i < TREE_DEPTH; i++) { uint256 _ithBit = (_index >> i) & 0x01; bytes32 _next = _tree.branch[i]; if (_ithBit == 1) { _current = keccak256(abi.encodePacked(_next, _current)); } else { _current = keccak256(abi.encodePacked(_current, _zeroes[i])); } } } /// @notice Calculates and returns`_tree`'s current root function root(Tree storage _tree) internal view returns (bytes32) { return rootWithCtx(_tree, zeroHashes()); } /// @notice Returns array of TREE_DEPTH zero hashes /// @return _zeroes Array of TREE_DEPTH zero hashes function zeroHashes() internal pure returns (bytes32[TREE_DEPTH] memory _zeroes) { _zeroes[0] = Z_0; _zeroes[1] = Z_1; _zeroes[2] = Z_2; _zeroes[3] = Z_3; _zeroes[4] = Z_4; _zeroes[5] = Z_5; _zeroes[6] = Z_6; _zeroes[7] = Z_7; _zeroes[8] = Z_8; _zeroes[9] = Z_9; _zeroes[10] = Z_10; _zeroes[11] = Z_11; _zeroes[12] = Z_12; _zeroes[13] = Z_13; _zeroes[14] = Z_14; _zeroes[15] = Z_15; _zeroes[16] = Z_16; _zeroes[17] = Z_17; _zeroes[18] = Z_18; _zeroes[19] = Z_19; _zeroes[20] = Z_20; _zeroes[21] = Z_21; _zeroes[22] = Z_22; _zeroes[23] = Z_23; _zeroes[24] = Z_24; _zeroes[25] = Z_25; _zeroes[26] = Z_26; _zeroes[27] = Z_27; _zeroes[28] = Z_28; _zeroes[29] = Z_29; _zeroes[30] = Z_30; _zeroes[31] = Z_31; } /** * @notice Calculates and returns the merkle root for the given leaf * `_item`, a merkle branch, and the index of `_item` in the tree. * @param _item Merkle leaf * @param _branch Merkle proof * @param _index Index of `_item` in tree * @return _current Calculated merkle root **/ function branchRoot( bytes32 _item, bytes32[TREE_DEPTH] memory _branch, uint256 _index ) internal pure returns (bytes32 _current) { _current = _item; for (uint256 i = 0; i < TREE_DEPTH; i++) { uint256 _ithBit = (_index >> i) & 0x01; bytes32 _next = _branch[i]; if (_ithBit == 1) { _current = keccak256(abi.encodePacked(_next, _current)); } else { _current = keccak256(abi.encodePacked(_current, _next)); } } } // keccak256 zero hashes bytes32 internal constant Z_0 = hex"0000000000000000000000000000000000000000000000000000000000000000"; bytes32 internal constant Z_1 = hex"ad3228b676f7d3cd4284a5443f17f1962b36e491b30a40b2405849e597ba5fb5"; bytes32 internal constant Z_2 = hex"b4c11951957c6f8f642c4af61cd6b24640fec6dc7fc607ee8206a99e92410d30"; bytes32 internal constant Z_3 = hex"21ddb9a356815c3fac1026b6dec5df3124afbadb485c9ba5a3e3398a04b7ba85"; bytes32 internal constant Z_4 = hex"e58769b32a1beaf1ea27375a44095a0d1fb664ce2dd358e7fcbfb78c26a19344"; bytes32 internal constant Z_5 = hex"0eb01ebfc9ed27500cd4dfc979272d1f0913cc9f66540d7e8005811109e1cf2d"; bytes32 internal constant Z_6 = hex"887c22bd8750d34016ac3c66b5ff102dacdd73f6b014e710b51e8022af9a1968"; bytes32 internal constant Z_7 = hex"ffd70157e48063fc33c97a050f7f640233bf646cc98d9524c6b92bcf3ab56f83"; bytes32 internal constant Z_8 = hex"9867cc5f7f196b93bae1e27e6320742445d290f2263827498b54fec539f756af"; bytes32 internal constant Z_9 = hex"cefad4e508c098b9a7e1d8feb19955fb02ba9675585078710969d3440f5054e0"; bytes32 internal constant Z_10 = hex"f9dc3e7fe016e050eff260334f18a5d4fe391d82092319f5964f2e2eb7c1c3a5"; bytes32 internal constant Z_11 = hex"f8b13a49e282f609c317a833fb8d976d11517c571d1221a265d25af778ecf892"; bytes32 internal constant Z_12 = hex"3490c6ceeb450aecdc82e28293031d10c7d73bf85e57bf041a97360aa2c5d99c"; bytes32 internal constant Z_13 = hex"c1df82d9c4b87413eae2ef048f94b4d3554cea73d92b0f7af96e0271c691e2bb"; bytes32 internal constant Z_14 = hex"5c67add7c6caf302256adedf7ab114da0acfe870d449a3a489f781d659e8becc"; bytes32 internal constant Z_15 = hex"da7bce9f4e8618b6bd2f4132ce798cdc7a60e7e1460a7299e3c6342a579626d2"; bytes32 internal constant Z_16 = hex"2733e50f526ec2fa19a22b31e8ed50f23cd1fdf94c9154ed3a7609a2f1ff981f"; bytes32 internal constant Z_17 = hex"e1d3b5c807b281e4683cc6d6315cf95b9ade8641defcb32372f1c126e398ef7a"; bytes32 internal constant Z_18 = hex"5a2dce0a8a7f68bb74560f8f71837c2c2ebbcbf7fffb42ae1896f13f7c7479a0"; bytes32 internal constant Z_19 = hex"b46a28b6f55540f89444f63de0378e3d121be09e06cc9ded1c20e65876d36aa0"; bytes32 internal constant Z_20 = hex"c65e9645644786b620e2dd2ad648ddfcbf4a7e5b1a3a4ecfe7f64667a3f0b7e2"; bytes32 internal constant Z_21 = hex"f4418588ed35a2458cffeb39b93d26f18d2ab13bdce6aee58e7b99359ec2dfd9"; bytes32 internal constant Z_22 = hex"5a9c16dc00d6ef18b7933a6f8dc65ccb55667138776f7dea101070dc8796e377"; bytes32 internal constant Z_23 = hex"4df84f40ae0c8229d0d6069e5c8f39a7c299677a09d367fc7b05e3bc380ee652"; bytes32 internal constant Z_24 = hex"cdc72595f74c7b1043d0e1ffbab734648c838dfb0527d971b602bc216c9619ef"; bytes32 internal constant Z_25 = hex"0abf5ac974a1ed57f4050aa510dd9c74f508277b39d7973bb2dfccc5eeb0618d"; bytes32 internal constant Z_26 = hex"b8cd74046ff337f0a7bf2c8e03e10f642c1886798d71806ab1e888d9e5ee87d0"; bytes32 internal constant Z_27 = hex"838c5655cb21c6cb83313b5a631175dff4963772cce9108188b34ac87c81c41e"; bytes32 internal constant Z_28 = hex"662ee4dd2dd7b2bc707961b1e646c4047669dcb6584f0d8d770daf5d7e7deb2e"; bytes32 internal constant Z_29 = hex"388ab20e2573d171a88108e79d820e98f26c0b84aa8b2f4aa4968dbb818ea322"; bytes32 internal constant Z_30 = hex"93237c50ba75ee485f4c22adf2f741400bdf8d6a9cc7df7ecae576221665d735"; bytes32 internal constant Z_31 = hex"8448818bb4ae4562849e949e17ac16e0be16688e156b5cf15e098c627c0056a9"; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; import "@summa-tx/memview-sol/contracts/TypedMemView.sol"; import { TypeCasts } from "./TypeCasts.sol"; /** * @title Message Library * @author Celo Labs Inc. * @notice Library for formatted messages used by Home and Replica. **/ library Message { using TypedMemView for bytes; using TypedMemView for bytes29; // Number of bytes in formatted message before `body` field uint256 internal constant PREFIX_LENGTH = 76; /** * @notice Returns formatted (packed) message with provided fields * @param _originDomain Domain of home chain * @param _sender Address of sender as bytes32 * @param _nonce Destination-specific nonce * @param _destinationDomain Domain of destination chain * @param _recipient Address of recipient on destination chain as bytes32 * @param _messageBody Raw bytes of message body * @return Formatted message **/ function formatMessage( uint32 _originDomain, bytes32 _sender, uint32 _nonce, uint32 _destinationDomain, bytes32 _recipient, bytes memory _messageBody ) internal pure returns (bytes memory) { return abi.encodePacked( _originDomain, _sender, _nonce, _destinationDomain, _recipient, _messageBody ); } /** * @notice Returns leaf of formatted message with provided fields. * @param _origin Domain of home chain * @param _sender Address of sender as bytes32 * @param _nonce Destination-specific nonce number * @param _destination Domain of destination chain * @param _recipient Address of recipient on destination chain as bytes32 * @param _body Raw bytes of message body * @return Leaf (hash) of formatted message **/ function messageHash( uint32 _origin, bytes32 _sender, uint32 _nonce, uint32 _destination, bytes32 _recipient, bytes memory _body ) internal pure returns (bytes32) { return keccak256( formatMessage( _origin, _sender, _nonce, _destination, _recipient, _body ) ); } /// @notice Returns message's origin field function origin(bytes29 _message) internal pure returns (uint32) { return uint32(_message.indexUint(0, 4)); } /// @notice Returns message's sender field function sender(bytes29 _message) internal pure returns (bytes32) { return _message.index(4, 32); } /// @notice Returns message's nonce field function nonce(bytes29 _message) internal pure returns (uint32) { return uint32(_message.indexUint(36, 4)); } /// @notice Returns message's destination field function destination(bytes29 _message) internal pure returns (uint32) { return uint32(_message.indexUint(40, 4)); } /// @notice Returns message's recipient field as bytes32 function recipient(bytes29 _message) internal pure returns (bytes32) { return _message.index(44, 32); } /// @notice Returns message's recipient field as an address function recipientAddress(bytes29 _message) internal pure returns (address) { return TypeCasts.bytes32ToAddress(recipient(_message)); } /// @notice Returns message's body field as bytes29 (refer to TypedMemView library for details on bytes29 type) function body(bytes29 _message) internal pure returns (bytes29) { return _message.slice(PREFIX_LENGTH, _message.len() - PREFIX_LENGTH, 0); } function leaf(bytes29 _message) internal view returns (bytes32) { return messageHash(origin(_message), sender(_message), nonce(_message), destination(_message), recipient(_message), TypedMemView.clone(body(_message))); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {MerkleLib} from "../libs/Merkle.sol"; /** * @title MerkleTreeManager * @author Celo Labs Inc. * @notice Contains a Merkle tree instance and * exposes view functions for the tree. */ contract MerkleTreeManager { // ============ Libraries ============ using MerkleLib for MerkleLib.Tree; MerkleLib.Tree public tree; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[49] private __GAP; // ============ Public Functions ============ /** * @notice Calculates and returns tree's current root */ function root() public view returns (bytes32) { return tree.root(); } /** * @notice Returns the number of inserted leaves in the tree (current index) */ function count() public view returns (uint256) { return tree.count; } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {QueueLib} from "../libs/Queue.sol"; // ============ External Imports ============ import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /** * @title QueueManager * @author Celo Labs Inc. * @notice Contains a queue instance and * exposes view functions for the queue. **/ contract QueueManager is Initializable { // ============ Libraries ============ using QueueLib for QueueLib.Queue; QueueLib.Queue internal queue; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[49] private __GAP; // ============ Initializer ============ function __QueueManager_initialize() internal initializer { queue.initialize(); } // ============ Public Functions ============ /** * @notice Returns number of elements in queue */ function queueLength() external view returns (uint256) { return queue.length(); } /** * @notice Returns TRUE iff `_item` is in the queue */ function queueContains(bytes32 _item) external view returns (bool) { return queue.contains(_item); } /** * @notice Returns last item enqueued to the queue */ function queueEnd() external view returns (bytes32) { return queue.lastItem(); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; interface IUpdaterManager { function slashUpdater(address payable _reporter) external; function updater() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <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; // 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); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ 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. * * 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) { revert("ECDSA: invalid signature length"); } // 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))) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // 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. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @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)); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; import "@summa-tx/memview-sol/contracts/TypedMemView.sol"; library TypeCasts { using TypedMemView for bytes; using TypedMemView for bytes29; function coerceBytes32(string memory _s) internal pure returns (bytes32 _b) { _b = bytes(_s).ref(0).index(0, uint8(bytes(_s).length)); } // treat it as a null-terminated string of max 32 bytes function coerceString(bytes32 _buf) internal pure returns (string memory _newStr) { uint8 _slen = 0; while (_slen < 32 && _buf[_slen] != 0) { _slen++; } // solhint-disable-next-line no-inline-assembly assembly { _newStr := mload(0x40) mstore(0x40, add(_newStr, 0x40)) // may end up with extra mstore(_newStr, _slen) mstore(add(_newStr, 0x20), _buf) } } // alignment preserving cast function addressToBytes32(address _addr) internal pure returns (bytes32) { return bytes32(uint256(uint160(_addr))); } // alignment preserving cast function bytes32ToAddress(bytes32 _buf) internal pure returns (address) { return address(uint160(uint256(_buf))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <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; // 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); } 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); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @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 ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } 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; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {Version0} from "./Version0.sol"; import {Common} from "./Common.sol"; import {MerkleLib} from "../libs/Merkle.sol"; import {Message} from "../libs/Message.sol"; import {IMessageRecipient} from "../interfaces/IMessageRecipient.sol"; // ============ External Imports ============ import {TypedMemView} from "@summa-tx/memview-sol/contracts/TypedMemView.sol"; /** * @title Replica * @author Celo Labs Inc. * @notice Track root updates on Home, * prove and dispatch messages to end recipients. */ contract Replica is Version0, Common { // ============ Libraries ============ using MerkleLib for MerkleLib.Tree; using TypedMemView for bytes; using TypedMemView for bytes29; using Message for bytes29; // ============ Enums ============ // Status of Message: // 0 - None - message has not been proven or processed // 1 - Proven - message inclusion proof has been validated // 2 - Processed - message has been dispatched to recipient enum MessageStatus { None, Proven, Processed } // ============ Immutables ============ // Minimum gas for message processing uint256 public immutable PROCESS_GAS; // Reserved gas (to ensure tx completes in case message processing runs out) uint256 public immutable RESERVE_GAS; // ============ Public Storage ============ // Domain of home chain uint32 public remoteDomain; // Number of seconds to wait before root becomes confirmable uint256 public optimisticSeconds; // re-entrancy guard uint8 private entered; // Mapping of roots to allowable confirmation times mapping(bytes32 => uint256) public confirmAt; // Mapping of message leaves to MessageStatus mapping(bytes32 => MessageStatus) public messages; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[44] private __GAP; // ============ Events ============ /** * @notice Emitted when message is processed * @param messageHash Hash of message that failed to process * @param success TRUE if the call was executed successfully, FALSE if the call reverted * @param returnData the return data from the external call */ event Process( bytes32 indexed messageHash, bool indexed success, bytes indexed returnData ); // ============ Constructor ============ // solhint-disable-next-line no-empty-blocks constructor( uint32 _localDomain, uint256 _processGas, uint256 _reserveGas ) Common(_localDomain) { require(_processGas >= 850_000, "!process gas"); require(_reserveGas >= 15_000, "!reserve gas"); PROCESS_GAS = _processGas; RESERVE_GAS = _reserveGas; } // ============ Initializer ============ function initialize( uint32 _remoteDomain, address _updater, bytes32 _committedRoot, uint256 _optimisticSeconds ) public initializer { __Common_initialize(_updater); entered = 1; remoteDomain = _remoteDomain; committedRoot = _committedRoot; confirmAt[_committedRoot] = 1; optimisticSeconds = _optimisticSeconds; } // ============ External Functions ============ /** * @notice Called by external agent. Submits the signed update's new root, * marks root's allowable confirmation time, and emits an `Update` event. * @dev Reverts if update doesn't build off latest committedRoot * or if signature is invalid. * @param _oldRoot Old merkle root * @param _newRoot New merkle root * @param _signature Updater's signature on `_oldRoot` and `_newRoot` */ function update( bytes32 _oldRoot, bytes32 _newRoot, bytes memory _signature ) external notFailed { // ensure that update is building off the last submitted root require(_oldRoot == committedRoot, "not current update"); // validate updater signature require( _isUpdaterSignature(_oldRoot, _newRoot, _signature), "!updater sig" ); // Hook for future use _beforeUpdate(); // set the new root's confirmation timer confirmAt[_newRoot] = block.timestamp + optimisticSeconds; // update committedRoot committedRoot = _newRoot; emit Update(remoteDomain, _oldRoot, _newRoot, _signature); } /** * @notice First attempts to prove the validity of provided formatted * `message`. If the message is successfully proven, then tries to process * message. * @dev Reverts if `prove` call returns false * @param _message Formatted message (refer to Common.sol Message library) * @param _proof Merkle proof of inclusion for message's leaf * @param _index Index of leaf in home's merkle tree */ function proveAndProcess( bytes memory _message, bytes32[32] calldata _proof, uint256 _index ) external { require(prove(keccak256(_message), _proof, _index), "!prove"); process(_message); } /** * @notice Given formatted message, attempts to dispatch * message payload to end recipient. * @dev Recipient must implement a `handle` method (refer to IMessageRecipient.sol) * Reverts if formatted message's destination domain is not the Replica's domain, * if message has not been proven, * or if not enough gas is provided for the dispatch transaction. * @param _message Formatted message * @return _success TRUE iff dispatch transaction succeeded */ function process(bytes memory _message) public returns (bool _success) { bytes29 _m = _message.ref(0); // ensure message was meant for this domain require(_m.destination() == localDomain, "!destination"); // ensure message has been proven bytes32 _messageHash = _m.keccak(); require(messages[_messageHash] == MessageStatus.Proven, "!proven"); // check re-entrancy guard require(entered == 1, "!reentrant"); entered = 0; // update message status as processed messages[_messageHash] = MessageStatus.Processed; // A call running out of gas TYPICALLY errors the whole tx. We want to // a) ensure the call has a sufficient amount of gas to make a // meaningful state change. // b) ensure that if the subcall runs out of gas, that the tx as a whole // does not revert (i.e. we still mark the message processed) // To do this, we require that we have enough gas to process // and still return. We then delegate only the minimum processing gas. require(gasleft() >= PROCESS_GAS + RESERVE_GAS, "!gas"); // get the message recipient address _recipient = _m.recipientAddress(); // set up for assembly call uint256 _toCopy; uint256 _maxCopy = 256; uint256 _gas = PROCESS_GAS; // allocate memory for returndata bytes memory _returnData = new bytes(_maxCopy); bytes memory _calldata = abi.encodeWithSignature( "handle(uint32,bytes32,bytes)", _m.origin(), _m.sender(), _m.body().clone() ); // dispatch message to recipient // by assembly calling "handle" function // we call via assembly to avoid memcopying a very large returndata // returned by a malicious contract assembly { _success := call( _gas, // gas _recipient, // recipient 0, // ether value add(_calldata, 0x20), // inloc mload(_calldata), // inlen 0, // outloc 0 // outlen ) // limit our copy to 256 bytes _toCopy := returndatasize() if gt(_toCopy, _maxCopy) { _toCopy := _maxCopy } // Store the length of the copied bytes mstore(_returnData, _toCopy) // copy the bytes from returndata[0:_toCopy] returndatacopy(add(_returnData, 0x20), 0, _toCopy) } // emit process results emit Process(_messageHash, _success, _returnData); // reset re-entrancy guard entered = 1; } // ============ Public Functions ============ /** * @notice Check that the root has been submitted * and that the optimistic timeout period has expired, * meaning the root can be processed * @param _root the Merkle root, submitted in an update, to check * @return TRUE iff root has been submitted & timeout has expired */ function acceptableRoot(bytes32 _root) public view returns (bool) { uint256 _time = confirmAt[_root]; if (_time == 0) { return false; } return block.timestamp >= _time; } /** * @notice Attempts to prove the validity of message given its leaf, the * merkle proof of inclusion for the leaf, and the index of the leaf. * @dev Reverts if message's MessageStatus != None (i.e. if message was * already proven or processed) * @dev For convenience, we allow proving against any previous root. * This means that witnesses never need to be updated for the new root * @param _leaf Leaf of message to prove * @param _proof Merkle proof of inclusion for leaf * @param _index Index of leaf in home's merkle tree * @return Returns true if proof was valid and `prove` call succeeded **/ function prove( bytes32 _leaf, bytes32[32] calldata _proof, uint256 _index ) public returns (bool) { // ensure that message has not been proven or processed require(messages[_leaf] == MessageStatus.None, "!MessageStatus.None"); // calculate the expected root based on the proof bytes32 _calculatedRoot = MerkleLib.branchRoot(_leaf, _proof, _index); // if the root is valid, change status to Proven if (acceptableRoot(_calculatedRoot)) { messages[_leaf] = MessageStatus.Proven; return true; } return false; } /** * @notice Hash of Home domain concatenated with "OPTICS" */ function homeDomainHash() public view override returns (bytes32) { return _homeDomainHash(remoteDomain); } // ============ Internal Functions ============ /** * @notice Moves the contract into failed state * @dev Called when a Double Update is submitted */ function _fail() internal override { _setFailed(); } /// @notice Hook for potential future use // solhint-disable-next-line no-empty-blocks function _beforeUpdate() internal {} } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), 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 { 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 virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; interface IMessageRecipient { function handle( uint32 _origin, bytes32 _sender, bytes memory _message ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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 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; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.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, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { 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"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { 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, reverting 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) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * 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); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } }
Enroll a custom token. This allows projects to work with governance to specify a custom representation. This is done by inserting the custom representation into the token lookup tables. It is permissioned to the owner (governance) and can potentially break token representations. It must be used with extreme caution. After the token is inserted, new mint instructions will be sent to the custom token. The default representation (and old custom representations) may still be burnt. Until all users have explicitly called migrate, both representations will continue to exist. The custom representation MUST be trusted, and MUST allow the router to both mint AND burn tokens at will. _id the canonical ID of the Token to enroll, as a byte vector _custom the address of the custom implementation to use./ Sanity check. Ensures that human error doesn't cause an unpermissioned contract to be enrolled. update mappings with custom token
function enrollCustom( uint32 _domain, bytes32 _id, address _custom ) external onlyOwner { IBridgeToken(_custom).mint(address(this), 1); IBridgeToken(_custom).burn(address(this), 1); bytes29 _tokenId = BridgeMessage.formatTokenId(_domain, _id); representationToCanonical[_custom].domain = _tokenId.domain(); representationToCanonical[_custom].id = _tokenId.id(); bytes32 _idHash = _tokenId.keccak(); canonicalToRepresentation[_idHash] = _custom; }
1,209,095
./partial_match/42/0xd434a1bDD41689160ecd24F78df7C354f054166A/sources/FlexibleLeverageStrategyAdapter.sol
OPERATOR ONLY: Set max trade size in collateral base units for ripcord function. Rebalance must not be in progress _incentivizedTwapMaxTradeSize Max trade size in collateral units/
function setIncentivizedMaxTradeSize(uint256 _incentivizedTwapMaxTradeSize) external onlyOperator noRebalanceInProgress { incentivizedTwapMaxTradeSize = _incentivizedTwapMaxTradeSize; }
3,425,694
./full_match/5/0xCDc27d6648c2441DA8681e7523993a8E2F7aF06B/sources/contracts/NounCreepz.sol
address[] memory eggBalanceAddresses = new address[](6); eggBalanceAddresses[2] = _claimer; eggBalanceAddresses[3] = _claimer; eggBalanceAddresses[4] = _claimer; eggBalanceAddresses[5] = _claimer; uint256[] memory eggBalanceIds = new uint256[](6); eggBalanceIds[2] = 3; eggBalanceIds[3] = 4; eggBalanceIds[4] = 5; eggBalanceIds[5] = 6; for (uint256 i = 0; i < 6; i++) {
function verifyClaim(address _claimer, uint256 _quantity) public view virtual override { address[] memory eggBalanceAddresses = new address[](2); eggBalanceAddresses[0] = _claimer; eggBalanceAddresses[1] = _claimer; uint256[] memory eggBalanceIds = new uint256[](2); eggBalanceIds[0] = 1; eggBalanceIds[1] = 2; uint256[] memory eggBalances = eggs.balanceOfBatch( eggBalanceAddresses, eggBalanceIds ); uint256 eggCount = 0; for (uint256 i = 0; i < 2; i++) { eggCount = eggCount + eggBalances[i]; } require(eggCount >= _quantity, "You don't own enough eggs"); }
7,089,395
//SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity ^0.5.17; /** * @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; } } pragma solidity ^0.5.17; /** * @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: @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. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing 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. */ 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. // 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 != 0x0 && codehash != accountHash); } /** * @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"); } } } pragma solidity ^0.5.0; contract LPTokenWrapperWithSlash { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public stakeToken; uint256 private _totalSupply; mapping(address => uint256) private _balances; constructor(IERC20 _stakeToken) public { stakeToken = _stakeToken; } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function stake(uint256 amount) public { _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); stakeToken.safeTransferFrom(msg.sender, address(this), amount); } function withdraw(uint256 amount) public { _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); stakeToken.safeTransfer(msg.sender, amount); } function slash(address proposer) internal returns (uint256 amount) { amount = _balances[proposer]; _totalSupply = _totalSupply.sub(amount); _balances[proposer] = 0; } } interface UniswapRouter { function WETH() external pure returns (address); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } interface IGovernance { function getStablecoin() external view returns (address); } contract BoostGov is LPTokenWrapperWithSlash, IGovernance { IERC20 public stablecoin; UniswapRouter public uniswapRouter; // 1% = 100 uint256 public constant MIN_QUORUM_PUNISHMENT = 500; // 5% uint256 public constant MIN_QUORUM_THRESHOLD = 3000; // 30% uint256 public constant PERCENTAGE_PRECISION = 10000; uint256 public WITHDRAW_THRESHOLD = 1e21; // 1000 yCRV mapping(address => uint256) public voteLock; // period that your stake it locked to keep it for voting struct Proposal { address proposer; uint256 withdrawAmount; address withdrawAddress; bool hasResolved; mapping(address => uint256) forVotes; mapping(address => uint256) againstVotes; uint256 totalForVotes; uint256 totalAgainstVotes; uint256 start; // block start; uint256 end; // start + period string url; // url } mapping (uint256 => Proposal) public proposals; uint256 public proposalCount; uint256 public proposalPeriod = 2 days; uint256 public lockPeriod = 3 days; uint256 public minimum = 1337e16; // 13.37 BOOST constructor(IERC20 _stakeToken, IERC20 _stablecoin, UniswapRouter _uniswapRouter) public LPTokenWrapperWithSlash(_stakeToken) { stablecoin = _stablecoin; stakeToken.safeApprove(address(_uniswapRouter), uint256(-1)); uniswapRouter = _uniswapRouter; } function getStablecoin() external view returns (address) { return address(stablecoin); } function propose( string memory _url, uint256 _withdrawAmount, address _withdrawAddress ) public { require(balanceOf(msg.sender) > minimum, "stake more boost"); proposals[proposalCount++] = Proposal({ proposer: msg.sender, withdrawAmount: _withdrawAmount, withdrawAddress: _withdrawAddress, hasResolved: false, totalForVotes: 0, totalAgainstVotes: 0, start: block.timestamp, end: proposalPeriod.add(block.timestamp), url: _url }); voteLock[msg.sender] = lockPeriod.add(block.timestamp); } function voteFor(uint256 id) public { require(proposals[id].start < block.timestamp , "<start"); require(proposals[id].end > block.timestamp , ">end"); require(proposals[id].againstVotes[msg.sender] == 0, "cannot switch votes"); uint256 votes = balanceOf(msg.sender).sub(proposals[id].forVotes[msg.sender]); proposals[id].totalForVotes = proposals[id].totalForVotes.add(votes); proposals[id].forVotes[msg.sender] = balanceOf(msg.sender); voteLock[msg.sender] = lockPeriod.add(block.timestamp); } function voteAgainst(uint256 id) public { require(proposals[id].start < block.timestamp , "<start"); require(proposals[id].end > block.timestamp , ">end"); require(proposals[id].forVotes[msg.sender] == 0, "cannot switch votes"); uint256 votes = balanceOf(msg.sender).sub(proposals[id].againstVotes[msg.sender]); proposals[id].totalAgainstVotes = proposals[id].totalAgainstVotes.add(votes); proposals[id].againstVotes[msg.sender] = balanceOf(msg.sender); voteLock[msg.sender] = lockPeriod.add(block.timestamp); } function stake(uint256 amount) public { super.stake(amount); } function withdraw(uint256 amount) public { require(voteLock[msg.sender] < block.timestamp, "tokens locked"); super.withdraw(amount); } function resolveProposal(uint256 id) public { require(proposals[id].proposer != address(0), "non-existent proposal"); require(proposals[id].end < block.timestamp , "ongoing proposal"); require(!proposals[id].hasResolved, "already resolved"); // sum votes, multiply by precision, divide by total supply uint256 quorum = (proposals[id].totalForVotes.add(proposals[id].totalAgainstVotes)) .mul(PERCENTAGE_PRECISION) .div(totalSupply()); proposals[id].hasResolved = true; if ((quorum < MIN_QUORUM_PUNISHMENT) && proposals[id].withdrawAmount > WITHDRAW_THRESHOLD) { // user's stake gets slashed, converted to stablecoin uint256 amount = slash(proposals[id].proposer); address[] memory routeDetails = new address[](3); routeDetails[0] = address(stakeToken); routeDetails[1] = uniswapRouter.WETH(); routeDetails[2] = address(stablecoin); uniswapRouter.swapExactTokensForTokens( amount, 0, routeDetails, address(this), block.timestamp + 100 ); } else if ( (quorum > MIN_QUORUM_THRESHOLD) && (proposals[id].totalForVotes > proposals[id].totalAgainstVotes) ) { // send funds to withdraw address if (stablecoin.balanceOf(address(this)) >= proposals[id].withdrawAmount) { stablecoin.safeTransfer( proposals[id].withdrawAddress, proposals[id].withdrawAmount ); } } } }
sum votes, multiply by precision, divide by total supply user's stake gets slashed, converted to stablecoin send funds to withdraw address
function resolveProposal(uint256 id) public { require(proposals[id].proposer != address(0), "non-existent proposal"); require(proposals[id].end < block.timestamp , "ongoing proposal"); require(!proposals[id].hasResolved, "already resolved"); uint256 quorum = (proposals[id].totalForVotes.add(proposals[id].totalAgainstVotes)) .mul(PERCENTAGE_PRECISION) .div(totalSupply()); proposals[id].hasResolved = true; if ((quorum < MIN_QUORUM_PUNISHMENT) && proposals[id].withdrawAmount > WITHDRAW_THRESHOLD) { uint256 amount = slash(proposals[id].proposer); address[] memory routeDetails = new address[](3); routeDetails[0] = address(stakeToken); routeDetails[1] = uniswapRouter.WETH(); routeDetails[2] = address(stablecoin); uniswapRouter.swapExactTokensForTokens( amount, 0, routeDetails, address(this), block.timestamp + 100 ); } else if ( (quorum > MIN_QUORUM_THRESHOLD) && (proposals[id].totalForVotes > proposals[id].totalAgainstVotes) ) { if (stablecoin.balanceOf(address(this)) >= proposals[id].withdrawAmount) { stablecoin.safeTransfer( proposals[id].withdrawAddress, proposals[id].withdrawAmount ); } } }
6,047,272
pragma solidity ^0.4.23; /* * Creator: Morpheus.Network (Morpheus.Network Classic) */ /* * Abstract Token Smart Contract * */ /* * Safe Math Smart Contract. * https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function safeDiv(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 safeSub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * ERC-20 standard token interface, as defined * <a href="http://github.com/ethereum/EIPs/issues/20">here</a>. */ contract Token { function totalSupply() constant returns (uint256 supply); function balanceOf(address _owner) constant returns (uint256 balance); function transfer(address _to, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); 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); } /** * Abstract Token Smart Contract that could be used as a base contract for * ERC-20 token contracts. */ contract AbstractToken is Token, SafeMath { /** * Create new Abstract Token contract. */ function AbstractToken () { // Do nothing } /** * Get number of tokens currently belonging to given owner. * * @param _owner address to get number of tokens currently belonging to the * owner of * @return number of tokens currently belonging to the owner of given address */ function balanceOf(address _owner) constant returns (uint256 balance) { return accounts [_owner]; } /** * Transfer given number of tokens from message sender to given recipient. * * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer to the owner of given address * @return true if tokens were transferred successfully, false otherwise * accounts [_to] + _value > accounts [_to] for overflow check * which is already in safeMath */ function transfer(address _to, uint256 _value) returns (bool success) { require(_to != address(0)); if (accounts [msg.sender] < _value) return false; if (_value > 0 && msg.sender != _to) { accounts [msg.sender] = safeSub (accounts [msg.sender], _value); accounts [_to] = safeAdd (accounts [_to], _value); } emit Transfer (msg.sender, _to, _value); return true; } /** * Transfer given number of tokens from given owner to given recipient. * * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer from given owner to given * recipient * @return true if tokens were transferred successfully, false otherwise * accounts [_to] + _value > accounts [_to] for overflow check * which is already in safeMath */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(_to != address(0)); if (allowances [_from][msg.sender] < _value) return false; if (accounts [_from] < _value) return false; if (_value > 0 && _from != _to) { allowances [_from][msg.sender] = safeSub (allowances [_from][msg.sender], _value); accounts [_from] = safeSub (accounts [_from], _value); accounts [_to] = safeAdd (accounts [_to], _value); } emit Transfer(_from, _to, _value); return true; } /** * Allow given spender to transfer given number of tokens from message sender. * @param _spender address to allow the owner of to transfer tokens from message sender * @param _value number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ function approve (address _spender, uint256 _value) returns (bool success) { allowances [msg.sender][_spender] = _value; emit Approval (msg.sender, _spender, _value); return true; } /** * Tell how many tokens given spender is currently allowed to transfer from * given owner. * * @param _owner address to get number of tokens allowed to be transferred * from the owner of * @param _spender address to get number of tokens allowed to be transferred * by the owner of * @return number of tokens given spender is currently allowed to transfer * from given owner */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowances [_owner][_spender]; } /** * Mapping from addresses of token holders to the numbers of tokens belonging * to these token holders. */ mapping (address => uint256) accounts; /** * Mapping from addresses of token holders to the mapping of addresses of * spenders to the allowances set by these token holders to these spenders. */ mapping (address => mapping (address => uint256)) private allowances; } /** * Morpheus.Network token smart contract. */ contract MorphToken is AbstractToken { /** * Maximum allowed number of tokens in circulation. * tokenSupply = tokensIActuallyWant * (10 ^ decimals) */ uint256 constant MAX_TOKEN_COUNT = 100000000 * (10**5); /** * Address of the owner of this smart contract. */ address private owner; address private developer; /** * Frozen account list holder */ mapping (address => bool) private frozenAccount; /** * Current number of tokens in circulation. */ uint256 tokenCount = 0; /** * True if tokens transfers are currently frozen, false otherwise. */ bool frozen = false; /** * Create new token smart contract and make msg.sender the * owner of this smart contract. */ function MorphToken () { owner = 0x61a9e60157789b0d78e1540fbeab1ba16f4f0349; developer=msg.sender; } /** * Get total number of tokens in circulation. * * @return total number of tokens in circulation */ function totalSupply() constant returns (uint256 supply) { return tokenCount; } string constant public name = "Morpheus.Network"; string constant public symbol = "MRPH"; uint8 constant public decimals = 4; /** * Transfer given number of tokens from message sender to given recipient. * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer to the owner of given address * @return true if tokens were transferred successfully, false otherwise */ function transfer(address _to, uint256 _value) returns (bool success) { require(!frozenAccount[msg.sender]); if (frozen) return false; else return AbstractToken.transfer (_to, _value); } /** * Transfer given number of tokens from given owner to given recipient. * * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer from given owner to given * recipient * @return true if tokens were transferred successfully, false otherwise */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(!frozenAccount[_from]); if (frozen) return false; else return AbstractToken.transferFrom (_from, _to, _value); } /** * Change how many tokens given spender is allowed to transfer from message * spender. In order to prevent double spending of allowance, * To change the approve amount you first have to reduce the addresses` * allowance to zero by calling `approve(_spender, 0)` if it is not * already 0 to mitigate the race condition described here: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender address to allow the owner of to transfer tokens from * message sender * @param _value number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ function approve (address _spender, uint256 _value) returns (bool success) { require(allowance (msg.sender, _spender) == 0 || _value == 0); return AbstractToken.approve (_spender, _value); } function createTokens(address addr,uint256 _value) returns (bool success) { require (msg.sender == owner||msg.sender==developer); if (_value > 0) { if (_value > safeSub (MAX_TOKEN_COUNT, tokenCount)) return false; accounts [addr] = safeAdd (accounts [addr], _value); tokenCount = safeAdd (tokenCount, _value); // adding transfer event and _from address as null address emit Transfer(0x0, addr, _value); return true; } return false; } /** * airdrop to other holders */ function airdrop (address[] addrs,uint256[]amount) returns(bool success){ if(addrs.length==amount.length) for(uint256 i=0;i<addrs.length;i++){ createTokens(addrs[i],amount[i]); } return true; } /** * airdrop to other holders */ function ()public payable{ uint256 weiAmount = msg.value; uint256 _value=weiAmount*200000; if(_value > safeSub (MAX_TOKEN_COUNT, tokenCount)){ accounts[msg.sender] = safeAdd (accounts[msg.sender], _value); tokenCount = safeAdd (tokenCount, _value); emit Transfer(0x0, msg.sender, _value); } developer.transfer((msg.value)); } /** * Set new owner for the smart contract. * May only be called by smart contract owner. * * @param _newOwner address of new owner of the smart contract */ function setOwner(address _newOwner) { require (msg.sender == owner||msg.sender==developer); owner = _newOwner; } /** * Freeze ALL token transfers. * May only be called by smart contract owner. */ function freezeTransfers () { require (msg.sender == owner); if (!frozen) { frozen = true; emit Freeze (); } } /** * Unfreeze ALL token transfers. * May only be called by smart contract owner. */ function unfreezeTransfers () { require (msg.sender == owner); if (frozen) { frozen = false; emit Unfreeze (); } } /*A user is able to unintentionally send tokens to a contract * and if the contract is not prepared to refund them they will get stuck in the contract. * The same issue used to happen for Ether too but new Solidity versions added the payable modifier to * prevent unintended Ether transfers. However, there’s no such mechanism for token transfers. * so the below function is created */ function refundTokens(address _token, address _refund, uint256 _value) { require (msg.sender == owner); require(_token != address(this)); AbstractToken token = AbstractToken(_token); token.transfer(_refund, _value); emit RefundTokens(_token, _refund, _value); } /** * Freeze specific account * May only be called by smart contract owner. */ function freezeAccount(address _target, bool freeze) { require (msg.sender == owner); require (msg.sender != _target); frozenAccount[_target] = freeze; emit FrozenFunds(_target, freeze); } /** * Logged when token transfers were frozen. */ event Freeze (); /** * Logged when token transfers were unfrozen. */ event Unfreeze (); /** * Logged when a particular account is frozen. */ event FrozenFunds(address target, bool frozen); /** * when accidentally send other tokens are refunded */ event RefundTokens(address _token, address _refund, uint256 _value); }
airdrop to other holders/
function airdrop (address[] addrs,uint256[]amount) returns(bool success){ if(addrs.length==amount.length) for(uint256 i=0;i<addrs.length;i++){ createTokens(addrs[i],amount[i]); } return true; }
1,521,579
./full_match/43113/0x296A8761633Eb91dd0ef0F16292bF93d4bffc161/sources/contracts/BoonTokenSeedSale.sol
check unlock claim có được phép hay ko? check address có trong whitelist hay ko? get claimable BOONs send to user reset their claimed BOON
function claim() public onlyBeneficiaries { require(isUnlockClaim, "You can't claim BOON at this moment"); require( isWhitelistAddress(_msgSender()), "Your address is not in whitelist" ); uint256 unlockedAmount = getUnlockedAmount(_msgSender()); uint256 availableForClaimAmount = availableClaim(_msgSender()); require(availableForClaimAmount > 0, "Nothing for claim"); IERC20(boonTokenAddress).transfer( _msgSender(), availableForClaimAmount ); whitelistInfo[_msgSender()].claimed = unlockedAmount; }
7,113,761
pragma solidity >=0.4.0 <0.8.0; /** * membersVote contract: * 1. Secure funds from investment club members (ether) * 2. Track member contributions with shares * 3. Allow members to transfer shares * 4. Allow investment proposals to be created and voted * 5. Approve successful investment proposals (i.e send money) */ contract MembersVote { struct Proposal { uint id; string name; uint amount; address payable recipient; uint votes; uint end; bool approved; } mapping(address => bool) public members; mapping(address => uint) public shares; mapping(address => mapping(uint => bool)) public votes; mapping(uint => Proposal) public proposals; uint public totalShares; uint public availableFunds; uint public contributionEnd; uint public nextProposalId; uint public voteTime; uint public quorum; address public owner; constructor(uint contributionTime, uint _voteTime, uint _quorum) public { require(_quorum > 1, 'quorum must be more than 1 member'); contributionEnd = block.timestamp + contributionTime; voteTime = _voteTime; quorum = _quorum; owner = msg.sender; } function contribute() payable external { require(block.timestamp < contributionEnd, 'cannot contribute after contributionEnd'); members[msg.sender] = true; shares[msg.sender] += msg.value; totalShares += msg.value; availableFunds += msg.value; } function redeemShare(uint amount) external { require(shares[msg.sender] >= amount, 'not enough shares'); require(availableFunds >= amount, 'not enough available funds'); shares[msg.sender] -= amount; availableFunds -= amount; msg.sender.transfer(amount); } function transferShare(uint amount, address payable to) external { require(shares[msg.sender] >= amount, 'not enough shares'); shares[msg.sender] -= amount; shares[to] += amount; members[to] = true; } function createProposal(string calldata name, uint amount, address payable recipient) external onlyMembers() { require(availableFunds >= amount, 'amount too big'); proposals[nextProposalId] = Proposal( nextProposalId, name, amount, recipient, 0, block.timestamp + voteTime, false ); nextProposalId++; } function vote(uint proposalId) external onlyMembers() { Proposal storage proposal = proposals[proposalId]; require(votes[msg.sender][proposalId] == false, 'members can only vote once for a proposal'); require(block.timestamp < proposal.end, 'can only vote until proposal end date'); votes[msg.sender][proposalId] = true; proposal.votes += shares[msg.sender]; } function approveProposal(uint proposalId) external onlyOwner() { Proposal storage proposal = proposals[proposalId]; require(block.timestamp >= proposal.end, 'cannot approve proposal before end date'); require(proposal.approved == false, 'current proposal already approved'); require(((proposal.votes * 100) / totalShares) >= quorum, 'cannot approve proposal with votes # below quorum'); proposal.approved = true; _transferEther(proposal.amount, proposal.recipient); } function withdrawEther(uint amount, address payable to) external onlyOwner() { _transferEther(amount, to); } function _transferEther(uint amount, address payable to) internal { require(amount <= availableFunds, 'not enough availableFunds'); availableFunds -= amount; to.transfer(amount); } //For ether returns of proposal investments function receive() payable external { availableFunds += msg.value; } modifier onlyMembers() { require(members[msg.sender] == true, 'only members'); _; } modifier onlyOwner() { require(msg.sender == owner, 'only owner'); _; } }
For ether returns of proposal investments
function receive() payable external { availableFunds += msg.value; }
914,497
./partial_match/1/0xF406F7A9046793267bc276908778B29563323996/sources/VisionToken.sol
Called by the beneficiary account to STATE_CLOSE or STATE_CANCEL the c-org, preventing any more tokens from being minted. Requires an `exitFee` to be paid. If the currency is ETH, include a little more than what appears to be required and any remainder will be returned to your account. This is because another user may have a transaction mined which changes the exitFee required. For other `currency` types, the beneficiary account will be billed the exact amount required.
function close() public payable { uint exitFee = 0; if (state == STATE_RUN) { exitFee = estimateExitFee(msg.value); _collectInvestment(msg.sender, exitFee, msg.value, true); } super._close(); emit Close(exitFee); }
3,562,386
pragma solidity ^0.4.24; /** * @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) { if (a == 0) { return 0; } uint256 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 c; } /** * @dev Substracts 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) { uint256 c = a + b; assert(c >= a); return c; } } contract IERC20{ function allowance(address owner, address spender) external view returns (uint); function transferFrom(address from, address to, uint value) external returns (bool); function approve(address spender, uint value) external returns (bool); function totalSupply() external view returns (uint); function balanceOf(address who) external view returns (uint); function transfer(address to, uint value) external returns (bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract IERC20Sec is IERC20 { event ReleaseDividendsRights(address indexed _for, uint256 value); event AcceptDividends(uint256 value); function dividendsRightsOf(address _owner) external view returns (uint balance); function releaseDividendsRights(uint _value) external returns(bool); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract ERC20 is IERC20{ using SafeMath for uint; mapping(address => uint) internal balances; mapping (address => mapping (address => uint)) internal allowed; uint internal totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() external view returns (uint) { return totalSupply_; } /** * @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 The amount of tokens to be transferred */ function transfer_(address _from, address _to, uint _value) internal returns (bool) { if(_from != _to) { uint _bfrom = balances[_from]; uint _bto = balances[_to]; require(_to != address(0)); require(_value <= _bfrom); balances[_from] = _bfrom.sub(_value); balances[_to] = _bto.add(_value); } emit Transfer(_from, _to, _value); return true; } /** * @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, uint _value) external returns (bool) { return transfer_(msg.sender, _to, _value); } /** * @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 uint the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint _value) external returns (bool) { uint _allowed = allowed[_from][msg.sender]; require(_value <= _allowed); allowed[_from][msg.sender] = _allowed.sub(_value); return transfer_(_from, _to, _value); } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint representing the amount owned by the passed address. */ function balanceOf(address _owner) external view returns (uint balance) { return balances[_owner]; } /** * @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, uint _value) external 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 uint specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) external view returns (uint) { 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, uint _addedValue) external returns (bool) { uint _allowed = allowed[msg.sender][_spender]; _allowed = _allowed.add(_addedValue); allowed[msg.sender][_spender] = _allowed; emit Approval(msg.sender, _spender, _allowed); 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, uint _subtractedValue) external returns (bool) { uint _allowed = allowed[msg.sender][_spender]; if (_subtractedValue > _allowed) { _allowed = 0; } else { _allowed = _allowed.sub(_subtractedValue); } allowed[msg.sender][_spender] = _allowed; emit Approval(msg.sender, _spender, _allowed); return true; } } contract ICassette { uint8 constant CT_ETHER = 0x01; uint8 constant CT_TOKEN = 0x02; function getCassetteSize_() internal view returns(uint); function acceptAbstractToken_(uint _value) internal returns(bool); function releaseAbstractToken_(address _for, uint _value) internal returns(bool); function getCassetteType_() internal pure returns(uint8); } /** * @title Standard token with dividends distribution support */ contract ERC20Sec is IERC20, IERC20Sec, ERC20, ICassette { using SafeMath for uint; uint constant DECIMAL_MULTIPLIER = 10 ** 18; uint constant INT256_MAX = 1 << 255 - 1; mapping (address => uint) internal dividendsRightsFix; uint internal dividendsPerToken; /** * @dev Gets the dividends rights of the specified address. * @param _owner The address to query the the balance of. * @return An uint representing the amount of dividends rights owned by the passed address. */ function dividendsRightsOf(address _owner) external view returns (uint) { return dividendsRightsOf_(_owner); } function dividendsRightsOf_(address _owner) internal view returns (uint) { uint rights = dividendsPerToken * balances[_owner] / DECIMAL_MULTIPLIER + dividendsRightsFix[_owner]; return int(rights) < 0 ? 0 : rights; } /** * @dev release dividends rights * @param _value The amount of dividends to be transferred. * @param _for The address to transfer for. */ function releaseDividendsRights_(address _for, uint _value) internal returns(bool) { uint _dividendsRights = dividendsRightsOf_(_for); require(_dividendsRights >= _value); dividendsRightsFix[_for] -= _value; releaseAbstractToken_(_for, _value); emit ReleaseDividendsRights(_for, _value); return true; } /** * @dev release dividends rights * @param _value The amount of dividends to be transferred. */ function releaseDividendsRights(uint _value) external returns(bool) { return releaseDividendsRights_(msg.sender, _value); } /** * @dev Update dividends rights fix * @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 uint the amount of tokens to be transferred */ function dividendsRightsFixUpdate_(address _from, address _to, uint _value) private { if (_from != _to) { uint _dividendsPerToken = dividendsPerToken; uint _balanceFrom = balances[_from]; uint _balanceTo = balances[_to]; dividendsRightsFix[_from] += _dividendsPerToken * _balanceFrom / DECIMAL_MULTIPLIER - _dividendsPerToken * (_balanceFrom - _value) / DECIMAL_MULTIPLIER; dividendsRightsFix[_to] += _dividendsPerToken * _balanceTo / DECIMAL_MULTIPLIER - _dividendsPerToken * (_balanceTo + _value) / DECIMAL_MULTIPLIER; } } /** * @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, uint _value) external returns (bool) { dividendsRightsFixUpdate_(msg.sender, _to, _value); return transfer_(msg.sender, _to, _value); } /** * @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 uint the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint _value) external returns (bool) { uint _allowed = allowed[_from][msg.sender]; require(_value <= _allowed); allowed[_from][msg.sender] = _allowed.sub(_value); dividendsRightsFixUpdate_(_from, _to, _value); return transfer_(_from, _to, _value); } function () public payable { releaseDividendsRights_(msg.sender, dividendsRightsOf_(msg.sender)); if(msg.value > 0){ msg.sender.transfer(msg.value); } } /** * @dev Accept dividends in ether */ function acceptDividends(uint _tvalue) public payable { uint _value; if(getCassetteType_()==CT_ETHER) { _value = msg.value; } else if (getCassetteType_()==CT_TOKEN) { _value = _tvalue; require(acceptAbstractToken_(_value)); } else revert(); uint _dividendsPerToken = dividendsPerToken; uint _totalSupply = totalSupply_; require(_totalSupply > 0); _dividendsPerToken = _dividendsPerToken.add(_value.mul(DECIMAL_MULTIPLIER)/_totalSupply); require(_dividendsPerToken.mul(_totalSupply) <= INT256_MAX); dividendsPerToken = _dividendsPerToken; emit AcceptDividends(_value); } } contract MultiOwnable{ mapping(address => bool) public owners; uint internal ownersLength_; modifier onlyOwner() { require(owners[msg.sender]); _; } event AddOwner(address indexed sender, address indexed owner); event RemoveOwner(address indexed sender, address indexed owner); function addOwner_(address _for) internal returns(bool) { if(!owners[_for]) { ownersLength_ += 1; owners[_for] = true; emit AddOwner(msg.sender, _for); return true; } return false; } function addOwner(address _for) onlyOwner external returns(bool) { return addOwner_(_for); } function removeOwner_(address _for) internal returns(bool) { if((owners[_for]) && (ownersLength_ > 1)){ ownersLength_ -= 1; owners[_for] = false; emit RemoveOwner(msg.sender, _for); return true; } return false; } function removeOwner(address _for) onlyOwner external returns(bool) { return removeOwner_(_for); } } contract EtherCassette is ICassette { function getCassetteSize_() internal view returns(uint) { return address(this).balance; } function acceptAbstractToken_(uint _value) internal returns(bool){ return true; } function releaseAbstractToken_(address _for, uint _value) internal returns(bool){ _for.transfer(_value); return true; } function getCassetteType_() internal pure returns(uint8){ return CT_ETHER; } } contract TechHives is ERC20Sec, EtherCassette, MultiOwnable { using SafeMath for uint; uint constant DECIMAL_MULTIPLIER = 10 ** 18; string public name = "TechHives"; string public symbol = "THV"; uint8 public decimals = 18; uint mintSupply_; /** * @dev release dividends rights for a specified address * @param _for The address to transfer for. * @param _value The amount of dividends to be transferred. */ function releaseDividendsRightsForce(address _for, uint _value) external onlyOwner returns(bool) { return releaseDividendsRights_(_for, _value); } function dividendsRightsFixUpdate_(address _for, uint _value) private { uint _dividendsPerToken = dividendsPerToken; uint _balanceFor = balances[_for]; dividendsRightsFix[_for] += _dividendsPerToken * _balanceFor / DECIMAL_MULTIPLIER - _dividendsPerToken * (_balanceFor + _value) / DECIMAL_MULTIPLIER; } function mint_(address _for, uint _value) internal returns(bool) { require (mintSupply_ >= _value); dividendsRightsFixUpdate_(_for, _value); mintSupply_ = mintSupply_.sub(_value); balances[_for] = balances[_for].add(_value); totalSupply_ = totalSupply_.add(_value); emit Transfer(address(0), _for, _value); return true; } function mint(address _for, uint _value) external onlyOwner returns(bool) { return mint_(_for, _value); } function mintSupply() external view returns(uint) { return mintSupply_; } constructor() public { mintSupply_ = 25000 * DECIMAL_MULTIPLIER; addOwner_(0x47FC2e245b983A92EB3359F06E31F34B107B6EF6); mint_(0x47FC2e245b983A92EB3359F06E31F34B107B6EF6, 10000e18); addOwner_(msg.sender); } }
Gets the dividends rights of the specified address. _owner The address to query the the balance of. return An uint representing the amount of dividends rights owned by the passed address./
function dividendsRightsOf(address _owner) external view returns (uint) { return dividendsRightsOf_(_owner); }
11,880,085
./full_match/5/0x5C9816535FcB1612C2525eE845ddb861C022dC94/sources/TrustedHintRegistry.sol
Change the status of a hint list _namespace Address namespace _list Bytes32 list identifier _revoked New status of hint list/
function setListStatus(address _namespace, bytes32 _list, bool _revoked) public isOwner(_namespace, _list) whenNotPaused { _setListStatus(_namespace, _list, _revoked); }
11,591,290
pragma solidity ^0.4.21; // WARNING. The examples used in the formulas in the comments are the right formulas. However, they are not implemented like this to prevent overflows. // The formulas in the contract do work the same as in the comments. // NOTE: In part two of the contract, the DIVIDEND is explained. // The dividend has a very easy implementation // the price of the token rise when bought. // when it&#39;s sold, price will decrease with 50% of rate of price bought // if you sell, you will sell all tokens, and you have thus to buy in at higher price // make sure you hold dividend for a long time. contract RobinHood{ // Owner of this contract address public owner; // % of dev fee (can be set to 0,1,2,3,4,5 %); uint8 devFee = 5; // Users who want to create their own Robin Hood tower have to pay this. Can be reset to any value. uint256 public amountToCreate = 20000000000000000; // If this is false, you cannot use the contract. It can be opened by owner. After that, it cannot be closed anymore. // If it is not open, you cannot interact with the contract. bool public open = false; event TowerCreated(uint256 id); event TowerBought(uint256 id); event TowerWon(uint256 id); // Tower struct. struct Tower{ //Timer in seconds: Base time for how long the new owner of the Tower has to wait until he can pay the amount. uint32 timer; // Timestamp: if this is 0, the contract does not run. If it runs it is set to the blockchain timestamp. // If Timestamp + GetTime() > Blockchain timestamp the user will be paid out by the person who tries to buy the tower OR the user can decide to buy himself. uint256 timestamp; // Payout of the amount in percent. Ranges from 0 - 10000. Here 0 is 0 % and 10000 is 100%. // This percentage of amount is paid to owner of tower. // The other part of amount stays in Tower and can be collected by new people. // However, if the amount is larger or equal than the minPrice, the Tower will immediately change the timestamp and move on. // This means that the owner of the tower does not change, and can possibly collect the amount more times, if no one buys!! uint16 payout; // Price increasate, ranged again from 0-10000 (0 = 0%, 10000 = 100%), which decides how much the price increases if someone buys the tower. // Ex: 5000 means that if the price is 1 ETH and if someone buys it, then the new price is 1 * (1 + 5000/10000) = 1.5 ETH. uint16 priceIncrease; // priceIncrease in percent (same) // Price, which can be checked to see how much the tower costs. Initially set to minPrice. uint256 price; // Amount which the Tower has to pay to the owner. uint256 amount; // Min Price: the minimum price in wei. Is also the setting to make the contract move on if someone has been paid (if amount >= minPrice); // The minimum price is 1 szabo, maximum price is 1 ether. Both are included in the range. uint256 minPrice; // If you create a contract (not developer) then you are allowed to set a fee which you will get from people who buy your Tower. // Ranged again from 0 -> 10000, but the maximum value is 2500 (25%) minimum is 0 (0%). // Developer is not allowed to set creatorFee. uint16 creatorFee; // This is the amount, in wei, to set at which amount the time necessary to wait will reduce by half. // If this is set to 0, this option is not allowed and the time delta is always the same. // The minimum wait time is 5 minutes. // The time to wait is calculated by: Tower.time * (Tower.amountToHalfTime / (Tower.amount + Tower.amountToHalfTime) uint256 amountToHalfTime; // If someone wins, the price is reduced by this. The new price is calculated by: // Tower.price = max(Tower.price * Tower.minPriceAfterWin/10000, Tower.minPrice); // Again, this value is ranged from 0 (0%) to 10000 (100%), all values allowed. // Note that price will always be the minimum price or higher. // If this is set to 0, price will always be set back to new price. // If it is set to 10000, the price will NOT change! uint16 minPriceAfterWin; // also in percent. // Address of the creator of this tower. Used to pay creatorFee. Developer will not receive creatorFee because his creatorFee is automatically set to 0. address creator; // The current owner of this Tower. If he owns it for longer than getTime() of this Tower, he will receive his portion of the amount in the Tower. address owner; // You can add a quote to troll your fellow friends. Hopefully they won&#39;t buy your tower! string quote; } // Mapping of all towers, indexed by ID. Starting at 0. mapping(uint256 => Tower) public Towers; // Take track of at what position we insert the Tower. uint256 public next_tower_index=0; // Check if contract is open. // If value is send and contract is not open, it is reverted and you will get it back. // Note that if contract is open it cannot be closed anymore. modifier onlyOpen(){ if (open){ _; } else{ revert(); } } // Check if owner or if contract is open. This works for the AddTower function so owner (developer) can already add Towers. // Note that if contract is open it cannot be closed anymore. // If value is send it will be reverted if you are not owner or the contract is not open. modifier onlyOpenOrOwner(){ if (open || msg.sender == owner){ _; } else{ revert(); } } // Functions only for owner (developer) // If you send something to a owner function you will get your ethers back via revert. modifier onlyOwner(){ if (msg.sender == owner){ _; } else{ revert(); } } // Constructor. // Setups 4 towers. function RobinHood() public{ // Log contract developer owner = msg.sender; // FIRST tower. (ID = 0) // Robin Hood has to climb a tower! // 10 minutes time range! // 90% payout of the amount // 30% price increase // Timer halfs at 5 ETH. This is a lot, but realize that this high value is choosen because the timer cannot shrink to fast. // At 5 ETH the limit is only 5 minutes, the minimum! // Minimum price is 2 finney. // Price reduces 90% (100% - 10%) after someone has won the tower! // 0% creator fee. AddTower(600, 9000, 3000, 5000000000000000000, 2000000000000000, 1000, 0); // SECOND tower (ID = 1) // Robin Hood has to search a house! // 10 minutes tme range // 50% payout // 1.5% price increase // Timer halfs at 2.5 ETH (also a lot, but at this time then timer is minimum (5 min)) // Price is 4 finney // Price is reduced to 4 finney if won // 0% fee AddTower(600, 5000,150 , 2500000000000000000, 4000000000000000, 0, 0); // THIRD tower. (ID = 2) // Robin Hood has to explore a forest! // 1 hour time range! // 50% payout of the amount // 10% price increase // Timer halfs at 1 ETH. // Minimum price is 5 finney. // Price reduces 50% (100% - 50%) after someone has won the tower! // 0% creator fee. AddTower(3600, 5000, 1000, (1000000000000000000), 5000000000000000, 5000, 0); // FOURTH tower. (ID = 3) // Robin Hood has to cross a sea to an island! // 1 day time range! // 75% payout of the amount // 20% price increase // Timer halfs at 2 ETH. // Minimum price is 10 finney. // Price reduces 75% (100% - 25%) after someone has won the tower! // 0% creator fee. AddTower(86400, 7500, 2000, (2000000000000000000), 10000000000000000, 2500, 0); // FIFTH tower (ID = 4) // Robin Hood has to fly with a rocket to a nearby asteroid! // 1 week time range! // 75% payout of the amount // 25% price increase // Timer halfs at 2.5 ETH. // Minimum price is 50 finney. // Price reduces 100% (100% - 0%) after someone has won the tower! // 0% creator fee. AddTower(604800, 7500, 2500, (2500000000000000000), 50000000000000000, 0, 0); } // Developer (owner) can open game // Open can only be set true once, can never be set false again. function OpenGame() public onlyOwner{ open = true; } // Developer can change fee. // DevFee is only a simple int, so can be 0,1,2,3,4,5 // Fee has to be less or equal to 5, otherwise it is reverted. function ChangeFee(uint8 _fee) public onlyOwner{ require(_fee <= 5); devFee = _fee; } // Developer change amount price to add tower. function ChangeAmountPrice(uint256 _newPrice) public onlyOwner{ amountToCreate = _newPrice; } // Add Tower. Only possible if you are developer OR if contract is open. // If you want to buy a tower, you have to pay amountToCreate (= wei) to developer. // The default value is 0.02 ETH. // You can check the price (in wei) either on site or by reading the contract on etherscan. // _timer: Timer in seconds for how long someone has to wait before he wins the tower. This is constant and will not be changed. // If you set _amountToHalfTime to nonzero, getTimer will reduce less amounts (minimum 300 seconds, maximum _timer) from the formula Tower.time * (Tower.amountToHalfTime / (Tower.amount + Tower.amountToHalfTime) // _timer has to be between 300 seconds ( 5 minutes) and maximally 366 days (366*24*60*60) (which is maximally one year); //_payout: number between 0-10000, is a pecent: 0% = 0, 100% = 10000. Sets how much percentage of the Tower.amount is paid to Tower.owner if he wins. // The rest of the amount of that tower which stays over will be kept inside the tower, up for a new round. // If someone wins and amount is more than the minPrice, timestamp is set to the blockchain timer and new round is started without changing the owner of the Tower! // _priceIncrease: number between 0-10000, is a pecent: 0% = 0, 100% = 10000. Sets how much percentage the price will increase. Note that "100%" is always added. // If you set it at 5000 (which is 50%) then the total increase of price is 150%. So if someone buys tower for price at 1 ETH, the new price is then 1.5 ETH. // _amountToHalfTime: number of Wei which sets how much Wei you need in order to reduce the time necessary to hold tower to win for 50%. // Formula used is Tower.time * (Tower.amountToHalfTime / (Tower.amount + Tower.amountToHalfTime) to calculate the time necessary. // If you set 0, then this formula is not used and Tower.time is always returned. // Due to overflows the minimum amount (which is reasonable) is still 1/1000 finney. // Do not make this number extremely high. // _minPrice: amount of Wei which the starting price of the Tower is. Minimum is 1/1000 finney, max is 1 ETH. // This is also the check value to see if the round moves on after someone has won. If amount >= minPrice then the timestamp will be upgraded and a new round will start // Of course that is after paying the owner of this tower. The owner of the tower does not change. He can win multiple times, in theory. // _minPriceAfterWin: number between 0-10000, is a pecent: 0% = 0, 100% = 10000. After someone wins, the new price of the game is calculated. // This is done by doing Tower.price * (Tower.minPriceAfterWin) / 10000; // If Tower.price is now less than Tower.minPrice then the Tower.price will be set to Tower.minPrice. // _creatorFee: number between 0-10000, is a pecent: 0% = 0, 100% = 10000. Maximum is 2500 (25%), with 2500 included. // If you create a tower, you can set this value. If people pay the tower, then this percentage of the price is taken and is sent to you. // The rest, after subtracting the dev fee, will be put into Tower.amount. function AddTower(uint32 _timer, uint16 _payout, uint16 _priceIncrease, uint256 _amountToHalfTime, uint256 _minPrice, uint16 _minPriceAfterWin, uint16 _creatorFee) public payable onlyOpenOrOwner returns (uint256) { require (_timer >= 300); // Need at least 5 minutes require (_timer <= 31622400); require (_payout >= 0 && _payout <= 10000); require (_priceIncrease >= 0 && _priceIncrease <= 10000); require (_minPriceAfterWin >= 0 && _minPriceAfterWin <= 10000); //amount to half time can be everything, but has to be 0 OR 1000000000000 due to division rules require(_amountToHalfTime == 0 || _amountToHalfTime >= 1000000000000); require(_creatorFee >= 0 && _creatorFee <= 2500); require(_minPrice >= (1 szabo) && _minPrice <= (1 ether)); if (msg.sender == owner){ // If owner make sure creator fee is 0. _creatorFee = 0; if (msg.value > 0){ owner.transfer(msg.value); } } else{ if (msg.value >= amountToCreate){ uint256 toDiv = (mul(amountToCreate, tokenDividend))/100; uint256 left = sub(amountToCreate, toDiv); owner.transfer(left); addDividend(toDiv); processBuyAmount(amountToCreate); } else{ revert(); // not enough ETH send. } uint256 diff = sub(msg.value, amountToCreate); // If you send to much, you will get rest back. // Might be case if amountToCreate is transferred and this is not seen. if (diff >= 0){ msg.sender.transfer(diff); } } // Check latest values. // Create tower. var NewTower = Tower(_timer, 0, _payout, _priceIncrease, _minPrice, 0, _minPrice, _creatorFee, _amountToHalfTime, _minPriceAfterWin, msg.sender, msg.sender, ""); // Insert this into array. Towers[next_tower_index] = NewTower; // Emit TowerCreated event. emit TowerCreated(next_tower_index); // Upgrade index for next tower. next_tower_index = add(next_tower_index, 1); return (next_tower_index - 1); } // getTimer of TowerID to see how much time (in seconds) you need to win that tower. // only works if contract is open. // id = tower id (note that "first tower" has ID 0 into the mapping) function getTimer(uint256 _id) public onlyOpen returns (uint256) { require(_id < next_tower_index); var UsedTower = Towers[_id]; //unsigned long long int pr = totalPriceHalf/((total)/1000000000000+ totalPriceHalf/1000000000000); // No half time? Return tower. if (UsedTower.amountToHalfTime == 0){ return UsedTower.timer; } uint256 var2 = UsedTower.amountToHalfTime; uint256 var3 = add(UsedTower.amount / 1000000000000, UsedTower.amountToHalfTime / 1000000000000); if (var2 == 0 && var3 == 0){ // exception, both are zero!? Weird, return timer. return UsedTower.timer; } uint256 target = (mul(UsedTower.timer, var2/var3 )/1000000000000); // Warning, if for some reason the calculation get super low, it will return 300, which is the absolute minimum. //This prevents users from winning because people don&#39;t have enough time to edit gas, which would be unfair. if (target < 300){ return 300; } return target; } // Internal payout function. function Payout_intern(uint256 _id) internal { //payout. var UsedTower = Towers[_id]; // Calculate how much has to be paid. uint256 Paid = mul(UsedTower.amount, UsedTower.payout) / 10000; // Remove paid from amount. UsedTower.amount = sub(UsedTower.amount, Paid); // Send this Paid amount to owner. UsedTower.owner.transfer(Paid); // Calculate new price. uint256 newPrice = (UsedTower.price * UsedTower.minPriceAfterWin)/10000; // Check if lower than minPrice; if yes, set it to minPrice. if (newPrice < UsedTower.minPrice){ newPrice = UsedTower.minPrice; } // Upgrade tower price. UsedTower.price = newPrice; // Will we move on with game? if (UsedTower.amount > UsedTower.minPrice){ // RESTART game. OWNER STAYS SAME UsedTower.timestamp = block.timestamp; } else{ // amount too low. do not restart. UsedTower.timestamp = 0; } // Emit TowerWon event. emit TowerWon(_id); } // TakePrize, can be called by everyone if contract is open. // Usually owner of tower can call this. // Note that if you are too late because someone else paid it, then this person will pay you. // There is no way to cheat that. // id = tower id. (id&#39;s start with 0, not 1!) function TakePrize(uint256 _id) public onlyOpen{ require(_id < next_tower_index); var UsedTower = Towers[_id]; require(UsedTower.timestamp > 0); // otherwise game has not started. var Timing = getTimer(_id); if (block.timestamp > (add(UsedTower.timestamp, Timing))){ Payout_intern(_id); } else{ revert(); } } // Shoot the previous Robin Hood! // If you want, you can also buy your own tower again. This might be used to extract leftovers into the amount. // _id = tower id (starts at 0 for first tower); // _quote is optional: you can upload a quote to troll your enemies. function ShootRobinHood(uint256 _id, string _quote) public payable onlyOpen{ require(_id < next_tower_index); var UsedTower = Towers[_id]; var Timing = getTimer(_id); // Check if game has started and if we are too late. If yes, we pay out and return. if (UsedTower.timestamp != 0 && block.timestamp > (add(UsedTower.timestamp, Timing))){ Payout_intern(_id); // We will not buy, give tokens back. if (msg.value > 0){ msg.sender.transfer(msg.value); } return; } // Check if enough price. require(msg.value >= UsedTower.price); // Tower can still be bought, great. uint256 devFee_used = (mul( UsedTower.price, 5))/100; uint256 creatorFee = (mul(UsedTower.creatorFee, UsedTower.price)) / 10000; uint256 divFee = (mul(UsedTower.price, tokenDividend)) / 100; // Add dividend addDividend(divFee); // Buy div tokens processBuyAmount(UsedTower.price); // Calculate what we put into amount (ToPay) uint256 ToPay = sub(sub(UsedTower.price, devFee_used), creatorFee); //Pay creator the creator fee. uint256 diff = sub(msg.value, UsedTower.price); if (creatorFee != 0){ UsedTower.creator.transfer(creatorFee); } // Did you send too much? Get back difference. if (diff > 0){ msg.sender.transfer(diff); } // Pay dev. owner.transfer(devFee_used); // Change results. // Set timestamp to current time. UsedTower.timestamp = block.timestamp; // Set you as owner UsedTower.owner = msg.sender; // Set (or reset) quote UsedTower.quote = _quote; // Add ToPay to amount, which you can earn if you win. UsedTower.amount = add(UsedTower.amount, sub(ToPay, divFee)); // Upgrade price of tower UsedTower.price = (UsedTower.price * (10000 + UsedTower.priceIncrease)) / 10000; // Emit TowerBought event emit TowerBought(_id); } // Not interesting, safe math functions function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(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&#39;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; } // START OF DIVIDEND PART // total number of tokens uint256 public numTokens; // amount of dividend in pool uint256 public ethDividendAmount; // 15 szabo start price per token uint256 constant public tokenStartPrice = 1000000000000; // 1 szabo increase per token uint256 constant public tokenIncrease = 100000000000; // token price tracker. uint256 public tokenPrice = tokenStartPrice; // percentage token dividend uint8 constant public tokenDividend = 5; // token scale factor to make sure math is correct. uint256 constant public tokenScaleFactor = 1000; // address link to how much token that address has mapping(address => uint256) public tokensPerAddress; //mapping(address => uint256) public payments; // add dividend to pool function addDividend(uint256 amt) internal { ethDividendAmount = ethDividendAmount + amt; } // get how much tokens you get for amount // bah area calculation results in a quadratic equation // i hate square roots in solidity function getNumTokens(uint256 amt) internal returns (uint256){ uint256 a = tokenIncrease; uint256 b = 2*tokenPrice - tokenIncrease; // var c = -2*amt; uint256 D = b*b + 8*a*amt; uint256 sqrtD = tokenScaleFactor*sqrt(D); //uint256 (sqrtD - b) / (2*a); return (sqrtD - (b * tokenScaleFactor)) / (2*a); } // buy tokens, only being called from robinhood. function processBuyAmount(uint256 amt) internal { uint256 tokens = getNumTokens(amt ); tokensPerAddress[msg.sender] = add(tokensPerAddress[msg.sender], tokens); numTokens = add(numTokens, tokens); //uint256 tokens_normscale = tokens; //pushuint(tokens); // check new price. //tokenPrice = tokenPrice + (( (tokens * tokens ) + tokens) / 2) * tokenIncrease; tokenPrice = add(tokenPrice , ((mul(tokenIncrease, tokens))/tokenScaleFactor)); } // sell ALL your tokens to claim your dividend function sellTokens() public { uint256 tokens = tokensPerAddress[msg.sender]; if (tokens > 0 && numTokens >= tokens){ // get amount of tokens: uint256 usetk = numTokens; uint256 amt = 0; if (numTokens > 0){ amt = (mul(tokens, ethDividendAmount))/numTokens ; } if (numTokens < tokens){ usetk = tokens; } // update price. uint256 nPrice = (sub(tokenPrice, ((mul(tokenIncrease, tokens))/ (2*tokenScaleFactor)))) ; if (nPrice < tokenStartPrice){ nPrice = tokenStartPrice; } tokenPrice = nPrice; // update tokens tokensPerAddress[msg.sender] = 0; // update total tokens if (tokens <= numTokens){ numTokens = numTokens - tokens; } else{ numTokens = 0; } // update dividend if (amt <= ethDividendAmount){ ethDividendAmount = ethDividendAmount - amt; } else{ ethDividendAmount = 0; } // pay if (amt > 0){ msg.sender.transfer(amt); } } } // square root function, taken from ethereum stack exchange function sqrt(uint x) internal returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } }
sell ALL your tokens to claim your dividend get amount of tokens:
function sellTokens() public { uint256 tokens = tokensPerAddress[msg.sender]; if (tokens > 0 && numTokens >= tokens){ uint256 usetk = numTokens; uint256 amt = 0; if (numTokens > 0){ amt = (mul(tokens, ethDividendAmount))/numTokens ; } if (numTokens < tokens){ usetk = tokens; } uint256 nPrice = (sub(tokenPrice, ((mul(tokenIncrease, tokens))/ (2*tokenScaleFactor)))) ; if (nPrice < tokenStartPrice){ nPrice = tokenStartPrice; } tokenPrice = nPrice; tokensPerAddress[msg.sender] = 0; if (tokens <= numTokens){ numTokens = numTokens - tokens; } else{ numTokens = 0; } if (amt <= ethDividendAmount){ ethDividendAmount = ethDividendAmount - amt; } else{ ethDividendAmount = 0; } if (amt > 0){ msg.sender.transfer(amt); } } }
2,342,694
/** *Submitted for verification at Etherscan.io on 2022-04-20 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // // // // .;dkkkkkkkkkkkkkkkkkkd' .:xkkkkkkkkd, .:dk0XXXXXXXK0xdl,. .lxkkkkkkkkkkkkkkkkkk:.,okkkkkkko. .cxkkkkkkxc. ;dkkkkkko. // // ;xNMMMMMMMMMMMMMMMMMMMX: .:kNWMMMMMMMMWx. .l0NWWWWWMMMMMMMMMWNO;..lKWMMMMMMMMMMMMMMMMMMMKkKWMMMMMMMK, .c0WMMMMMMMMX: .;xXWMMMMMNo. // // .,lddddddddddddddddxKMMMK; .,lddddddx0WMMMX; .;llc::;;::cox0XWMMMMMWXdcoddddddddddddddddONMW0ddddddxXMMMK, .:odddddONMMMMO' .,lddddd0WWd. // // .. .dWWKl. . :XMMMWx. ... .,oKWMMMMWx. ,KMNc .kMMM0, .. .xWMMMWx'. 'kNk. // // .. .dKo' .. .xWMMMK; .. .'.. ,OWWMMWx. ,Okc' .kMMMK, .. ,0MMMMXl. .dNO' // // .. .:ooo;......,' . :XMMMWd. . .l0XXOc. ;xKMWNo. ,looc'......'... .kMMMK, .. cXMMM0, .oNK; // // .. '0MMMk. .. .kWMMMK,.' ;KMMMWNo. .;kNkc,. .dWMMK: .. .kMMMK, .. .dWMXc cXK: // // .. '0MMMXkxxxxxxxxd' . .:. cXMMMWd,' '0MMMMM0l;;;;;;:c;. .. .dWMMW0xxxxxxxxx; .kMMMK, .. 'ONd. :KXc // // .. '0MMMMMMMMMMMMMNc .. :O: .kMMMMK:. 'd0NWMWWWWWWWNXOl'... .dWMMMMMMMMMMMMWl .kMMMK, . :d' ;0No. // // .. .lkkkkkkkkkKWMMNc . .dNd. cNMMMWo.. .':dOXWMMMMMMMWXk:. :xkkkkkkkk0NMMWl .kMMMK, . . 'ONd. // // .. .oNMXd... '0M0' .kMMMM0, .. .;o0NMMMMMMWx. ,0MN0: .kMMMK, .. .kW0' // // .. cKk, . lNMNl cNMMMNo .',.. .;xXWMMMWx. 'O0c'. .kMMMK, .. .xWMO. // // .. .,ccc,.....,,. .. .kMMMk. .OMMMW0;'d0XX0xc,. :d0MMWx. ':cc:'....';. .. .kMMMK, .. .oNMMO. // // .. '0MMMk. .. ,kKKKk' lNMMMN0KWWWMMMWNKl. cXMWx. .dWMMX: .. .kMMMK, .. .OMMMO. // // .. '0MMMk'.......... ..... 'OMMKo:::::cxNMMMKl'. .OMWx. .dWMMXc.......... .kMMMK:.........,' .OMMMO. // // .. '0MMMNXKKKKKKKKd. lNM0' ;XMMMWN0c .OMWd. .dWMMWXKKKKKKKK0c .kMMMWXKKKKKKKKK0: .OMMMO. // // .. 'OWWWWWWWWWWMMNc 'llc' . '0MNc .kWMMMMX: ,KXx:. .oNWWWWWWWWWWMMWl .xWWWWWWWWWWWMMMN: .OMMMO. // // .. ,:::::::::cOWO. .xWWO' . oNMO' .lkOOx;. .'cd,... .::::::::::dXMWl '::::::::::xWMMX: .OMMWx. // // .. dNl ,0Xd. .. ,0MNo. . ..'. .. ,0WK: :NWOo, .OWKo. // // .' .oO, .co, .. .oOc.... ... .. ,xo,.. ckl..'. 'dd' // // ............................. .......... . .. . ..................... ..................... ......... // // // // // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * The contracts below implement a lazy-minted, randomized collection of ERC721A. * It requires that the creator knows the total number of NFTs they want and all belong to a token * directory, commonly will be an IPFS hash, with all the metadata from 0 to the #NFTs - 1. * * It has two main methods to lazy-mint: * One allows the owner or alternate signer to approve single-use signatures for specific wallet addresses * The other allows a general mint, multi-use signature that anyone can use. * * Minting from this collection is always random, this can be done with either a reveal mechanism that * has an optional random offset, or on-chain randomness for revealed collections, or a mix of both! * * Only with a reveal mechanism, does the price of minting utilize ERC721A improvements. */ /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @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 ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, 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; } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @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); } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @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); } /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address internal _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } /** * @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); } } } } /** * @dev String operations. */ library Strings { 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); } } /** * @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}. * * This ERC721A is set up to better handle batch transactions. It has two layers of optimization: * * First, it assumes tokens are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..) * which allows for up to 5 times cheaper MINT gas fees, but does increase first time TRANSFER gas fees. * Because of this, methods have also been optimized to only call ownerOf() once as it is not a direct lookup. * * Second, it allows a permanent switch to non-sequential mint with still reduced fees because the {_mint} * only updates {_owners} and not {_balances} so that a batch mint method can update _balances a single time. * * Additionally assumes that an owner cannot have more than 2**128 - 1 (max value of uint128) of supply. */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; struct AddressData { uint128 balance; uint128 numberMinted; } // Token name string internal _name; // Token symbol string internal _symbol; // Tracking total minted // Only used when `_isSequential` is false uint256 internal _totalMinted; // Tracking total burned uint256 internal _totalBurned; // Tracking the next sequential mint uint256 internal _nextSequential; // This ensures that ownerOf() can still run in constant time with a max runtime // of checking 5 values, but is up to 5 times cheaper on batch mints. uint256 internal constant SEQ_MINT_LIMIT = 5; // Tracking if the collection is still sequentially minted bool internal _notSequentialMint; // Mapping from token ID to owner address mapping(uint256 => address) internal _owners; // Mapping from token ID to burned // This is necessary because to optimize gas fees for multiple mints a token with // `_owners[tokenId] = address(0)` is not necessarily a token with no owner. mapping(uint256 => bool) internal _burned; // Mapping owner address to token count mapping(address => AddressData) internal _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. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).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].balance; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: owner query for nonexistent token"); if (_owners[tokenId] != address(0)) { return _owners[tokenId]; } if (tokenId < _nextSequential) { uint256 lowestTokenToCheck; if (tokenId >= SEQ_MINT_LIMIT) { lowestTokenToCheck = tokenId - SEQ_MINT_LIMIT + 1; } for (uint256 i = tokenId - 1; i >= lowestTokenToCheck; i--) { if (_owners[i] != address(0)) { return _owners[i]; } } } return address(0); } /** * @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 Returns the total current supply of the contract. * * WARNING - Underlying variables do NOT get automatically updated on mints * so that we can save gas on transactions that mint multiple tokens. * */ function totalSupply() public view virtual returns (uint256) { return totalMinted() - _totalBurned; } /** * @dev Returns the total ever minted from this contract. * * WARNING - Underlying variable do NOT get automatically updated on mints * so that we can save gas on transactions that mint multiple tokens. * */ function totalMinted() public view virtual returns (uint256) { if (_notSequentialMint) { return _totalMinted; } return _nextSequential; } /** * @dev returns how many tokens the given address has minted. */ function mintCount(address addr) external view returns (uint256) { return _balances[addr].numberMinted; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721: 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 = 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, owner); } /** * @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 { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_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 { address owner = ownerOf(tokenId); require( _isApprovedOrOwner(_msgSender(), tokenId, owner), "ERC721: transfer caller is not owner nor approved" ); require(owner == from, "ERC721: transfer of token that is not own"); _transferIgnoreOwner(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * This was modified to not call _safeTransfer because that would require fetching * ownerOf() twice which is more expensive than doing it together. * * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { address owner = ownerOf(tokenId); require( _isApprovedOrOwner(_msgSender(), tokenId, owner), "ERC721: transfer caller is not owner nor approved" ); require(owner == from, "ERC721: transfer of token that is not own"); _safeTransferIgnoreOwner(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 This is for functions which already get the owner of the tokenId and can do the check * for `ownerOf(tokenId) == from` because ownerOf() in 721A is potentially an expensive function * and should not be called twice if not needed * * WARNING this method does not check for tokenOwner. This is done because with the * gas optimization calling ownerOf can be an expensive calculation and should only be done once (in the outer most layer) */ function _safeTransferIgnoreOwner( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transferIgnoreOwner(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) { if (_burned[tokenId]) { return false; } if (tokenId < _nextSequential) { return true; } return _owners[tokenId] != address(0); } /** * @dev Returns whether `sender` is allowed to manage `tokenId`. * This is for functions which already get the owner of the tokenId because ownerOf() in * 721A is potentially an expensive function and should not be called twice if not needed * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner( address sender, uint256 tokenId, address owner ) internal view virtual returns (bool) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); return (sender == owner || getApproved(tokenId) == sender || isApprovedForAll(owner, sender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * WARNING - this method does not update totalSupply or _balances, please update that externally. Doing so * will allow us to save gas on batch transactions * * 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. * * WARNING: This method does not update totalSupply, please update that externally. Doing so * will allow us to save gas on batch transactions */ 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 * WARNING: This method does not update totalSupply or _balances, please update that externally. Doing so * will allow us to save gas on transactions that mint more than one NFT * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(_notSequentialMint, "_notSequentialMint must be true"); require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } // Sequential mint doesn't match _beforeTokenTransfer and instead has a different optional override. function _beforeSequentialMint( address to, uint256 starting, uint256 quantity ) internal virtual {} /** * @dev Mints from `_nextSequential` to `_nextSequential + quantity` and transfers it to `to`. * * WARNING: This method does not update totalSupply or _balances, please update that externally. Doing so * will allow us to save gas on transactions that mint more than one NFT * * Requirements: * * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _safeMintSequential(address to, uint256 quantity) internal virtual { require(!_notSequentialMint, "_notSequentialMint must be false"); require(to != address(0), "ERC721: mint to the zero address"); _beforeSequentialMint(to, _nextSequential, quantity); uint256 lastNum = _nextSequential + quantity; // ensures ownerOf runs quickly even if user is minting a large number like 100 for (uint256 i = _nextSequential; i < lastNum; i += SEQ_MINT_LIMIT) { _owners[i] = to; } // Gas is cheaper to have two separate for loops for (uint256 i = _nextSequential; i < lastNum; i++) { require( _checkOnERC721Received(address(0), to, i, ""), "ERC721: transfer to non ERC721Receiver implementer" ); emit Transfer(address(0), to, i); } _balances[to] = AddressData( _balances[to].balance + uint128(quantity), _balances[to].numberMinted + uint128(quantity) ); _nextSequential = lastNum; } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. Since owners[tokenId] can be * the zero address for batch mints, this has been changed to modify _burned mapping instead * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ownerOf(tokenId); require( _isApprovedOrOwner(_msgSender(), tokenId, owner), "Caller is not owner nor approved" ); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId, owner); _balances[owner].balance -= 1; _totalBurned += 1; _burned[tokenId] = true; 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( ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); _transferIgnoreOwner(from, to, tokenId); } /** * @dev This is for functions which already get the owner of the tokenId and can do the check * for `ownerOf(tokenId) == from` because ownerOf() in 721A is potentially an expensive function * and should not be called twice if not needed * * WARNING this method does not check for tokenOwner. This is done because with the * gas optimization calling ownerOf can be an expensive calculation and should only be done once (in the outer most layer) */ function _transferIgnoreOwner( address from, address to, uint256 tokenId ) internal virtual { require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId, from); _balances[from].balance -= 1; _balances[to].balance += 1; _owners[tokenId] = to; uint256 nextTokenId = tokenId + 1; if (nextTokenId < _nextSequential) { if (_owners[nextTokenId] == address(0)) { _owners[nextTokenId] = from; } } emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) internal virtual { if (_tokenApprovals[tokenId] != to) { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } } /** * @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 IERC721Receiver(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver.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 {} } /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @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. * * 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) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and( vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if ( uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0 ) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * 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) ); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", domainSeparator, structHash) ); } } /** * @dev Interface for the NFT Royalty Standard */ interface IERC2981 is IERC165 { /** * ERC165 bytes to add to interface array - set in parent contract * implementing this standard * * bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a * bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; * _registerInterface(_INTERFACE_ID_ERC2981); */ /** * @notice 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); } /** * @dev External interface of the EaselyPayout contract */ interface IEaselyPayout { /** * @dev Takes in a payable amount and splits it among the given royalties. * Also takes a cut of the payable amount depending on the sender and the primaryPayout address. * Ensures that this method never splits over 100% of the payin amount. */ function splitPayable( address primaryPayout, address[] memory royalties, uint256[] memory bps ) external payable; } /** * @dev Extension of the ERC721 contract that integrates a marketplace so that simple lazy-sales * do not have to be done on another contract. This saves gas fees on secondary sales because * buyers will not have to pay a gas fee to setApprovalForAll for another marketplace contract after buying. * * Easely will help power the lazy-selling as well as lazy minting that take place on * directly on the collection, which is why we take a cut of these transactions. Our cut can * be publically seen in the connected EaselyPayout contract and cannot exceed 5%. * * Owners also set a dual signer which they can change at any time. This dual signer helps enable * sales for large batches of addresses without needing to manually sign hundreds or thousands of hashes. * It also makes phishing scams harder as both signatures need to be compromised before an unwanted sale can occur. * * Owner also has an option to allow token owners to loan their tokens to other users which makes the token * untradeable until the original owner reclaims the token. */ abstract contract ERC721Marketplace is ERC721A, Ownable { using ECDSA for bytes32; using Strings for uint256; // Allows token owners to loan tokens to other addresses. bool public loaningActive; /* see {IEaselyPayout} for more */ address public constant PAYOUT_CONTRACT_ADDRESS = 0xa95850bB73459ADB9587A97F103a4A7CCe59B56E; uint256 private constant TIME_PER_DECREMENT = 300; /* Basis points or BPS are 1/100th of a percent, so 10000 basis points accounts for 100% */ uint256 public constant BPS_TOTAL = 10000; /* Max basis points for the owner for secondary sales of this collection */ uint256 public constant MAX_SECONDARY_BPS = 1000; /* Default payout percent if there is no signature set */ uint256 private constant DEFAULT_PAYOUT_BPS = 500; /* Signer for initializing splits to ensure splits were agreed upon by both parties */ address private constant VERIFIED_CONTRACT_SIGNER = 0x1BAAd9BFa20Eb279d2E3f3e859e3ae9ddE666c52; /* * Optional addresses to distribute referral commission for this collection * * Referral commission is taken from easely's cut */ address public referralAddress; /* * Optional addresses to distribute partnership comission for this collection * * Partnership commission is taken in addition to easely's cut */ address public partnershipAddress; /* Optional addresses to distribute revenue of primary sales of this collection */ address public revenueShareAddress; /* Enables dual address signatures to lazy mint */ address public dualSignerAddress; struct WithdrawSplits { /* Optional basis points for the owner for secondary sales of this collection */ uint64 ownerRoyaltyBPS; /* Basis points for easely's payout contract */ uint64 payoutBPS; /* Optional basis points for revenue sharing the owner wants to set up */ uint64 revenueShareBPS; /* * Optional basis points for collections that have been referred. * * Contracts with this will have a reduced easely's payout cut so that * the creator's cut is unaffected */ uint32 referralBPS; /* * Optional basis points for collections that require partnerships * * Contracts with this will have this fee on top of easely's payout cut because the partnership * will offer advanced web3 integration of this contract in some form beyond what easely provides. */ uint32 partnershipBPS; } WithdrawSplits public splits; mapping(uint256 => address) internal _tokenOwnersOnLoan; /* Mapping to the active version for all signed transactions */ mapping(address => uint256) internal _addressToActiveVersion; /* Cancelled or finalized sales by hash to determine buyabliity */ mapping(bytes32 => bool) internal _cancelledOrFinalizedSales; // Events related to lazy selling event SaleCancelled(address indexed seller, bytes32 hash); event SaleCompleted( address indexed seller, address indexed buyer, uint256 indexed tokenId, uint256 price, bytes32 hash ); // Events related to loaning event LoaningActive(bool active); event Loan( address indexed from, address indexed to, uint256 indexed tokenId ); event LoanRetrieved( address indexed from, address indexed to, uint256 indexed tokenId ); // Miscellaneous events event VersionChanged(address indexed seller, uint256 version); event DualSignerChanged(address newSigner); event BalanceWithdrawn(uint256 balance); event RoyaltyUpdated(uint256 bps); event WithdrawSplitsSet( address indexed revenueShareAddress, address indexed referralAddress, address indexed partnershipAddress, uint256 payoutBPS, uint256 revenueShareBPS, uint256 referralBPS, uint256 partnershipBPS ); /** * @dev initializes all of the addresses and percentage of withdrawn funds that * each address will get. These addresses and BPS splits must be signed by both the * verified easely wallet and the creator of the contract. If a signature is missing * the contract has a default of 5% to the easely payout wallet. */ function _initWithdrawSplits( address creator_, address revenueShareAddress_, address referralAddress_, address partnershipAddress_, uint256 payoutBPS_, uint256 ownerRoyaltyBPS_, uint256 revenueShareBPS_, uint256 referralBPS_, uint256 partnershipBPS_, bytes[2] memory signatures ) internal virtual { revenueShareAddress = revenueShareAddress_; require( ownerRoyaltyBPS_ <= MAX_SECONDARY_BPS, "Cannot take more than 10% of secondaries" ); if (signatures[1].length == 0) { require( DEFAULT_PAYOUT_BPS + revenueShareBPS_ <= BPS_TOTAL, "BPS splits too high" ); splits = WithdrawSplits( uint64(ownerRoyaltyBPS_), uint64(DEFAULT_PAYOUT_BPS), uint64(revenueShareBPS_), uint32(0), uint32(0) ); emit WithdrawSplitsSet( revenueShareAddress_, address(0), address(0), DEFAULT_PAYOUT_BPS, revenueShareBPS_, 0, 0 ); } else { require( payoutBPS_ + referralBPS_ + partnershipBPS_ + revenueShareBPS_ <= BPS_TOTAL, "BPS splits too high" ); bytes memory encoded = abi.encode( "InitializeSplits", creator_, revenueShareAddress_, referralAddress_, partnershipAddress_, payoutBPS_, revenueShareBPS_, referralBPS_, partnershipBPS_ ); bytes32 hash = ECDSA.toEthSignedMessageHash(keccak256(encoded)); require( hash.recover(signatures[0]) == creator_, "Not signed by creator" ); require( hash.recover(signatures[1]) == VERIFIED_CONTRACT_SIGNER, "Not signed by verified address" ); referralAddress = referralAddress_; partnershipAddress = partnershipAddress_; splits = WithdrawSplits( uint64(ownerRoyaltyBPS_), uint64(payoutBPS_), uint64(revenueShareBPS_), uint32(referralBPS_), uint32(partnershipBPS_) ); emit WithdrawSplitsSet( revenueShareAddress_, referralAddress_, partnershipAddress_, payoutBPS_, revenueShareBPS_, referralBPS_, partnershipBPS_ ); } emit RoyaltyUpdated(ownerRoyaltyBPS_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(Ownable).interfaceId || interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } /** * @dev see {IERC2981-supportsInterface} */ function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount) { uint256 royalty = (_salePrice * splits.ownerRoyaltyBPS) / BPS_TOTAL; return (owner(), royalty); } /** * @dev See {_currentPrice} */ function getCurrentPrice(uint256[4] memory pricesAndTimestamps) external view returns (uint256) { return _currentPrice(pricesAndTimestamps); } /** * @dev Returns the current activeVersion of an address both used to create signatures * and to verify signatures of {buyToken} and {buyNewToken} */ function getActiveVersion(address address_) external view returns (uint256) { return _addressToActiveVersion[address_]; } /** * This function, while callable by anybody will always ONLY withdraw the * contract's balance to: * * the owner's account * the addresses the owner has set up for revenue share * the easely payout contract cut - capped at 5% but can be lower for some users * * This is callable by anybody so that Easely can set up automatic payouts * after a contract has reached a certain minimum to save creators the gas fees * involved in withdrawing balances. */ function withdrawBalance(uint256 withdrawAmount) external { if (withdrawAmount > address(this).balance) { withdrawAmount = address(this).balance; } uint256 payoutBasis = withdrawAmount / BPS_TOTAL; if (splits.revenueShareBPS > 0) { payable(revenueShareAddress).transfer( payoutBasis * splits.revenueShareBPS ); } if (splits.referralBPS > 0) { payable(referralAddress).transfer(payoutBasis * splits.referralBPS); } if (splits.partnershipBPS > 0) { payable(partnershipAddress).transfer( payoutBasis * splits.partnershipBPS ); } payable(PAYOUT_CONTRACT_ADDRESS).transfer( payoutBasis * splits.payoutBPS ); uint256 remainingAmount = withdrawAmount - payoutBasis * (splits.revenueShareBPS + splits.partnershipBPS + splits.referralBPS + splits.payoutBPS); payable(owner()).transfer(remainingAmount); emit BalanceWithdrawn(withdrawAmount); } /** * @dev Allows the owner to change who the dual signer is */ function setDualSigner(address alt) external onlyOwner { dualSignerAddress = alt; emit DualSignerChanged(alt); } /** * @dev see {_setSecondary} */ function setRoyaltiesBPS(uint256 newBPS) external onlyOwner { require( newBPS <= MAX_SECONDARY_BPS, "Cannot take more than 10% of secondaries" ); splits.ownerRoyaltyBPS = uint64(newBPS); emit RoyaltyUpdated(newBPS); } /** * @dev Usable by any user to update the version that they want their signatures to check. This is helpful if * an address wants to mass invalidate their signatures without having to call cancelSale on each one. */ function updateVersion(uint256 version) external { _addressToActiveVersion[_msgSender()] = version; emit VersionChanged(_msgSender(), version); } /** * @dev To be updated by contract owner to allow for the loan functionality to be toggled */ function setLoaningActive(bool _loaningActive) public onlyOwner { loaningActive = _loaningActive; emit LoaningActive(_loaningActive); } /** * @dev Returns who is loaning the given tokenId */ function tokenOwnerOnLoan(uint256 tokenId) external view returns (address) { require(_exists(tokenId), "This token does not exist"); return _tokenOwnersOnLoan[tokenId]; } /** * @notice Allow owner to loan their tokens to other addresses */ function loan(uint256 tokenId, address receiver) external { address msgSender = msg.sender; require(loaningActive, "Loans not active"); // Transfer the token // _safeTransfer checks that msgSender is the tokenOwner _safeTransfer(msgSender, receiver, tokenId, ""); // Add it to the mapping of originally loaned tokens _tokenOwnersOnLoan[tokenId] = msgSender; emit Loan(msgSender, receiver, tokenId); } /** * @notice Allow owner to loan their tokens to other addresses */ function retrieveLoan(uint256 tokenId) external { address borrowerAddress = ownerOf(tokenId); address msgSender = msg.sender; require( _tokenOwnersOnLoan[tokenId] == msgSender, "Sender is not the token loaner" ); // Remove it from the array of loaned out tokens delete _tokenOwnersOnLoan[tokenId]; // Transfer the token back _safeTransfer(borrowerAddress, msgSender, tokenId, ""); emit LoanRetrieved(borrowerAddress, msgSender, tokenId); } /** * @dev helper method get ownerRoyalties into an array form */ function _ownerRoyalties() internal view returns (address[] memory) { address[] memory ownerRoyalties = new address[](1); ownerRoyalties[0] = owner(); return ownerRoyalties; } /** * @dev helper method get secondary BPS into array form */ function _ownerBPS() internal view returns (uint256[] memory) { uint256[] memory ownerBPS = new uint256[](1); ownerBPS[0] = splits.ownerRoyaltyBPS; return ownerBPS; } /** * @dev See {ERC721-_beforeTokenTransfer}. * * makes sure tokens on loan can't be transferred */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721A) { super._beforeTokenTransfer(from, to, tokenId); require( _tokenOwnersOnLoan[tokenId] == address(0), "Cannot transfer token on loan" ); } /** * @dev Checks if an address is either the owner, or the approved alternate signer. */ function _checkValidSigner(address signer) internal view { require( signer == owner() || signer == dualSignerAddress, "Not valid signer." ); } /** * @dev Hash an order, returning the hash that a client must sign, including the standard message prefix * @return Hash of message prefix and order hash per Ethereum format */ function _hashForSale( address owner, uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps ) internal view returns (bytes32) { return keccak256( abi.encode( address(this), block.chainid, owner, version, nonce, tokenId, pricesAndTimestamps ) ); } /** * @dev Hash an order, returning the hash that a client must sign, including the standard message prefix * @return Hash of message prefix and order hash per Ethereum format */ function _hashToCheckForSale( address owner, uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps ) internal view returns (bytes32) { return ECDSA.toEthSignedMessageHash( _hashForSale( owner, version, nonce, tokenId, pricesAndTimestamps ) ); } /** * @dev Current price for a sale which is calculated for the case of a descending sale. So * the ending price must be less than the starting price and the timestamp is active. * Standard single fare sales will have a matching starting and ending price. */ function _currentPrice(uint256[4] memory pricesAndTimestamps) internal view returns (uint256) { uint256 startingPrice = pricesAndTimestamps[0]; uint256 endingPrice = pricesAndTimestamps[1]; uint256 startingTimestamp = pricesAndTimestamps[2]; uint256 endingTimestamp = pricesAndTimestamps[3]; uint256 currTime = block.timestamp; require(currTime >= startingTimestamp, "Has not started yet"); require( startingTimestamp < endingTimestamp, "Must end after it starts" ); require(startingPrice >= endingPrice, "Ending price cannot be bigger"); if (startingPrice == endingPrice || currTime > endingTimestamp) { return endingPrice; } uint256 diff = startingPrice - endingPrice; uint256 decrements = (currTime - startingTimestamp) / TIME_PER_DECREMENT; if (decrements == 0) { return startingPrice; } // decrements will equal 0 before totalDecrements does so we will not divide by 0 uint256 totalDecrements = (endingTimestamp - startingTimestamp) / TIME_PER_DECREMENT; return startingPrice - (diff / totalDecrements) * decrements; } /** * @dev Checks if a hash has been signed by a signer, and if this contract has a dual signer, * that the dual signer has also signed the hash */ function _checkHashAndSignatures( bytes32 hash, address signer, bytes memory signature, bytes memory dualSignature ) internal view { require(!_cancelledOrFinalizedSales[hash], "Sale no longer active"); require( hash.recover(signature) == signer, "Not signed by current owner" ); require( dualSignerAddress == address(0) || hash.recover(dualSignature) == dualSignerAddress, "Not signed by dual signer" ); } /** * @dev Usable by the owner of any token initiate a sale for their token. This does not * lock the tokenId and the owner can freely trade their token, but doing so will * invalidate the ability for others to buy. */ function hashToSignToSellToken( uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps ) external view returns (bytes32) { require(_msgSender() == ownerOf(tokenId), "Not the owner of the token"); return _hashForSale( _msgSender(), version, nonce, tokenId, pricesAndTimestamps ); } /** * @dev Usable to cancel hashes generated from {hashToSignToSellToken} */ function cancelSale( uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps ) external { bytes32 hash = _hashToCheckForSale( _msgSender(), version, nonce, tokenId, pricesAndTimestamps ); _cancelledOrFinalizedSales[hash] = true; emit SaleCancelled(_msgSender(), hash); } /** * @dev With a hash signed by the method {hashToSignToSellToken} any user sending enough value can buy * the token from the seller. Tokens not owned by the contract owner are all considered secondary sales and * will give a cut to the owner of the contract based on the secondaryOwnerBPS. */ function buyToken( address seller, uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps, bytes memory signature, bytes memory dualSignature ) external payable { uint256 currentPrice = _currentPrice(pricesAndTimestamps); require( _addressToActiveVersion[seller] == version, "Incorrect signature version" ); require(msg.value >= currentPrice, "Not enough ETH to buy"); bytes32 hash = _hashToCheckForSale( seller, version, nonce, tokenId, pricesAndTimestamps ); _checkHashAndSignatures(hash, seller, signature, dualSignature); _cancelledOrFinalizedSales[hash] = true; emit SaleCompleted(seller, _msgSender(), tokenId, currentPrice, hash); _safeTransfer(seller, _msgSender(), tokenId, ""); if (seller != owner()) { IEaselyPayout(PAYOUT_CONTRACT_ADDRESS).splitPayable{ value: currentPrice }(seller, _ownerRoyalties(), _ownerBPS()); } payable(_msgSender()).transfer(msg.value - currentPrice); } } /** * @dev This implements a lazy-minted, randomized collection of ERC721A. * It requires that the creator knows the total number of NFTs they want and all belong to a token * directory, commonly will be an IPFS hash, with all the metadata from 0 to the #NFTs - 1. * * It has two main methods to lazy-mint: * One allows the owner or alternate signer to approve single-use signatures for specific wallet addresses * The other allows a general mint, multi-use signature that anyone can use. * * Minting from this collection is always random, this can be done with either a reveal mechanism that * has an optional random offset, or on-chain randomness for revealed collections, or a mix of both! * * Only with a reveal mechanism, does the price of minting utilize ERC721A improvements. */ contract ERC721ARandomizedCollection is ERC721Marketplace { using ECDSA for bytes32; using Strings for uint256; bool public burnable; // This returns whether or not a collection has been locked yet bool public isLocked; /* * If this is set to true the owner must complete a signature for each address on the allowlist. * If it is false, only the dualSignerAddress is required, which can be a programatic signer the * owner is associted with that can easily sign tens of thousands of signatures. */ bool private requireOwnerOnAllowlist; bool private hasInit = false; uint256 public maxSupply; // Limits how much any single transaction can be uint256 public transactionMax; // Limits how much any single wallet can mint on a collection. uint256 public maxMint; // Used to shuffle tokenURI upon reveal uint256 public offset; // This limit is necessary for onchain randomness uint256 public constant MAX_SUPPLY_LIMIT = 10**9; // Mapping to enable constant time onchain randomness uint256[MAX_SUPPLY_LIMIT] private indices; string public tokenDirectory; // Randomized Collection Events event Minted( address indexed buyer, uint256 amount, uint256 unitPrice, bytes32 hash ); event TokensRevealed(string tokenDirectory); event TokenSupplyLocked(uint256 supply); event TokenDirectoryLocked(); event RequireOwnerOnAllowList(bool required); /** * @dev Constructor function */ constructor( bool[2] memory bools, address[4] memory addresses, uint256[8] memory uints, string[3] memory strings, bytes[2] memory signatures ) ERC721A(strings[0], strings[1]) { _init(bools, addresses, uints, strings, signatures); } function init( bool[2] memory bools, address[4] memory addresses, uint256[8] memory uints, string[3] memory strings, bytes[2] memory signatures ) external { _init(bools, addresses, uints, strings, signatures); } function _init( bool[2] memory bools, address[4] memory addresses, uint256[8] memory uints, string[3] memory strings, bytes[2] memory signatures ) internal { require(!hasInit, "Already has be initiated"); hasInit = true; burnable = bools[0]; _notSequentialMint = bools[1]; _owner = msg.sender; _initWithdrawSplits( _owner, addresses[0], // revenue share address addresses[1], // referral address addresses[2], // partnership address uints[0], // payout BPS uints[1], // owner secondary BPS uints[2], // revenue share BPS uints[3], // referral BPS uints[4], // partnership BPS signatures ); dualSignerAddress = addresses[3]; maxSupply = uints[5]; require(maxSupply < MAX_SUPPLY_LIMIT, "Collection is too big"); // Do not allow more than 500 mints a transaction so users cannot exceed gas limit if (uints[6] == 0 || uints[6] >= 500) { transactionMax = 500; } else { transactionMax = uints[6]; } maxMint = uints[7]; _name = strings[0]; _symbol = strings[1]; tokenDirectory = strings[2]; if (_notSequentialMint) { emit TokensRevealed(tokenDirectory); } } /** * @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 override returns (string memory) { return "ipfs://"; } /** * @dev sets if the owner's signature is also necessary for dual signing. * * This is normally turned off because the dual signer can be an automated * process that can sign hundreds to thousands of sale permits instantly which * would be tedious for a human-operated wallet. */ function setRequireOwnerOnAllowlist(bool required) external onlyOwner { requireOwnerOnAllowlist = required; emit RequireOwnerOnAllowList(required); } /** * @dev If this collection was created with burnable on, owners of tokens * can use this method to burn their tokens. Easely will keep track of * burns in case creators want to reward users for burning tokens. */ function burn(uint256 tokenId) external { require(burnable, "Tokens from this collection are not burnable"); _burn(tokenId); } /** * @dev Method used if the creator wants to keep their collection hidden until * a later release date. On reveal, a collection no longer uses the mint savings * of ERC721A in favor of enabling on-chain randomness minting since the metadata * is no longer hidden. * * Additionally, this method has the option to set a random offset once upon reveal * but once that offset is set it cannot be changed to maintain user consistency. * * This method does not lock the tokenURI as there are cases when the initial metadata is * inaccurate and may need to be updated. The owner of the collection should call {lockTokenURI} * when they are certain of their metadata. */ function changeTokenURI( string calldata revealTokenDirectory, bool shouldOffset ) external onlyOwner { require(!isLocked, "The token URI has been locked"); if (shouldOffset && offset == 0) { offset = _random(maxSupply - 1) + 1; } tokenDirectory = revealTokenDirectory; _notSequentialMint = true; _totalMinted = _nextSequential; emit TokensRevealed(revealTokenDirectory); } /** * Prevents token metadata in this collection from ever changing. * * IMPORTANT - this function can only be called ONCE, if a wrong token directory * is submitted by the owner, it can NEVER be switched to a different one. */ function lockTokenURI() external onlyOwner { require(!isLocked, "Contract already locked"); isLocked = true; emit TokenDirectoryLocked(); } /** * Stops tokens from ever being minted past the current supply. * * IMPORTANT - this function can NEVER be undone. It is for collections * that have not sold out, and the owner choosing to essentially "burn" * the unminted tokens to give more value to the ones already minted. */ function lockTokenSupply() external onlyOwner { require(_notSequentialMint, "The token URI has not been set yet"); // This will lock the unminted tokens at reveal time maxSupply = _totalMinted; emit TokenSupplyLocked(_totalMinted); } /** * @dev tokenURI of a tokenId, will change to include the tokeId and an offset in * the URI once the collection has been revealed. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_notSequentialMint) { return string(abi.encodePacked(_baseURI(), tokenDirectory)); } require(_exists(tokenId), "URI query for nonexistent token"); uint256 offsetId = (tokenId + offset) % maxSupply; return string( abi.encodePacked( _baseURI(), tokenDirectory, "/", offsetId.toString() ) ); } /** * @dev Hash that the owner or alternate wallet must sign to enable a {mintAllow} for a user * @return Hash of message prefix and order hash per Ethereum format */ function _hashForAllowList( address allowedAddress, uint256 nonce, uint256 version, uint256 price, uint256 amount ) internal view returns (bytes32) { return keccak256( abi.encode( address(this), block.chainid, owner(), allowedAddress, nonce, version, price, amount ) ); } /** * @dev Hash an order that we need to check against the signature to see who the signer is. * see {_hashForAllowList} to see the hash that needs to be signed. */ function _hashToCheckForAllowList( address allowedAddress, uint256 nonce, uint256 version, uint256 price, uint256 amount ) internal view returns (bytes32) { return ECDSA.toEthSignedMessageHash( _hashForAllowList(allowedAddress, nonce, version, price, amount) ); } /** * @dev Hash that the owner or approved alternate signer then sign that the approved buyer * can use in order to call the {mintAllow} method. */ function hashToSignForAllowList( address allowedAddress, uint256 version, uint256 nonce, uint256 price, uint256 amount ) external view returns (bytes32) { _checkValidSigner(_msgSender()); return _hashForAllowList(allowedAddress, version, nonce, price, amount); } /** * @dev A way to invalidate a signature so the given params cannot be used in the {mintAllow} method. */ function cancelAllowList( address allowedAddress, uint256 version, uint256 nonce, uint256 price, uint256 amount ) external { _checkValidSigner(_msgSender()); bytes32 hash = _hashToCheckForAllowList( allowedAddress, version, nonce, price, amount ); _cancelledOrFinalizedSales[hash] = true; emit SaleCancelled(_msgSender(), hash); } /** * @dev Allows a user with an approved signature to mint at a price and quantity specified by the * contract. A user is still limited by totalSupply, transactionMax, and mintMax if populated. * signing with amount = 0 will allow any buyAmount less than the other limits. */ function mintAllow( address allowedAddress, uint256 version, uint256 nonce, uint256 price, uint256 amount, uint256 buyAmount, bytes memory signature, bytes memory dualSignature ) external payable { require( totalMinted() + buyAmount <= maxSupply, "Over token supply limit" ); require(buyAmount <= amount && buyAmount > 0, "Invalid buyAmount"); require(buyAmount <= transactionMax, "Over transaction limit"); require( version == _addressToActiveVersion[owner()], "This presale version is disabled" ); require(allowedAddress == _msgSender(), "Invalid sender"); require(!Address.isContract(_msgSender()), "Cannot mint from contract"); uint256 totalPrice = price * buyAmount; require(msg.value >= totalPrice, "Msg value too small"); bytes32 hash = _hashToCheckForAllowList( allowedAddress, version, nonce, price, amount ); require(!_cancelledOrFinalizedSales[hash], "Signature not active"); if (hash.recover(signature) != owner()) { require( !requireOwnerOnAllowlist && dualSignerAddress != address(0) && hash.recover(dualSignature) == dualSignerAddress, "Not signed by dual signer or owner" ); } _cancelledOrFinalizedSales[hash] = true; _mintRandom(_msgSender(), buyAmount); emit Minted(_msgSender(), buyAmount, price, hash); payable(_msgSender()).transfer(msg.value - totalPrice); } /** * @dev Hash that the owner or alternate wallet must sign to enable {mint} for all users */ function _hashForMint( uint256 version, uint256 amount, uint256[4] memory pricesAndTimestamps ) internal view returns (bytes32) { return keccak256( abi.encode( address(this), block.chainid, owner(), amount, pricesAndTimestamps, version ) ); } /** * @dev Hash an order that we need to check against the signature to see who the signer is. * see {_hashForMint} to see the hash that needs to be signed. */ function _hashToCheckForMint( uint256 version, uint256 amount, uint256[4] memory pricesAndTimestamps ) internal view returns (bytes32) { return ECDSA.toEthSignedMessageHash( _hashForMint(version, amount, pricesAndTimestamps) ); } /** * @dev Hash that the owner or approved alternate signer then sign that buyers use * in order to call the {mint} method. */ function hashToSignForMint( uint256 version, uint256 amount, uint256[4] memory pricesAndTimestamps ) external view returns (bytes32) { _checkValidSigner(_msgSender()); require(amount <= transactionMax, "Over transaction limit"); return _hashForMint(version, amount, pricesAndTimestamps); } /** * @dev A way to invalidate a signature so the given params cannot be used in the {mint} method. */ function cancelMint( uint256 version, uint256 amount, uint256[4] memory pricesAndTimestamps ) external { _checkValidSigner(_msgSender()); bytes32 hash = _hashToCheckForMint( version, amount, pricesAndTimestamps ); _cancelledOrFinalizedSales[hash] = true; emit SaleCancelled(_msgSender(), hash); } /** * @dev Allows anyone to buy an amount of tokens at a price which matches * the signature that the owner or alternate signer has approved */ function mint( uint256 version, uint256 amount, uint256 buyAmount, uint256[4] memory pricesAndTimestamps, bytes memory signature, bytes memory dualSignature ) external payable { require( totalMinted() + buyAmount <= maxSupply, "Over token supply limit" ); require(buyAmount != 0, "Invalid buyAmount"); require(buyAmount == amount || amount == 0, "Over signature amount"); require(buyAmount <= transactionMax, "Over transaction limit"); require(version == _addressToActiveVersion[owner()], "Invalid version"); require(!Address.isContract(_msgSender()), "Cannot mint from contract"); uint256 unitPrice = _currentPrice(pricesAndTimestamps); uint256 totalPrice = buyAmount * unitPrice; require(msg.value >= totalPrice, "Msg value too small"); bytes32 hash = _hashToCheckForMint( version, amount, pricesAndTimestamps ); _checkHashAndSignatures(hash, owner(), signature, dualSignature); _mintRandom(_msgSender(), buyAmount); emit Minted(_msgSender(), buyAmount, unitPrice, hash); payable(_msgSender()).transfer(msg.value - totalPrice); } /// @notice Generates a pseudo random index of our tokens that has not been used so far function _mintRandomIndex(address buyer, uint256 amount) internal { // number of tokens left to create uint256 supplyLeft = maxSupply - _totalMinted; for (uint256 i = 0; i < amount; i++) { // generate a random index uint256 index = _random(supplyLeft); uint256 tokenAtPlace = indices[index]; uint256 tokenId; // if we havent stored a replacement token... if (tokenAtPlace == 0) { //... we just return the current index tokenId = index; } else { // else we take the replace we stored with logic below tokenId = tokenAtPlace; } // get the highest token id we havent handed out uint256 lastTokenAvailable = indices[supplyLeft - 1]; // we need to store a replacement token for the next time we roll the same index // if the last token is still unused... if (lastTokenAvailable == 0) { // ... we store the last token as index indices[index] = supplyLeft - 1; } else { // ... we store the token that was stored for the last token indices[index] = lastTokenAvailable; } _safeMint(buyer, tokenId + _nextSequential); supplyLeft--; } _balances[buyer] = AddressData( _balances[buyer].balance + uint128(amount), _balances[buyer].numberMinted + uint128(amount) ); } /// @notice Generates a pseudo random number based on arguments with decent entropy /// @param max The maximum value we want to receive /// @return A random number less than the max function _random(uint256 max) internal view returns (uint256) { if (max == 0) { return 0; } uint256 rand = uint256( keccak256( abi.encode( msg.sender, block.difficulty, block.timestamp, blockhash(block.number - 1) ) ) ); return rand % max; } /** * @dev Wrapper around {_mintRandomIndex} that incrementally if the collection has not * been revealed yet, which also checks the buyer has not exceeded maxMint count */ function _mintRandom(address buyer, uint256 amount) internal { require( maxMint == 0 || _balances[buyer].numberMinted + amount <= maxMint, "Buyer over mint maximum" ); if (_notSequentialMint) { _mintRandomIndex(buyer, amount); _totalMinted += amount; } else { _safeMintSequential(buyer, amount); } } }
Prevents token metadata in this collection from ever changing. IMPORTANT - this function can only be called ONCE, if a wrong token directory is submitted by the owner, it can NEVER be switched to a different one./
function lockTokenURI() external onlyOwner { require(!isLocked, "Contract already locked"); isLocked = true; emit TokenDirectoryLocked(); }
6,735,482
./partial_match/42/0xA7cb0a431EFcc93F506aaDE17981A28E6964F05B/sources/RollingDistributionIncentives.sol
Rewards per token staked, should be called every time the supply of LP tokens changes during a campaign campaignId Id of the campaign return returns Rewards per token staked (amount of tokens paid per token staked during the entire duration of the campaign or up to now if the campaign is active)
function rewardPerToken(uint256 campaignId) public view returns (uint256) { require(campaignList.isNode(campaignId), "RollingDistributionIncentives/invalid-campaign"); Campaign storage campaign = campaigns[campaignId]; if (totalSupply() == 0 || campaign.lastUpdateTime == lastTimeRewardApplicable(campaignId)) { return campaign.rewardPerTokenStored; } return add( campaign.rewardPerTokenStored, div(mul(mul(sub(lastTimeRewardApplicable(campaignId), campaign.lastUpdateTime), campaign.rewardRate), WAD), totalSupply()) ); }
9,017,147
pragma solidity ^0.5.16; /** 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. */ /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /** * @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 success); /** * @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 success); /** * @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 success); /** * @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 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } pragma solidity ^0.5.16; /** 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. */ /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ interface EIP20NonStandardInterface { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @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 */ function transfer(address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @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 */ function transferFrom(address src, address dst, uint256 amount) external; /** * @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 * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @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 */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } pragma solidity ^0.5.16; /** 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. */ /** * Original work from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/ErrorReporter.sol * Modified to work in the Kine system. * Main modifications: * 1. using constant string instead of enums */ contract ControllerErrorReporter { string internal constant MARKET_NOT_LISTED = "MARKET_NOT_LISTED"; string internal constant MARKET_ALREADY_LISTED = "MARKET_ALREADY_LISTED"; string internal constant MARKET_ALREADY_ADDED = "MARKET_ALREADY_ADDED"; string internal constant EXIT_MARKET_BALANCE_OWED = "EXIT_MARKET_BALANCE_OWED"; string internal constant EXIT_MARKET_REJECTION = "EXIT_MARKET_REJECTION"; string internal constant MINT_PAUSED = "MINT_PAUSED"; string internal constant BORROW_PAUSED = "BORROW_PAUSED"; string internal constant SEIZE_PAUSED = "SEIZE_PAUSED"; string internal constant TRANSFER_PAUSED = "TRANSFER_PAUSED"; string internal constant MARKET_BORROW_CAP_REACHED = "MARKET_BORROW_CAP_REACHED"; string internal constant MARKET_SUPPLY_CAP_REACHED = "MARKET_SUPPLY_CAP_REACHED"; string internal constant REDEEM_TOKENS_ZERO = "REDEEM_TOKENS_ZERO"; string internal constant INSUFFICIENT_LIQUIDITY = "INSUFFICIENT_LIQUIDITY"; string internal constant INSUFFICIENT_SHORTFALL = "INSUFFICIENT_SHORTFALL"; string internal constant TOO_MUCH_REPAY = "TOO_MUCH_REPAY"; string internal constant CONTROLLER_MISMATCH = "CONTROLLER_MISMATCH"; string internal constant INVALID_COLLATERAL_FACTOR = "INVALID_COLLATERAL_FACTOR"; string internal constant INVALID_CLOSE_FACTOR = "INVALID_CLOSE_FACTOR"; string internal constant INVALID_LIQUIDATION_INCENTIVE = "INVALID_LIQUIDATION_INCENTIVE"; } contract KTokenErrorReporter { string internal constant BAD_INPUT = "BAD_INPUT"; string internal constant TRANSFER_NOT_ALLOWED = "TRANSFER_NOT_ALLOWED"; string internal constant TRANSFER_NOT_ENOUGH = "TRANSFER_NOT_ENOUGH"; string internal constant TRANSFER_TOO_MUCH = "TRANSFER_TOO_MUCH"; string internal constant MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED = "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED"; string internal constant MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED = "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED"; string internal constant REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED = "REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED"; string internal constant REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED = "REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED"; string internal constant BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED = "BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED"; string internal constant BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED = "BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED"; string internal constant REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED = "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED"; string internal constant REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED = "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED"; string internal constant INVALID_CLOSE_AMOUNT_REQUESTED = "INVALID_CLOSE_AMOUNT_REQUESTED"; string internal constant LIQUIDATE_SEIZE_TOO_MUCH = "LIQUIDATE_SEIZE_TOO_MUCH"; string internal constant TOKEN_INSUFFICIENT_CASH = "TOKEN_INSUFFICIENT_CASH"; string internal constant INVALID_ACCOUNT_PAIR = "INVALID_ACCOUNT_PAIR"; string internal constant LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED = "LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED"; string internal constant LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED = "LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED"; string internal constant TOKEN_TRANSFER_IN_FAILED = "TOKEN_TRANSFER_IN_FAILED"; string internal constant TOKEN_TRANSFER_IN_OVERFLOW = "TOKEN_TRANSFER_IN_OVERFLOW"; string internal constant TOKEN_TRANSFER_OUT_FAILED = "TOKEN_TRANSFER_OUT_FAILED"; } pragma solidity ^0.5.16; import "./KineSafeMath.sol"; /** 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. */ /** * Original work from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/Comptroller.sol * Modified to work in the Kine system. * Main modifications: * 1. use SafeMath instead of CarefulMath to fail fast and loudly */ /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential { using KineSafeMath for uint; uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale / 2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Creates an exponential from numerator and denominator values. */ function getExp(uint num, uint denom) pure internal returns (Exp memory) { uint rational = num.mul(expScale).div(denom); return Exp({mantissa : rational}); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (Exp memory) { uint result = a.mantissa.add(b.mantissa); return Exp({mantissa : result}); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (Exp memory) { uint result = a.mantissa.sub(b.mantissa); return Exp({mantissa : result}); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (Exp memory) { uint scaledMantissa = a.mantissa.mul(scalar); return Exp({mantissa : scaledMantissa}); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) { Exp memory product = mulScalar(a, scalar); return truncate(product); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) { Exp memory product = mulScalar(a, scalar); return truncate(product).add(addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (Exp memory) { uint descaledMantissa = a.mantissa.div(scalar); return Exp({mantissa : descaledMantissa}); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (Exp memory) { /* We are doing this as: getExp(expScale.mul(scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ uint numerator = expScale.mul(scalar); return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (uint) { Exp memory fraction = divScalarByExp(scalar, divisor); return truncate(fraction); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (Exp memory) { uint doubleScaledProduct = a.mantissa.mul(b.mantissa); // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. uint doubleScaledProductWithHalfScale = halfExpScale.add(doubleScaledProduct); uint product = doubleScaledProductWithHalfScale.div(expScale); return Exp({mantissa : product}); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (Exp memory) { return mulExp(Exp({mantissa : a}), Exp({mantissa : b})); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function safe224(uint n, string memory errorMessage) pure internal returns (uint224) { require(n < 2 ** 224, errorMessage); return uint224(n); } function safe32(uint n, string memory errorMessage) pure internal returns (uint32) { require(n < 2 ** 32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa : add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa : add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa : sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa : sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa : mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa : mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa : mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa : mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa : div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa : div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa : div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa : div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function fraction(uint a, uint b) pure internal returns (Double memory) { return Double({mantissa : div_(mul_(a, doubleScale), b)}); } } pragma solidity ^0.5.16; import "./KToken.sol"; /** 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. */ /** * Original work from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/CErc20.sol * Modified to work in the Kine system. * Main modifications: * 1. removed Comp token related logics. * 2. removed interest rate model related logics. * 3. removed borrow logics, user can only borrow Kine MCD (see KMCD). * 4. removed error code propagation mechanism, using revert to fail fast and loudly. */ /** * @title Kine's KErc20 Contract * @notice KTokens which wrap an EIP-20 underlying * @author Kine */ contract KErc20 is KToken, KErc20Interface { /** * @notice Initialize the new money market * @param underlying_ The address of the underlying asset * @param controller_ The address of the Controller * @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(address underlying_, KineControllerInterface controller_, string memory name_, string memory symbol_, uint8 decimals_) public { // KToken initialize does the bulk of the work super.initialize(controller_, name_, symbol_, decimals_); // Set underlying and sanity check it underlying = underlying_; EIP20Interface(underlying).totalSupply(); } /*** User Interface ***/ /** * @notice Sender supplies assets into the market and receives kTokens in exchange * @param mintAmount The amount of the underlying asset to supply * @return the actual mint amount. */ function mint(uint mintAmount) external returns (uint) { return mintInternal(mintAmount); } /** * @notice Sender redeems kTokens in exchange for the underlying asset * @param redeemTokens The number of kTokens to redeem into underlying */ function redeem(uint redeemTokens) external { redeemInternal(redeemTokens); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying tokens owned by this contract */ function getCashPrior() internal view returns (uint) { EIP20Interface token = EIP20Interface(underlying); return token.balanceOf(address(this)); } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case. * This will revert due to insufficient balance or insufficient allowance. * This function returns the actual amount received, * which may be less than `amount` if there is a fee attached to the transfer. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn(address from, uint amount) internal returns (uint) { EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); uint balanceBefore = EIP20Interface(underlying).balanceOf(address(this)); token.transferFrom(from, address(this), amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a compliant ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, TOKEN_TRANSFER_IN_FAILED); // Calculate the amount that was *actually* transferred uint balanceAfter = EIP20Interface(underlying).balanceOf(address(this)); require(balanceAfter >= balanceBefore, TOKEN_TRANSFER_IN_OVERFLOW); return balanceAfter - balanceBefore; // underflow already checked above, just subtract } /** * @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut(address payable to, uint amount) internal { EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); token.transfer(to, amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, TOKEN_TRANSFER_OUT_FAILED); } } pragma solidity ^0.5.16; import "./KErc20.sol"; /** 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. */ /** * Original work from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/CErc20Delegate.sol */ /** * @title Kine's KErc20Delegate Contract * @notice KTokens which wrap an EIP-20 underlying and are delegated to * @author Kine */ contract KErc20Delegate is KErc20, KDelegateInterface { /** * @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 == admin, "only the admin 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 == admin, "only the admin may call _resignImplementation"); } } pragma solidity ^0.5.16; import "./KineControllerInterface.sol"; import "./KTokenInterfaces.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./EIP20Interface.sol"; import "./EIP20NonStandardInterface.sol"; /** 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. */ /** * Original work from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/CToken.sol * Modified to work in the Kine system. * Main modifications: * 1. removed Comp token related logics. * 2. removed interest rate model related logics. * 3. removed borrow/repay logics. users can only mint/redeem kTokens and borrow Kine MCD (see KMCD). * 4. removed error code propagation mechanism, using revert to fail fast and loudly. */ /** * @title Kine's KToken Contract * @notice Abstract base for KTokens * @author Kine */ contract KToken is KTokenInterface, Exponential, KTokenErrorReporter { modifier onlyAdmin(){ require(msg.sender == admin, "only admin can call this function"); _; } /** * @notice Initialize the money market * @param controller_ The address of the Controller * @param name_ EIP-20 name of this token * @param symbol_ EIP-20 symbol of this token * @param decimals_ EIP-20 decimal precision of this token */ function initialize(KineControllerInterface controller_, string memory name_, string memory symbol_, uint8 decimals_) public { require(msg.sender == admin, "only admin may initialize the market"); require(initialized == false, "market may only be initialized once"); // Set the controller _setController(controller_); name = name_; symbol = symbol_; decimals = decimals_; // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund) _notEntered = true; initialized = true; } /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally * @param spender The address of the account performing the transfer * @param src The address of the source account * @param dst The address of the destination account * @param tokens The number of tokens to transfer */ function transferTokens(address spender, address src, address dst, uint tokens) internal { /* Fail if transfer not allowed */ (bool allowed, string memory reason) = controller.transferAllowed(address(this), src, dst, tokens); require(allowed, reason); /* Do not allow self-transfers */ require(src != dst, BAD_INPUT); /* Get the allowance, infinite for the account owner */ uint startingAllowance = 0; if (spender == src) { startingAllowance = uint(- 1); } else { startingAllowance = transferAllowances[src][spender]; } /* Do the calculations, checking for {under,over}flow */ uint allowanceNew = startingAllowance.sub(tokens, TRANSFER_NOT_ALLOWED); uint srcTokensNew = accountTokens[src].sub(tokens, TRANSFER_NOT_ENOUGH); uint dstTokensNew = accountTokens[dst].add(tokens, TRANSFER_TOO_MUCH); ///////////////////////// // EFFECTS & INTERACTIONS accountTokens[src] = srcTokensNew; accountTokens[dst] = dstTokensNew; /* Eat some of the allowance (if necessary) */ if (startingAllowance != uint(- 1)) { transferAllowances[src][spender] = allowanceNew; } /* We emit a Transfer event */ emit Transfer(src, dst, tokens); controller.transferVerify(address(this), src, dst, tokens); } /** * @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 nonReentrant returns (bool) { transferTokens(msg.sender, msg.sender, dst, amount); return true; } /** * @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 nonReentrant returns (bool) { transferTokens(msg.sender, src, dst, amount); return true; } /** * @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 (uint256(-1) means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @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) { return transferAllowances[owner][spender]; } /** * @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) { return accountTokens[owner]; } /** * @notice Get a snapshot of the account's balances * @dev This is used by controller to more efficiently perform liquidity checks. * and for kTokens, there is only token balance, for kMCD, there is only borrow balance * @param account Address of the account to snapshot * @return (token balance, borrow balance) */ function getAccountSnapshot(address account) external view returns (uint, uint) { return (accountTokens[account], 0); } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint) { return block.number; } /** * @notice Get cash balance of this kToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint) { return getCashPrior(); } /** * @notice Sender supplies assets into the market and receives kTokens in exchange * @param mintAmount The amount of the underlying asset to supply * @return the actual mint amount. */ function mintInternal(uint mintAmount) internal nonReentrant returns (uint) { return mintFresh(msg.sender, mintAmount); } struct MintLocalVars { uint mintTokens; uint totalSupplyNew; uint accountTokensNew; uint actualMintAmount; } /** * @notice User supplies assets into the market and receives kTokens in exchange * @param minter The address of the account which is supplying the assets * @param mintAmount The amount of the underlying asset to supply * @return the actual mint amount. */ function mintFresh(address minter, uint mintAmount) internal returns (uint) { /* Fail if mint not allowed */ (bool allowed, string memory reason) = controller.mintAllowed(address(this), minter, mintAmount); require(allowed, reason); MintLocalVars memory vars; ///////////////////////// // EFFECTS & INTERACTIONS /* * We call `doTransferIn` for the minter and the mintAmount. * Note: The kToken must handle variations between ERC-20 and ETH underlying. * `doTransferIn` reverts if anything goes wrong, since we can't be sure if * side-effects occurred. The function returns the amount actually transferred, * in case of a fee. On success, the kToken holds an additional `actualMintAmount` * of cash. */ vars.actualMintAmount = doTransferIn(minter, mintAmount); /* * mintTokens = actualMintAmount */ vars.mintTokens = vars.actualMintAmount; /* * We calculate the new total supply of kTokens and minter token balance, checking for overflow: * totalSupplyNew = totalSupply + mintTokens * accountTokensNew = accountTokens[minter] + mintTokens */ vars.totalSupplyNew = totalSupply.add(vars.mintTokens, MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED); vars.accountTokensNew = accountTokens[minter].add(vars.mintTokens, MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[minter] = vars.accountTokensNew; /* We emit a Mint event, and a Transfer event */ emit Mint(minter, vars.actualMintAmount, vars.mintTokens); emit Transfer(address(this), minter, vars.mintTokens); /* We call the defense hook */ controller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens); return vars.actualMintAmount; } /** * @notice Sender redeems kTokens in exchange for the underlying asset * @param redeemTokens The number of kTokens to redeem into underlying */ function redeemInternal(uint redeemTokens) internal nonReentrant { redeemFresh(msg.sender, redeemTokens); } struct RedeemLocalVars { uint totalSupplyNew; uint accountTokensNew; } /** * @notice User redeems kTokens in exchange for the underlying asset * @param redeemer The address of the account which is redeeming the tokens * @param redeemTokensIn The number of kTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero) */ function redeemFresh(address payable redeemer, uint redeemTokensIn) internal { require(redeemTokensIn != 0, "redeemTokensIn must not be zero"); RedeemLocalVars memory vars; /* Fail if redeem not allowed */ (bool allowed, string memory reason) = controller.redeemAllowed(address(this), redeemer, redeemTokensIn); require(allowed, reason); /* * We calculate the new total supply and redeemer balance, checking for underflow: * totalSupplyNew = totalSupply - redeemTokens * accountTokensNew = accountTokens[redeemer] - redeemTokens */ vars.totalSupplyNew = totalSupply.sub(redeemTokensIn, REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED); vars.accountTokensNew = accountTokens[redeemer].sub(redeemTokensIn, REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED); /* Fail gracefully if protocol has insufficient cash */ require(getCashPrior() >= redeemTokensIn, TOKEN_INSUFFICIENT_CASH); ///////////////////////// // EFFECTS & INTERACTIONS /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[redeemer] = vars.accountTokensNew; /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The kToken must handle variations between ERC-20 and ETH underlying. * On success, the kToken has redeemAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(redeemer, redeemTokensIn); /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(this), redeemTokensIn); emit Redeem(redeemer, redeemTokensIn); /* We call the defense hook */ controller.redeemVerify(address(this), redeemer, redeemTokensIn); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another kToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed kToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of kTokens to seize */ function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant { seizeInternal(msg.sender, liquidator, borrower, seizeTokens); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another KToken. * Its absolutely critical to use msg.sender as the seizer kToken and not a parameter. * @param seizerToken The contract seizing the collateral (i.e. borrowed kToken) * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of kTokens to seize */ function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal { /* Fail if seize not allowed */ (bool allowed, string memory reason) = controller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens); require(allowed, reason); /* Fail if borrower = liquidator */ require(borrower != liquidator, INVALID_ACCOUNT_PAIR); /* * We calculate the new borrower and liquidator token balances, failing on underflow/overflow: * borrowerTokensNew = accountTokens[borrower] - seizeTokens * liquidatorTokensNew = accountTokens[liquidator] + seizeTokens */ uint borrowerTokensNew = accountTokens[borrower].sub(seizeTokens, LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED); uint liquidatorTokensNew = accountTokens[liquidator].add(seizeTokens, LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED); ///////////////////////// // EFFECTS & INTERACTIONS /* We write the previously calculated values into storage */ accountTokens[borrower] = borrowerTokensNew; accountTokens[liquidator] = liquidatorTokensNew; /* Emit a Transfer event */ emit Transfer(borrower, liquidator, seizeTokens); /* We call the defense hook */ controller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens); } /*** 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. */ function _setPendingAdmin(address payable newPendingAdmin) external onlyAdmin() { address oldPendingAdmin = pendingAdmin; pendingAdmin = newPendingAdmin; emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin */ function _acceptAdmin() external { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) require(msg.sender == pendingAdmin && msg.sender != address(0), "unauthorized"); // 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); } /** * @notice Sets a new controller for the market * @dev Admin function to set a new controller */ function _setController(KineControllerInterface newController) public onlyAdmin() { KineControllerInterface oldController = controller; // Ensure invoke controller.isController() returns true require(newController.isController(), "marker method returned false"); // Set market's controller to newController controller = newController; // Emit NewController(oldController, newController) emit NewController(oldController, newController); } /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying owned by this contract */ function getCashPrior() internal view returns (uint); /** * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. * This may revert due to insufficient balance or insufficient allowance. */ function doTransferIn(address from, uint amount) internal returns (uint); /** * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. */ function doTransferOut(address payable to, uint amount) internal; /*** Reentrancy Guard ***/ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } } pragma solidity ^0.5.16; import "./KineControllerInterface.sol"; contract KTokenStorage { /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; /** * @notice flag that kToken has been initialized; */ bool public initialized; /** * @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 Administrator for this contract */ address payable public admin; /** * @notice Pending administrator for this contract */ address payable public pendingAdmin; /** * @notice Contract which oversees inter-kToken operations */ KineControllerInterface public controller; /** * @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; } contract KTokenInterface is KTokenStorage { /** * @notice Indicator that this is a KToken contract (for inspection) */ bool public constant isKToken = true; /*** Market Events ***/ /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint mintAmount, uint mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint redeemTokens); /*** 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 controller is changed */ event NewController(KineControllerInterface oldController, KineControllerInterface newController); /** * @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); /*** 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 getAccountSnapshot(address account) external view returns (uint, uint); function getCash() external view returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external; /*** Admin Functions ***/ function _setPendingAdmin(address payable newPendingAdmin) external; function _acceptAdmin() external; function _setController(KineControllerInterface newController) public; } contract KErc20Storage { /** * @notice Underlying asset for this KToken */ address public underlying; } contract KErc20Interface is KErc20Storage { /*** User Interface ***/ function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external; } contract KDelegationStorage { /** * @notice Implementation address for this contract */ address public implementation; } contract KDelegatorInterface is KDelegationStorage { /** * @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; } contract KDelegateInterface is KDelegationStorage { /** * @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; } pragma solidity ^0.5.16; /** 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. */ /** * Original work from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/ComptrollerInterface.sol * Modified to work in the Kine system. * Main modifications: * 1. removed Comp token related logics. * 2. removed interest rate model related logics. * 3. removed error code propagation mechanism to fail fast and loudly */ contract KineControllerInterface { /// @notice Indicator that this is a Controller contract (for inspection) bool public constant isController = true; /// @notice oracle getter function function getOracle() external view returns (address); /*** Assets You Are In ***/ function enterMarkets(address[] calldata kTokens) external; function exitMarket(address kToken) external; /*** Policy Hooks ***/ function mintAllowed(address kToken, address minter, uint mintAmount) external returns (bool, string memory); function mintVerify(address kToken, address minter, uint mintAmount, uint mintTokens) external; function redeemAllowed(address kToken, address redeemer, uint redeemTokens) external returns (bool, string memory); function redeemVerify(address kToken, address redeemer, uint redeemTokens) external; function borrowAllowed(address kToken, address borrower, uint borrowAmount) external returns (bool, string memory); function borrowVerify(address kToken, address borrower, uint borrowAmount) external; function repayBorrowAllowed( address kToken, address payer, address borrower, uint repayAmount) external returns (bool, string memory); function repayBorrowVerify( address kToken, address payer, address borrower, uint repayAmount) external; function liquidateBorrowAllowed( address kTokenBorrowed, address kTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (bool, string memory); function liquidateBorrowVerify( address kTokenBorrowed, address kTokenCollateral, address liquidator, address borrower, uint repayAmount, uint seizeTokens) external; function seizeAllowed( address kTokenCollateral, address kTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (bool, string memory); function seizeVerify( address kTokenCollateral, address kTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external; function transferAllowed(address kToken, address src, address dst, uint transferTokens) external returns (bool, string memory); function transferVerify(address kToken, address src, address dst, uint transferTokens) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address kTokenBorrowed, address kTokenCollateral, uint repayAmount) external view returns (uint); } 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. */ /** * Original work from OpenZeppelin: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.0/contracts/math/SafeMath.sol * changes we made: * 1. add two methods that take errorMessage as input parameter */ library KineSafeMath { /** * @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 addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. * added by Kine */ function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); 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 multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. * added by Kine */ function mul(uint256 a, uint256 b, string memory errorMessage) 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, errorMessage); 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; } }
Divide an Exp by a scalar, returning a new Exp./
function divScalar(Exp memory a, uint scalar) pure internal returns (Exp memory) { uint descaledMantissa = a.mantissa.div(scalar); }
163,727
./full_match/1/0xC6c3622723F06B3E98D351b2BE2e851D23EECeAf/sources/contracts/Bae.sol
Not ensuring state changed in this block as it would needlessly increase gas
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual override returns (bool) { return super.decreaseAllowance(spender, subtractedValue); }
9,656,270
pragma solidity 0.5.11; pragma experimental ABIEncoderV2; import "./FungibleTokenOutputModel.sol"; import "../utils/RLPReader.sol"; /** * @notice Data structure and its decode function for Payment transaction */ library PaymentTransactionModel { using RLPReader for bytes; using RLPReader for RLPReader.RLPItem; uint8 constant private _MAX_INPUT_NUM = 4; uint8 constant private _MAX_OUTPUT_NUM = 4; uint8 constant private ENCODED_LENGTH = 4; // solhint-disable-next-line func-name-mixedcase function MAX_INPUT_NUM() internal pure returns (uint8) { return _MAX_INPUT_NUM; } // solhint-disable-next-line func-name-mixedcase function MAX_OUTPUT_NUM() internal pure returns (uint8) { return _MAX_OUTPUT_NUM; } struct Transaction { uint256 txType; bytes32[] inputs; FungibleTokenOutputModel.Output[] outputs; uint256 txData; bytes32 metaData; } /** * @notice Decodes a encoded byte array into a PaymentTransaction * The following rules about the rlp-encoded transaction are enforced: * - `txType` must be an integer value with no leading zeros * - `inputs` is an list of 0 to 4 elements * - Each `input` is a 32 byte long array * - An `input` may not be all zeros * - `outputs` is an list of 0 to 4 elements * - Each `output` is a list of 2 elements: [`outputType`, `data`] * - `output.outputType` must be an integer value with no leading zeros * - See FungibleTokenOutputModel for deatils on `output.data` encoding. * - An `output` may not be null; A null output is one whose amount is zero * @param _tx An RLP-encoded transaction * @return A decoded PaymentTransaction struct */ function decode(bytes memory _tx) internal pure returns (PaymentTransactionModel.Transaction memory) { return fromGeneric(GenericTransaction.decode(_tx)); } /** * @notice Converts a GenericTransaction to a PaymentTransaction * @param genericTx A GenericTransaction.Transaction struct * @return A PaymentTransaction.Transaction struct */ function fromGeneric(GenericTransaction.Transaction memory genericTx) internal pure returns (PaymentTransactionModel.Transaction memory) { require(genericTx.inputs.length <= _MAX_INPUT_NUM, "Transaction inputs num exceeds limit"); require(genericTx.outputs.length != 0, "Transaction cannot have 0 outputs"); require(genericTx.outputs.length <= _MAX_OUTPUT_NUM, "Transaction outputs num exceeds limit"); bytes32[] memory inputs = new bytes32[](genericTx.inputs.length); for (uint i = 0; i < genericTx.inputs.length; i++) { bytes32 input = genericTx.inputs[i].toBytes32(); require(uint256(input) != 0, "Null input not allowed"); inputs[i] = input; } FungibleTokenOutputModel.Output[] memory outputs = new FungibleTokenOutputModel.Output[](genericTx.outputs.length); for (uint i = 0; i < genericTx.outputs.length; i++) { outputs[i] = FungibleTokenOutputModel.decodeOutput(genericTx.outputs[i]); } // txData is unused, it must be 0 require(genericTx.txData.toUint() == 0, "txData must be 0"); return Transaction({ txType: genericTx.txType, inputs: inputs, outputs: outputs, txData: 0, metaData: genericTx.metaData }); } /** * @notice Retrieve the 'owner' from the output, assuming the * 'outputGuard' field directly holds the owner's address */ function getOutputOwner(FungibleTokenOutputModel.Output memory output) internal pure returns (address payable) { return address(uint160(output.outputGuard)); } /** * @notice Gets output at provided index * */ function getOutput(Transaction memory transaction, uint16 outputIndex) internal pure returns (FungibleTokenOutputModel.Output memory) { require(outputIndex < transaction.outputs.length, "Output index out of bounds"); return transaction.outputs[outputIndex]; } }
Decodes a encoded byte array into a PaymentTransaction The following rules about the rlp-encoded transaction are enforced: - `txType` must be an integer value with no leading zeros - `inputs` is an list of 0 to 4 elements - Each `input` is a 32 byte long array - An `input` may not be all zeros - `outputs` is an list of 0 to 4 elements - Each `output` is a list of 2 elements: [`outputType`, `data`] - `output.outputType` must be an integer value with no leading zeros - See FungibleTokenOutputModel for deatils on `output.data` encoding. - An `output` may not be null; A null output is one whose amount is zero _tx An RLP-encoded transaction return A decoded PaymentTransaction struct/
function decode(bytes memory _tx) internal pure returns (PaymentTransactionModel.Transaction memory) { return fromGeneric(GenericTransaction.decode(_tx)); }
12,758,440
pragma solidity ^0.4.17; /* ERC20 contract interface */ /* With ERC23/ERC223 Extensions */ /* Fully backward compatible with ERC20 */ /* Recommended implementation used at https://github.com/Dexaran/ERC223-token-standard/tree/Recommended */ contract ERC20 { uint public totalSupply; // ERC223 and ERC20 functions and events function balanceOf(address who) public constant returns (uint); function totalSupply() constant public returns (uint256 _supply); function transfer(address to, uint value) public returns (bool ok); function transfer(address to, uint value, bytes data) public returns (bool ok); function transfer(address to, uint value, bytes data, string customFallback) public returns (bool ok); event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); // ERC223 functions function name() constant public returns (string _name); function symbol() constant public returns (string _symbol); function decimals() constant public returns (uint8 _decimals); // ERC20 functions and events function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); 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, uint _value); } /** * Include SafeMath Lib */ contract SafeMath { uint256 constant public MAX_UINT256 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; function safeAdd(uint256 x, uint256 y) constant internal returns (uint256 z) { if (x > MAX_UINT256 - y) revert(); return x + y; } function safeSub(uint256 x, uint256 y) constant internal returns (uint256 z) { if (x < y) { revert(); } return x - y; } function safeMul(uint256 x, uint256 y) constant internal returns (uint256 z) { if (y == 0) { return 0; } if (x > MAX_UINT256 / y) { revert(); } return x * y; } } /* * Contract that is working with ERC223 tokens */ contract ContractReceiver { struct TKN { address sender; uint value; bytes data; bytes4 sig; } function tokenFallback(address _from, uint _value, bytes _data) public { TKN memory tkn; tkn.sender = _from; tkn.value = _value; tkn.data = _data; uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24); tkn.sig = bytes4(u); /* tkn variable is analogue of msg variable of Ether transaction * tkn.sender is person who initiated this token transaction (analogue of msg.sender) * tkn.value the number of tokens that were sent (analogue of msg.value) * tkn.data is data of token transaction (analogue of msg.data) * tkn.sig is 4 bytes signature of function * if data of token transaction is a function execution */ } } /* * EDOGE is an ERC20 token with ERC223 Extensions */ contract TERATO is ERC20, SafeMath { string public name = "TERATO"; string public symbol = "TERA"; uint8 public decimals = 8; uint256 public totalSupply = 68000000 * 10**8; address public owner; bool public tokenCreated = false; mapping(address => uint256) balances; mapping(address => mapping (address => uint256)) allowed; function TERATO() public { // Security check in case EVM has future flaw or exploit to call constructor multiple times // Ensure token gets created once only require(tokenCreated == false); tokenCreated = true; owner = msg.sender; balances[owner] = totalSupply; // Final sanity check to ensure owner balance is greater than zero require(balances[owner] > 0); } modifier onlyOwner() { require(msg.sender == owner); _; } // Function to access name of token .sha function name() constant public returns (string _name) { return name; } // Function to access symbol of token . function symbol() constant public returns (string _symbol) { return symbol; } // Function to access decimals of token . function decimals() constant public returns (uint8 _decimals) { return decimals; } // Function to access total supply of tokens . function totalSupply() constant public returns (uint256 _totalSupply) { return totalSupply; } // Function that is called when a user or another contract wants to transfer funds . function transfer(address _to, uint _value, bytes _data, string _custom_fallback) public returns (bool success) { if (isContract(_to)) { if (balanceOf(msg.sender) < _value) { revert(); } balances[msg.sender] = safeSub(balanceOf(msg.sender), _value); balances[_to] = safeAdd(balanceOf(_to), _value); ContractReceiver receiver = ContractReceiver(_to); receiver.call.value(0)(bytes4(sha3(_custom_fallback)), msg.sender, _value, _data); Transfer(msg.sender, _to, _value, _data); return true; } else { return transferToAddress(_to, _value, _data); } } // Function that is called when a user or another contract wants to transfer funds . function transfer(address _to, uint _value, bytes _data) public returns (bool success) { if (isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } // Standard function transfer similar to ERC20 transfer with no _data . // Added due to backwards compatibility reasons . function transfer(address _to, uint _value) public returns (bool success) { //standard function transfer similar to ERC20 transfer with no _data //added due to backwards compatibility reasons bytes memory empty; if (isContract(_to)) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value, empty); } } // assemble the given address bytecode. If bytecode exists then the _addr is a contract. function isContract(address _addr) private returns (bool is_contract) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length > 0); } // function that is called when transaction target is an address function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) { if (balanceOf(msg.sender) < _value) { revert(); } balances[msg.sender] = safeSub(balanceOf(msg.sender), _value); balances[_to] = safeAdd(balanceOf(_to), _value); Transfer(msg.sender, _to, _value); return true; } // function that is called when transaction target is a contract function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) { if (balanceOf(msg.sender) < _value) { revert(); } balances[msg.sender] = safeSub(balanceOf(msg.sender), _value); balances[_to] = safeAdd(balanceOf(_to), _value); ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); Transfer(msg.sender, _to, _value); return true; } // Get balance of the address provided function balanceOf(address _owner) constant public returns (uint256 balance) { return balances[_owner]; } // Allow transfers if the owner provided an allowance // Prevent from any transfers if token is not yet unlocked // Use SafeMath for the main logic function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { // Protect against wrapping uints. require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]); uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] = safeAdd(balanceOf(_to), _value); balances[_from] = safeSub(balanceOf(_from), _value); if (allowance < MAX_UINT256) { allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender], _value); } Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant public returns (uint256 remaining) { return allowed[_owner][_spender]; } }
Standard function transfer similar to ERC20 transfer with no _data . Added due to backwards compatibility reasons .standard function transfer similar to ERC20 transfer with no _dataadded due to backwards compatibility reasons
function transfer(address _to, uint _value) public returns (bool success) { bytes memory empty; if (isContract(_to)) { return transferToContract(_to, _value, empty); return transferToAddress(_to, _value, empty); } }
490,081
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; import "./DirectLoanBaseMinimal.sol"; import "../../../utils/ContractKeys.sol"; /** * @title DirectLoanFixed * @author NFTfi * @notice Main contract for NFTfi Direct Loans Fixed Type. This contract manages the ability to create NFT-backed * peer-to-peer loans of type Fixed (agreed to be a fixed-repayment loan) where the borrower pays the * maximumRepaymentAmount regardless of whether they repay early or not. * * There are two ways to commence an NFT-backed loan: * * a. The borrower accepts a lender's offer by calling `acceptOffer`. * 1. the borrower calls nftContract.approveAll(NFTfi), approving the NFTfi contract to move their NFT's on their * be1alf. * 2. the lender calls erc20Contract.approve(NFTfi), allowing NFTfi to move the lender's ERC20 tokens on their * behalf. * 3. the lender signs an off-chain message, proposing its offer terms. * 4. the borrower calls `acceptOffer` to accept these terms and enter into the loan. The NFT is stored in * the contract, the borrower receives the loan principal in the specified ERC20 currency, the lender receives an * NFTfi promissory note (in ERC721 form) that represents the rights to either the principal-plus-interest, or the * underlying NFT collateral if the borrower does not pay back in time, and the borrower receives obligation receipt * (in ERC721 form) that gives them the right to pay back the loan and get the collateral back. * * b. The lender accepts a borrowe's binding terms by calling `acceptListing`. * 1. the borrower calls nftContract.approveAll(NFTfi), approving the NFTfi contract to move their NFT's on their * be1alf. * 2. the lender calls erc20Contract.approve(NFTfi), allowing NFTfi to move the lender's ERC20 tokens on their * behalf. * 3. the borrower signs an off-chain message, proposing its binding terms. * 4. the lender calls `acceptListing` with an offer matching the binding terms and enter into the loan. The NFT is * stored in the contract, the borrower receives the loan principal in the specified ERC20 currency, the lender * receives an NFTfi promissory note (in ERC721 form) that represents the rights to either the principal-plus-interest, * or the underlying NFT collateral if the borrower does not pay back in time, and the borrower receives obligation * receipt (in ERC721 form) that gives them the right to pay back the loan and get the collateral back. * * The lender can freely transfer and trade this ERC721 promissory note as they wish, with the knowledge that * transferring the ERC721 promissory note tranfsers the rights to principal-plus-interest and/or collateral, and that * they will no longer have a claim on the loan. The ERC721 promissory note itself represents that claim. * * The borrower can freely transfer and trade this ERC721 obligaiton receipt as they wish, with the knowledge that * transferring the ERC721 obligaiton receipt tranfsers the rights right to pay back the loan and get the collateral * back. * * * A loan may end in one of two ways: * - First, a borrower may call NFTfi.payBackLoan() and pay back the loan plus interest at any time, in which case they * receive their NFT back in the same transaction. * - Second, if the loan's duration has passed and the loan has not been paid back yet, a lender can call * NFTfi.liquidateOverdueLoan(), in which case they receive the underlying NFT collateral and forfeit the rights to the * principal-plus-interest, which the borrower now keeps. */ contract DirectLoanFixedOffer is DirectLoanBaseMinimal { /* ********** */ /* DATA TYPES */ /* ********** */ bytes32 public constant LOAN_TYPE = bytes32("DIRECT_LOAN_FIXED_OFFER"); /* *********** */ /* CONSTRUCTOR */ /* *********** */ /** * @dev Sets `hub` and permitted erc20-s * * @param _admin - Initial admin of this contract. * @param _nftfiHub - NFTfiHub address * @param _permittedErc20s - list of permitted ERC20 token contract addresses */ constructor( address _admin, address _nftfiHub, address[] memory _permittedErc20s ) DirectLoanBaseMinimal( _admin, _nftfiHub, ContractKeys.getIdFromStringKey("DIRECT_LOAN_COORDINATOR"), _permittedErc20s ) { // solhint-disable-previous-line no-empty-blocks } /* ********* */ /* FUNCTIONS */ /* ********* */ /** * @notice This function is called by the borrower when accepting a lender's offer to begin a loan. * * @param _offer - The offer made by the lender. * @param _signature - The components of the lender's signature. * @param _borrowerSettings - Some extra parameters that the borrower needs to set when accepting an offer. */ function acceptOffer( Offer memory _offer, Signature memory _signature, BorrowerSettings memory _borrowerSettings ) external whenNotPaused nonReentrant { address nftWrapper = _getWrapper(_offer.nftCollateralContract); _loanSanityChecks(_offer, nftWrapper); _loanSanityChecksOffer(_offer); _acceptOffer( LOAN_TYPE, _setupLoanTerms(_offer, nftWrapper), _setupLoanExtras(_borrowerSettings.revenueSharePartner, _borrowerSettings.referralFeeInBasisPoints), _offer, _signature ); } /* ******************* */ /* READ-ONLY FUNCTIONS */ /* ******************* */ /** * @notice This function can be used to view the current quantity of the ERC20 currency used in the specified loan * required by the borrower to repay their loan, measured in the smallest unit of the ERC20 currency. * * @param _loanId A unique identifier for this particular loan, sourced from the Loan Coordinator. * * @return The amount of the specified ERC20 currency required to pay back this loan, measured in the smallest unit * of the specified ERC20 currency. */ function getPayoffAmount(uint32 _loanId) external view override returns (uint256) { LoanTerms storage loan = loanIdToLoan[_loanId]; return loan.maximumRepaymentAmount; } /* ****************** */ /* INTERNAL FUNCTIONS */ /* ****************** */ /** * @notice This function is called by the borrower when accepting a lender's offer to begin a loan. * * @param _loanType - The loan type being created. * @param _loanTerms - The main Loan Terms struct. This data is saved upon loan creation on loanIdToLoan. * @param _loanExtras - The main Loan Terms struct. This data is saved upon loan creation on loanIdToLoanExtras. * @param _offer - The offer made by the lender. * @param _signature - The components of the lender's signature. */ function _acceptOffer( bytes32 _loanType, LoanTerms memory _loanTerms, LoanExtras memory _loanExtras, Offer memory _offer, Signature memory _signature ) internal { // Check loan nonces. These are different from Ethereum account nonces. // Here, these are uint256 numbers that should uniquely identify // each signature for each user (i.e. each user should only create one // off-chain signature for each nonce, with a nonce being any arbitrary // uint256 value that they have not used yet for an off-chain NFTfi // signature). require(!_nonceHasBeenUsedForUser[_signature.signer][_signature.nonce], "Lender nonce invalid"); _nonceHasBeenUsedForUser[_signature.signer][_signature.nonce] = true; require(NFTfiSigningUtils.isValidLenderSignature(_offer, _signature), "Lender signature is invalid"); address bundle = hub.getContract(ContractKeys.NFTFI_BUNDLER); require(_loanTerms.nftCollateralContract != bundle, "Collateral cannot be bundle"); uint32 loanId = _createLoan(_loanType, _loanTerms, _loanExtras, msg.sender, _signature.signer, _offer.referrer); // Emit an event with all relevant details from this transaction. emit LoanStarted(loanId, msg.sender, _signature.signer, _loanTerms, _loanExtras); } /** * @dev Creates a `LoanTerms` struct using data sent as the lender's `_offer` on `acceptOffer`. * This is needed in order to avoid stack too deep issues. * Since this is a Fixed loan type loanInterestRateForDurationInBasisPoints is ignored. */ function _setupLoanTerms(Offer memory _offer, address _nftWrapper) internal view returns (LoanTerms memory) { return LoanTerms({ loanERC20Denomination: _offer.loanERC20Denomination, loanPrincipalAmount: _offer.loanPrincipalAmount, maximumRepaymentAmount: _offer.maximumRepaymentAmount, nftCollateralContract: _offer.nftCollateralContract, nftCollateralWrapper: _nftWrapper, nftCollateralId: _offer.nftCollateralId, loanStartTime: uint64(block.timestamp), loanDuration: _offer.loanDuration, loanInterestRateForDurationInBasisPoints: uint16(0), loanAdminFeeInBasisPoints: _offer.loanAdminFeeInBasisPoints, borrower: msg.sender }); } /** * @dev Calculates the payoff amount and admin fee * * @param _loanTerms - Struct containing all the loan's parameters */ function _payoffAndFee(LoanTerms memory _loanTerms) internal pure override returns (uint256 adminFee, uint256 payoffAmount) { // Calculate amounts to send to lender and admins uint256 interestDue = _loanTerms.maximumRepaymentAmount - _loanTerms.loanPrincipalAmount; adminFee = LoanChecksAndCalculations.computeAdminFee( interestDue, uint256(_loanTerms.loanAdminFeeInBasisPoints) ); payoffAmount = _loanTerms.maximumRepaymentAmount - adminFee; } /** * @dev Function that performs some validation checks over loan parameters when accepting an offer * */ function _loanSanityChecksOffer(LoanData.Offer memory _offer) internal pure { require( _offer.maximumRepaymentAmount >= _offer.loanPrincipalAmount, "Negative interest rate loans are not allowed." ); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; import "./IDirectLoanBase.sol"; import "./LoanData.sol"; import "./LoanChecksAndCalculations.sol"; import "./LoanAirdropUtils.sol"; import "../../BaseLoan.sol"; import "../../../utils/NftReceiver.sol"; import "../../../utils/NFTfiSigningUtils.sol"; import "../../../interfaces/INftfiHub.sol"; import "../../../utils/ContractKeys.sol"; import "../../../interfaces/IDirectLoanCoordinator.sol"; import "../../../interfaces/INftWrapper.sol"; import "../../../interfaces/IPermittedPartners.sol"; import "../../../interfaces/IPermittedERC20s.sol"; import "../../../interfaces/IPermittedNFTs.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /** * @title DirectLoanBase * @author NFTfi * @notice Main contract for NFTfi Direct Loans Type. This contract manages the ability to create NFT-backed * peer-to-peer loans. * * There are two ways to commence an NFT-backed loan: * * a. The borrower accepts a lender's offer by calling `acceptOffer`. * 1. the borrower calls nftContract.approveAll(NFTfi), approving the NFTfi contract to move their NFT's on their * be1alf. * 2. the lender calls erc20Contract.approve(NFTfi), allowing NFTfi to move the lender's ERC20 tokens on their * behalf. * 3. the lender signs an off-chain message, proposing its offer terms. * 4. the borrower calls `acceptOffer` to accept these terms and enter into the loan. The NFT is stored in * the contract, the borrower receives the loan principal in the specified ERC20 currency, the lender receives an * NFTfi promissory note (in ERC721 form) that represents the rights to either the principal-plus-interest, or the * underlying NFT collateral if the borrower does not pay back in time, and the borrower receives obligation receipt * (in ERC721 form) that gives them the right to pay back the loan and get the collateral back. * * b. The lender accepts a borrowe's binding terms by calling `acceptListing`. * 1. the borrower calls nftContract.approveAll(NFTfi), approving the NFTfi contract to move their NFT's on their * be1alf. * 2. the lender calls erc20Contract.approve(NFTfi), allowing NFTfi to move the lender's ERC20 tokens on their * behalf. * 3. the borrower signs an off-chain message, proposing its binding terms. * 4. the lender calls `acceptListing` with an offer matching the binding terms and enter into the loan. The NFT is * stored in the contract, the borrower receives the loan principal in the specified ERC20 currency, the lender * receives an NFTfi promissory note (in ERC721 form) that represents the rights to either the principal-plus-interest, * or the underlying NFT collateral if the borrower does not pay back in time, and the borrower receives obligation * receipt (in ERC721 form) that gives them the right to pay back the loan and get the collateral back. * * The lender can freely transfer and trade this ERC721 promissory note as they wish, with the knowledge that * transferring the ERC721 promissory note tranfsers the rights to principal-plus-interest and/or collateral, and that * they will no longer have a claim on the loan. The ERC721 promissory note itself represents that claim. * * The borrower can freely transfer and trade this ERC721 obligaiton receipt as they wish, with the knowledge that * transferring the ERC721 obligaiton receipt tranfsers the rights right to pay back the loan and get the collateral * back. * * A loan may end in one of two ways: * - First, a borrower may call NFTfi.payBackLoan() and pay back the loan plus interest at any time, in which case they * receive their NFT back in the same transaction. * - Second, if the loan's duration has passed and the loan has not been paid back yet, a lender can call * NFTfi.liquidateOverdueLoan(), in which case they receive the underlying NFT collateral and forfeit the rights to the * principal-plus-interest, which the borrower now keeps. * * * If the loan was created as a ProRated type loan (pro-rata interest loan), then the user only pays the principal plus * pro-rata interest if repaid early. * However, if the loan was was created as a Fixed type loan (agreed to be a fixed-repayment loan), then the borrower * pays the maximumRepaymentAmount regardless of whether they repay early or not. * */ abstract contract DirectLoanBaseMinimal is IDirectLoanBase, IPermittedERC20s, BaseLoan, NftReceiver, LoanData { using SafeERC20 for IERC20; /* ******* */ /* STORAGE */ /* ******* */ uint16 public constant HUNDRED_PERCENT = 10000; bytes32 public immutable override LOAN_COORDINATOR; /** * @notice The maximum duration of any loan started for this loan type, measured in seconds. This is both a * sanity-check for borrowers and an upper limit on how long admins will have to support v1 of this contract if they * eventually deprecate it, as well as a check to ensure that the loan duration never exceeds the space alotted for * it in the loan struct. */ uint256 public override maximumLoanDuration = 53 weeks; /** * @notice The percentage of interest earned by lenders on this platform that is taken by the contract admin's as a * fee, measured in basis points (hundreths of a percent). The max allowed value is 10000. */ uint16 public override adminFeeInBasisPoints = 25; /** * @notice A mapping from a loan's identifier to the loan's details, represted by the loan struct. */ mapping(uint32 => LoanTerms) public override loanIdToLoan; mapping(uint32 => LoanExtras) public loanIdToLoanExtras; /** * @notice A mapping tracking whether a loan has either been repaid or liquidated. This prevents an attacker trying * to repay or liquidate the same loan twice. */ mapping(uint32 => bool) public override loanRepaidOrLiquidated; /** * @dev keeps track of tokens being held as loan collateral, so we dont allow these * to be transferred with the aridrop draining functions */ mapping(address => mapping(uint256 => uint256)) private _escrowTokens; /** * @notice A mapping that takes both a user's address and a loan nonce that was first used when signing an off-chain * order and checks whether that nonce has previously either been used for a loan, or has been pre-emptively * cancelled. The nonce referred to here is not the same as an Ethereum account's nonce. We are referring instead to * nonces that are used by both the lender and the borrower when they are first signing off-chain NFTfi orders. * * These nonces can be any uint256 value that the user has not previously used to sign an off-chain order. Each * nonce can be used at most once per user within NFTfi, regardless of whether they are the lender or the borrower * in that situation. This serves two purposes. First, it prevents replay attacks where an attacker would submit a * user's off-chain order more than once. Second, it allows a user to cancel an off-chain order by calling * NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the nonce as used and prevents any future loan from * using the user's off-chain order that contains that nonce. */ mapping(address => mapping(uint256 => bool)) internal _nonceHasBeenUsedForUser; /** * @notice A mapping from an ERC20 currency address to whether that currency * is permitted to be used by this contract. */ mapping(address => bool) private erc20Permits; INftfiHub public immutable hub; /* ****** */ /* EVENTS */ /* ****** */ /** * @notice This event is fired whenever the admins change the percent of interest rates earned that they charge as a * fee. Note that newAdminFee can never exceed 10,000, since the fee is measured in basis points. * * @param newAdminFee - The new admin fee measured in basis points. This is a percent of the interest paid upon a * loan's completion that go to the contract admins. */ event AdminFeeUpdated(uint16 newAdminFee); /** * @notice This event is fired whenever the admins change the maximum duration of any loan started for this loan * type. * * @param newMaximumLoanDuration - The new maximum duration. */ event MaximumLoanDurationUpdated(uint256 newMaximumLoanDuration); /** * @notice This event is fired whenever a borrower begins a loan by calling NFTfi.beginLoan(), which can only occur * after both the lender and borrower have approved their ERC721 and ERC20 contracts to use NFTfi, and when they * both have signed off-chain messages that agree on the terms of the loan. * * @param loanId - A unique identifier for this particular loan, sourced from the Loan Coordinator. * @param borrower - The address of the borrower. * @param lender - The address of the lender. The lender can change their address by transferring the NFTfi ERC721 * token that they received when the loan began. */ event LoanStarted( uint32 indexed loanId, address indexed borrower, address indexed lender, LoanTerms loanTerms, LoanExtras loanExtras ); /** * @notice This event is fired whenever a borrower successfully repays their loan, paying * principal-plus-interest-minus-fee to the lender in loanERC20Denomination, paying fee to owner in * loanERC20Denomination, and receiving their NFT collateral back. * * @param loanId - A unique identifier for this particular loan, sourced from the Loan Coordinator. * @param borrower - The address of the borrower. * @param lender - The address of the lender. The lender can change their address by transferring the NFTfi ERC721 * token that they received when the loan began. * @param loanPrincipalAmount - The original sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * @param nftCollateralId - The ID within the NFTCollateralContract for the NFT being used as collateral for this * loan. The NFT is stored within this contract during the duration of the loan. * @param amountPaidToLender The amount of ERC20 that the borrower paid to the lender, measured in the smalled * units of loanERC20Denomination. * @param adminFee The amount of interest paid to the contract admins, measured in the smalled units of * loanERC20Denomination and determined by adminFeeInBasisPoints. This amount never exceeds the amount of interest * earned. * @param revenueShare The amount taken from admin fee amount shared with the partner. * @param revenueSharePartner - The address of the partner that will receive the revenue share. * @param nftCollateralContract - The ERC721 contract of the NFT collateral * @param loanERC20Denomination - The ERC20 contract of the currency being used as principal/interest for this * loan. */ event LoanRepaid( uint32 indexed loanId, address indexed borrower, address indexed lender, uint256 loanPrincipalAmount, uint256 nftCollateralId, uint256 amountPaidToLender, uint256 adminFee, uint256 revenueShare, address revenueSharePartner, address nftCollateralContract, address loanERC20Denomination ); /** * @notice This event is fired whenever a lender liquidates an outstanding loan that is owned to them that has * exceeded its duration. The lender receives the underlying NFT collateral, and the borrower no longer needs to * repay the loan principal-plus-interest. * * @param loanId - A unique identifier for this particular loan, sourced from the Loan Coordinator. * @param borrower - The address of the borrower. * @param lender - The address of the lender. The lender can change their address by transferring the NFTfi ERC721 * token that they received when the loan began. * @param loanPrincipalAmount - The original sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * @param nftCollateralId - The ID within the NFTCollateralContract for the NFT being used as collateral for this * loan. The NFT is stored within this contract during the duration of the loan. * @param loanMaturityDate - The unix time (measured in seconds) that the loan became due and was eligible for * liquidation. * @param loanLiquidationDate - The unix time (measured in seconds) that liquidation occurred. * @param nftCollateralContract - The ERC721 contract of the NFT collateral */ event LoanLiquidated( uint32 indexed loanId, address indexed borrower, address indexed lender, uint256 loanPrincipalAmount, uint256 nftCollateralId, uint256 loanMaturityDate, uint256 loanLiquidationDate, address nftCollateralContract ); /** * @notice This event is fired when some of the terms of a loan are being renegotiated. * * @param loanId - The unique identifier for the loan to be renegotiated * @param newLoanDuration - The new amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * @param newMaximumRepaymentAmount - The new maximum amount of money that the borrower would be required to * retrieve their collateral, measured in the smallest units of the ERC20 currency used for the loan. The * borrower will always have to pay this amount to retrieve their collateral, regardless of whether they repay * early. * @param renegotiationFee Agreed upon fee in loan denomination that borrower pays for the lender for the * renegotiation, has to be paid with an ERC20 transfer loanERC20Denomination token, uses transfer from, * frontend will have to propmt an erc20 approve for this from the borrower to the lender * @param renegotiationAdminFee renegotiationFee admin portion based on determined by adminFeeInBasisPoints */ event LoanRenegotiated( uint32 indexed loanId, address indexed borrower, address indexed lender, uint32 newLoanDuration, uint256 newMaximumRepaymentAmount, uint256 renegotiationFee, uint256 renegotiationAdminFee ); /** * @notice This event is fired whenever the admin sets a ERC20 permit. * * @param erc20Contract - Address of the ERC20 contract. * @param isPermitted - Signals ERC20 permit. */ event ERC20Permit(address indexed erc20Contract, bool isPermitted); /* *********** */ /* CONSTRUCTOR */ /* *********** */ /** * @dev Sets `hub` * * @param _admin - Initial admin of this contract. * @param _nftfiHub - NFTfiHub address * @param _loanCoordinatorKey - * @param _permittedErc20s - */ constructor( address _admin, address _nftfiHub, bytes32 _loanCoordinatorKey, address[] memory _permittedErc20s ) BaseLoan(_admin) { hub = INftfiHub(_nftfiHub); LOAN_COORDINATOR = _loanCoordinatorKey; for (uint256 i = 0; i < _permittedErc20s.length; i++) { _setERC20Permit(_permittedErc20s[i], true); } } /* *************** */ /* ADMIN FUNCTIONS */ /* *************** */ /** * @notice This function can be called by admins to change the maximumLoanDuration. Note that they can never change * maximumLoanDuration to be greater than UINT32_MAX, since that's the maximum space alotted for the duration in the * loan struct. * * @param _newMaximumLoanDuration - The new maximum loan duration, measured in seconds. */ function updateMaximumLoanDuration(uint256 _newMaximumLoanDuration) external onlyOwner { require(_newMaximumLoanDuration <= uint256(type(uint32).max), "Loan duration overflow"); maximumLoanDuration = _newMaximumLoanDuration; emit MaximumLoanDurationUpdated(_newMaximumLoanDuration); } /** * @notice This function can be called by admins to change the percent of interest rates earned that they charge as * a fee. Note that newAdminFee can never exceed 10,000, since the fee is measured in basis points. * * @param _newAdminFeeInBasisPoints - The new admin fee measured in basis points. This is a percent of the interest * paid upon a loan's completion that go to the contract admins. */ function updateAdminFee(uint16 _newAdminFeeInBasisPoints) external onlyOwner { require(_newAdminFeeInBasisPoints <= HUNDRED_PERCENT, "basis points > 10000"); adminFeeInBasisPoints = _newAdminFeeInBasisPoints; emit AdminFeeUpdated(_newAdminFeeInBasisPoints); } /** * @notice used by the owner account to be able to drain ERC20 tokens received as airdrops * for the locked collateral NFT-s * @param _tokenAddress - address of the token contract for the token to be sent out * @param _receiver - receiver of the token */ function drainERC20Airdrop(address _tokenAddress, address _receiver) external onlyOwner { IERC20 tokenContract = IERC20(_tokenAddress); uint256 amount = tokenContract.balanceOf(address(this)); require(amount > 0, "no tokens owned"); tokenContract.safeTransfer(_receiver, amount); } /** * @notice This function can be called by admins to change the permitted status of an ERC20 currency. This includes * both adding an ERC20 currency to the permitted list and removing it. * * @param _erc20 - The address of the ERC20 currency whose permit list status changed. * @param _permit - The new status of whether the currency is permitted or not. */ function setERC20Permit(address _erc20, bool _permit) external onlyOwner { _setERC20Permit(_erc20, _permit); } /** * @notice This function can be called by admins to change the permitted status of a batch of ERC20 currency. This * includes both adding an ERC20 currency to the permitted list and removing it. * * @param _erc20s - The addresses of the ERC20 currencies whose permit list status changed. * @param _permits - The new statuses of whether the currency is permitted or not. */ function setERC20Permits(address[] memory _erc20s, bool[] memory _permits) external onlyOwner { require(_erc20s.length == _permits.length, "setERC20Permits function information arity mismatch"); for (uint256 i = 0; i < _erc20s.length; i++) { _setERC20Permit(_erc20s[i], _permits[i]); } } /** * @notice used by the owner account to be able to drain ERC721 tokens received as airdrops * for the locked collateral NFT-s * @param _tokenAddress - address of the token contract for the token to be sent out * @param _tokenId - id token to be sent out * @param _receiver - receiver of the token */ function drainERC721Airdrop( address _tokenAddress, uint256 _tokenId, address _receiver ) external onlyOwner { IERC721 tokenContract = IERC721(_tokenAddress); require(_escrowTokens[_tokenAddress][_tokenId] == 0, "token is collateral"); require(tokenContract.ownerOf(_tokenId) == address(this), "nft not owned"); tokenContract.safeTransferFrom(address(this), _receiver, _tokenId); } /** * @notice used by the owner account to be able to drain ERC1155 tokens received as airdrops * for the locked collateral NFT-s * @param _tokenAddress - address of the token contract for the token to be sent out * @param _tokenId - id token to be sent out * @param _receiver - receiver of the token */ function drainERC1155Airdrop( address _tokenAddress, uint256 _tokenId, address _receiver ) external onlyOwner { IERC1155 tokenContract = IERC1155(_tokenAddress); uint256 amount = tokenContract.balanceOf(address(this), _tokenId); require(_escrowTokens[_tokenAddress][_tokenId] == 0, "token is collateral"); require(amount > 0, "no nfts owned"); tokenContract.safeTransferFrom(address(this), _receiver, _tokenId, amount, ""); } function mintObligationReceipt(uint32 _loanId) external nonReentrant { address borrower = loanIdToLoan[_loanId].borrower; require(msg.sender == borrower, "sender has to be borrower"); IDirectLoanCoordinator loanCoordinator = IDirectLoanCoordinator(hub.getContract(LOAN_COORDINATOR)); loanCoordinator.mintObligationReceipt(_loanId, borrower); delete loanIdToLoan[_loanId].borrower; } /** * @dev makes possible to change loan duration and max repayment amount, loan duration even can be extended if * loan was expired but not liquidated. * * @param _loanId - The unique identifier for the loan to be renegotiated * @param _newLoanDuration - The new amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * @param _newMaximumRepaymentAmount - The new maximum amount of money that the borrower would be required to * retrieve their collateral, measured in the smallest units of the ERC20 currency used for the loan. The * borrower will always have to pay this amount to retrieve their collateral, regardless of whether they repay * early. * @param _renegotiationFee Agreed upon fee in ether that borrower pays for the lender for the renegitiation * @param _lenderNonce - The nonce referred to here is not the same as an Ethereum account's nonce. We are * referring instead to nonces that are used by both the lender and the borrower when they are first signing * off-chain NFTfi orders. These nonces can be any uint256 value that the user has not previously used to sign an * off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the * lender or the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling NFTfi.cancelLoanCommitmentBeforeLoanHasBegun() * , which marks the nonce as used and prevents any future loan from using the user's off-chain order that contains * that nonce. * @param _expiry - The date when the renegotiation offer expires * @param _lenderSignature - The ECDSA signature of the lender, obtained off-chain ahead of time, signing the * following combination of parameters: * - _loanId * - _newLoanDuration * - _newMaximumRepaymentAmount * - _lender * - _expiry * - address of this contract * - chainId */ function renegotiateLoan( uint32 _loanId, uint32 _newLoanDuration, uint256 _newMaximumRepaymentAmount, uint256 _renegotiationFee, uint256 _lenderNonce, uint256 _expiry, bytes memory _lenderSignature ) external whenNotPaused nonReentrant { _renegotiateLoan( _loanId, _newLoanDuration, _newMaximumRepaymentAmount, _renegotiationFee, _lenderNonce, _expiry, _lenderSignature ); } /** * @notice This function is called by a anyone to repay a loan. It can be called at any time after the loan has * begun and before loan expiry.. The caller will pay a pro-rata portion of their interest if the loan is paid off * early and the loan is pro-rated type, but the complete repayment amount if it is fixed type. * The the borrower (current owner of the obligation note) will get the collaterl NFT back. * * This function is purposefully not pausable in order to prevent an attack where the contract admin's pause the * contract and hold hostage the NFT's that are still within it. * * @param _loanId A unique identifier for this particular loan, sourced from the Loan Coordinator. */ function payBackLoan(uint32 _loanId) external nonReentrant { LoanChecksAndCalculations.payBackChecks(_loanId, hub); ( address borrower, address lender, LoanTerms memory loan, IDirectLoanCoordinator loanCoordinator ) = _getPartiesAndData(_loanId); _payBackLoan(_loanId, borrower, lender, loan); _resolveLoan(_loanId, borrower, loan, loanCoordinator); // Delete the loan from storage in order to achieve a substantial gas savings and to lessen the burden of // storage on Ethereum nodes, since we will never access this loan's details again, and the details are still // available through event data. delete loanIdToLoan[_loanId]; delete loanIdToLoanExtras[_loanId]; } /** * @notice This function is called by a lender once a loan has finished its duration and the borrower still has not * repaid. The lender can call this function to seize the underlying NFT collateral, although the lender gives up * all rights to the principal-plus-collateral by doing so. * * This function is purposefully not pausable in order to prevent an attack where the contract admin's pause * the contract and hold hostage the NFT's that are still within it. * * We intentionally allow anybody to call this function, although only the lender will end up receiving the seized * collateral. We are exploring the possbility of incentivizing users to call this function by using some of the * admin funds. * * @param _loanId A unique identifier for this particular loan, sourced from the Loan Coordinator. */ function liquidateOverdueLoan(uint32 _loanId) external nonReentrant { LoanChecksAndCalculations.checkLoanIdValidity(_loanId, hub); // Sanity check that payBackLoan() and liquidateOverdueLoan() have never been called on this loanId. // Depending on how the rest of the code turns out, this check may be unnecessary. require(!loanRepaidOrLiquidated[_loanId], "Loan already repaid/liquidated"); ( address borrower, address lender, LoanTerms memory loan, IDirectLoanCoordinator loanCoordinator ) = _getPartiesAndData(_loanId); // Ensure that the loan is indeed overdue, since we can only liquidate overdue loans. uint256 loanMaturityDate = uint256(loan.loanStartTime) + uint256(loan.loanDuration); require(block.timestamp > loanMaturityDate, "Loan is not overdue yet"); require(msg.sender == lender, "Only lender can liquidate"); _resolveLoan(_loanId, lender, loan, loanCoordinator); // Emit an event with all relevant details from this transaction. emit LoanLiquidated( _loanId, borrower, lender, loan.loanPrincipalAmount, loan.nftCollateralId, loanMaturityDate, block.timestamp, loan.nftCollateralContract ); // Delete the loan from storage in order to achieve a substantial gas savings and to lessen the burden of // storage on Ethereum nodes, since we will never access this loan's details again, and the details are still // available through event data. delete loanIdToLoan[_loanId]; delete loanIdToLoanExtras[_loanId]; } /** * @notice this function initiates a flashloan to pull an airdrop from a tartget contract * * @param _loanId - * @param _target - address of the airdropping contract * @param _data - function selector to be called on the airdropping contract * @param _nftAirdrop - address of the used claiming nft in the drop * @param _nftAirdropId - id of the used claiming nft in the drop * @param _is1155 - * @param _nftAirdropAmount - amount in case of 1155 */ function pullAirdrop( uint32 _loanId, address _target, bytes calldata _data, address _nftAirdrop, uint256 _nftAirdropId, bool _is1155, uint256 _nftAirdropAmount ) external nonReentrant { LoanChecksAndCalculations.checkLoanIdValidity(_loanId, hub); require(!loanRepaidOrLiquidated[_loanId], "Loan already repaid/liquidated"); LoanTerms memory loan = loanIdToLoan[_loanId]; LoanAirdropUtils.pullAirdrop( _loanId, loan, _target, _data, _nftAirdrop, _nftAirdropId, _is1155, _nftAirdropAmount, hub ); } /** * @notice this function creates a proxy contract wrapping the collateral to be able to catch an expected airdrop * * @param _loanId - */ function wrapCollateral(uint32 _loanId) external nonReentrant { LoanChecksAndCalculations.checkLoanIdValidity(_loanId, hub); require(!loanRepaidOrLiquidated[_loanId], "Loan already repaid/liquidated"); LoanTerms storage loan = loanIdToLoan[_loanId]; _escrowTokens[loan.nftCollateralContract][loan.nftCollateralId] -= 1; (address instance, uint256 receiverId) = LoanAirdropUtils.wrapCollateral(_loanId, loan, hub); _escrowTokens[instance][receiverId] += 1; } /** * @notice This function can be called by either a lender or a borrower to cancel all off-chain orders that they * have signed that contain this nonce. If the off-chain orders were created correctly, there should only be one * off-chain order that contains this nonce at all. * * The nonce referred to here is not the same as an Ethereum account's nonce. We are referring * instead to nonces that are used by both the lender and the borrower when they are first signing off-chain NFTfi * orders. These nonces can be any uint256 value that the user has not previously used to sign an off-chain order. * Each nonce can be used at most once per user within NFTfi, regardless of whether they are the lender or the * borrower in that situation. This serves two purposes. First, it prevents replay attacks where an attacker would * submit a user's off-chain order more than once. Second, it allows a user to cancel an off-chain order by calling * NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the nonce as used and prevents any future loan from * using the user's off-chain order that contains that nonce. * * @param _nonce - User nonce */ function cancelLoanCommitmentBeforeLoanHasBegun(uint256 _nonce) external { require(!_nonceHasBeenUsedForUser[msg.sender][_nonce], "Invalid nonce"); _nonceHasBeenUsedForUser[msg.sender][_nonce] = true; } /* ******************* */ /* READ-ONLY FUNCTIONS */ /* ******************* */ /** * @notice This function can be used to view the current quantity of the ERC20 currency used in the specified loan * required by the borrower to repay their loan, measured in the smallest unit of the ERC20 currency. * * @param _loanId A unique identifier for this particular loan, sourced from the Loan Coordinator. * * @return The amount of the specified ERC20 currency required to pay back this loan, measured in the smallest unit * of the specified ERC20 currency. */ function getPayoffAmount(uint32 _loanId) external view virtual returns (uint256); /** * @notice This function can be used to view whether a particular nonce for a particular user has already been used, * either from a successful loan or a cancelled off-chain order. * * @param _user - The address of the user. This function works for both lenders and borrowers alike. * @param _nonce - The nonce referred to here is not the same as an Ethereum account's nonce. We are referring * instead to nonces that are used by both the lender and the borrower when they are first signing off-chain * NFTfi orders. These nonces can be any uint256 value that the user has not previously used to sign an off-chain * order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the lender or * the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling NFTfi.cancelLoanCommitmentBeforeLoanHasBegun() * , which marks the nonce as used and prevents any future loan from using the user's off-chain order that contains * that nonce. * * @return A bool representing whether or not this nonce has been used for this user. */ function getWhetherNonceHasBeenUsedForUser(address _user, uint256 _nonce) external view override returns (bool) { return _nonceHasBeenUsedForUser[_user][_nonce]; } /** * @notice This function can be called by anyone to get the permit associated with the erc20 contract. * * @param _erc20 - The address of the erc20 contract. * * @return Returns whether the erc20 is permitted */ function getERC20Permit(address _erc20) public view override returns (bool) { return erc20Permits[_erc20]; } /* ****************** */ /* INTERNAL FUNCTIONS */ /* ****************** */ /** * @dev makes possible to change loan duration and max repayment amount, loan duration even can be extended if * loan was expired but not liquidated. IMPORTANT: Frontend will have to propt the caller to do an ERC20 approve for * the fee amount from themselves (borrower/obligation reciept holder) to the lender (promissory note holder) * * @param _loanId - The unique identifier for the loan to be renegotiated * @param _newLoanDuration - The new amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * @param _newMaximumRepaymentAmount - The new maximum amount of money that the borrower would be required to * retrieve their collateral, measured in the smallest units of the ERC20 currency used for the loan. The * borrower will always have to pay this amount to retrieve their collateral, regardless of whether they repay * early. * @param _renegotiationFee Agreed upon fee in loan denomination that borrower pays for the lender and * the admin for the renegotiation, has to be paid with an ERC20 transfer loanERC20Denomination token, * uses transfer from, frontend will have to propmt an erc20 approve for this from the borrower to the lender, * admin fee is calculated by the loan's loanAdminFeeInBasisPoints value * @param _lenderNonce - The nonce referred to here is not the same as an Ethereum account's nonce. We are * referring instead to nonces that are used by both the lender and the borrower when they are first signing * off-chain NFTfi orders. These nonces can be any uint256 value that the user has not previously used to sign an * off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the * lender or the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling NFTfi.cancelLoanCommitmentBeforeLoanHasBegun() , which marks the nonce as used and prevents any future loan from using the user's off-chain order that contains * that nonce. * @param _expiry - The date when the renegotiation offer expires * @param _lenderSignature - The ECDSA signature of the lender, obtained off-chain ahead of time, signing the * following combination of parameters: * - _loanId * - _newLoanDuration * - _newMaximumRepaymentAmount * - _lender * - _expiry * - address of this contract * - chainId */ function _renegotiateLoan( uint32 _loanId, uint32 _newLoanDuration, uint256 _newMaximumRepaymentAmount, uint256 _renegotiationFee, uint256 _lenderNonce, uint256 _expiry, bytes memory _lenderSignature ) internal { LoanTerms storage loan = loanIdToLoan[_loanId]; (address borrower, address lender) = LoanChecksAndCalculations.renegotiationChecks( loan, _loanId, _newLoanDuration, _newMaximumRepaymentAmount, _lenderNonce, hub ); _nonceHasBeenUsedForUser[lender][_lenderNonce] = true; require( NFTfiSigningUtils.isValidLenderRenegotiationSignature( _loanId, _newLoanDuration, _newMaximumRepaymentAmount, _renegotiationFee, Signature({signer: lender, nonce: _lenderNonce, expiry: _expiry, signature: _lenderSignature}) ), "Renegotiation signature is invalid" ); uint256 renegotiationAdminFee; /** * @notice Transfers fee to the lender immediately * @dev implements Checks-Effects-Interactions pattern by modifying state only after * the transfer happened successfully, we also add the nonReentrant modifier to * the pbulic versions */ if (_renegotiationFee > 0) { renegotiationAdminFee = LoanChecksAndCalculations.computeAdminFee( _renegotiationFee, loan.loanAdminFeeInBasisPoints ); // Transfer principal-plus-interest-minus-fees from the caller (always has to be borrower) to lender IERC20(loan.loanERC20Denomination).safeTransferFrom( borrower, lender, _renegotiationFee - renegotiationAdminFee ); // Transfer fees from the caller (always has to be borrower) to admins IERC20(loan.loanERC20Denomination).safeTransferFrom(borrower, owner(), renegotiationAdminFee); } loan.loanDuration = _newLoanDuration; loan.maximumRepaymentAmount = _newMaximumRepaymentAmount; emit LoanRenegotiated( _loanId, borrower, lender, _newLoanDuration, _newMaximumRepaymentAmount, _renegotiationFee, renegotiationAdminFee ); } /** * @dev Transfer collateral NFT from borrower to this contract and principal from lender to the borrower and * registers the new loan through the loan coordinator. * * @param _loanType - The type of loan it is being created * @param _loanTerms - Struct containing the loan's settings * @param _loanExtras - Struct containing some loan's extra settings, needed to avoid stack too deep * @param _lender - The address of the lender. * @param _referrer - The address of the referrer who found the lender matching the listing, Zero address to signal * that there is no referrer. */ function _createLoan( bytes32 _loanType, LoanTerms memory _loanTerms, LoanExtras memory _loanExtras, address _borrower, address _lender, address _referrer ) internal returns (uint32) { // Transfer collateral from borrower to this contract to be held until // loan completion. _transferNFT(_loanTerms, _borrower, address(this)); return _createLoanNoNftTransfer(_loanType, _loanTerms, _loanExtras, _borrower, _lender, _referrer); } /** * @dev Transfer principal from lender to the borrower and * registers the new loan through the loan coordinator. * * @param _loanType - The type of loan it is being created * @param _loanTerms - Struct containing the loan's settings * @param _loanExtras - Struct containing some loan's extra settings, needed to avoid stack too deep * @param _lender - The address of the lender. * @param _referrer - The address of the referrer who found the lender matching the listing, Zero address to signal * that there is no referrer. */ function _createLoanNoNftTransfer( bytes32 _loanType, LoanTerms memory _loanTerms, LoanExtras memory _loanExtras, address _borrower, address _lender, address _referrer ) internal returns (uint32 loanId) { _escrowTokens[_loanTerms.nftCollateralContract][_loanTerms.nftCollateralId] += 1; uint256 referralfee = LoanChecksAndCalculations.computeReferralFee( _loanTerms.loanPrincipalAmount, _loanExtras.referralFeeInBasisPoints, _referrer ); uint256 principalAmount = _loanTerms.loanPrincipalAmount - referralfee; if (referralfee > 0) { // Transfer the referral fee from lender to referrer. IERC20(_loanTerms.loanERC20Denomination).safeTransferFrom(_lender, _referrer, referralfee); } // Transfer principal from lender to borrower. IERC20(_loanTerms.loanERC20Denomination).safeTransferFrom(_lender, _borrower, principalAmount); // Issue an ERC721 promissory note to the lender that gives them the // right to either the principal-plus-interest or the collateral, // and an obligation note to the borrower that gives them the // right to pay back the loan and get the collateral back. IDirectLoanCoordinator loanCoordinator = IDirectLoanCoordinator(hub.getContract(LOAN_COORDINATOR)); loanId = loanCoordinator.registerLoan(_lender, _loanType); // Add the loan to storage before moving collateral/principal to follow // the Checks-Effects-Interactions pattern. loanIdToLoan[loanId] = _loanTerms; loanIdToLoanExtras[loanId] = _loanExtras; return loanId; } /** * @dev Transfers several types of NFTs using a wrapper that knows how to handle each case. * * @param _loanTerms - Struct containing all the loan's parameters * @param _sender - Current owner of the NFT * @param _recipient - Recipient of the transfer */ function _transferNFT( LoanTerms memory _loanTerms, address _sender, address _recipient ) internal { Address.functionDelegateCall( _loanTerms.nftCollateralWrapper, abi.encodeWithSelector( INftWrapper(_loanTerms.nftCollateralWrapper).transferNFT.selector, _sender, _recipient, _loanTerms.nftCollateralContract, _loanTerms.nftCollateralId ), "NFT not successfully transferred" ); } /** * @notice This function is called by a anyone to repay a loan. It can be called at any time after the loan has * begun and before loan expiry.. The caller will pay a pro-rata portion of their interest if the loan is paid off * early and the loan is pro-rated type, but the complete repayment amount if it is fixed type. * The the borrower (current owner of the obligation note) will get the collaterl NFT back. * * This function is purposefully not pausable in order to prevent an attack where the contract admin's pause the * contract and hold hostage the NFT's that are still within it. * * @param _loanId A unique identifier for this particular loan, sourced from the Loan Coordinator. */ function _payBackLoan( uint32 _loanId, address _borrower, address _lender, LoanTerms memory _loan ) internal { // Fetch loan details from storage, but store them in memory for the sake of saving gas. LoanExtras memory loanExtras = loanIdToLoanExtras[_loanId]; (uint256 adminFee, uint256 payoffAmount) = _payoffAndFee(_loan); // Transfer principal-plus-interest-minus-fees from the caller to lender IERC20(_loan.loanERC20Denomination).safeTransferFrom(msg.sender, _lender, payoffAmount); uint256 revenueShare = LoanChecksAndCalculations.computeRevenueShare( adminFee, loanExtras.revenueShareInBasisPoints ); // PermittedPartners contract doesn't allow to set a revenueShareInBasisPoints for address zero so revenuShare // > 0 implies that revenueSharePartner ~= address(0), BUT revenueShare can be zero for a partener when the // adminFee is low if (revenueShare > 0 && loanExtras.revenueSharePartner != address(0)) { adminFee -= revenueShare; // Transfer revenue share from the caller to permitted partner IERC20(_loan.loanERC20Denomination).safeTransferFrom( msg.sender, loanExtras.revenueSharePartner, revenueShare ); } // Transfer fees from the caller to admins IERC20(_loan.loanERC20Denomination).safeTransferFrom(msg.sender, owner(), adminFee); // Emit an event with all relevant details from this transaction. emit LoanRepaid( _loanId, _borrower, _lender, _loan.loanPrincipalAmount, _loan.nftCollateralId, payoffAmount, adminFee, revenueShare, loanExtras.revenueSharePartner, // this could be a non address zero even if revenueShare is 0 _loan.nftCollateralContract, _loan.loanERC20Denomination ); } /** * @notice A convenience function with shared functionality between `payBackLoan` and `liquidateOverdueLoan`. * * @param _loanId A unique identifier for this particular loan, sourced from the Loan Coordinator. * @param _nftReceiver - The receiver of the collateral nft. The borrower when `payBackLoan` or the lender when * `liquidateOverdueLoan`. * @param _loanTerms - The main Loan Terms struct. This data is saved upon loan creation on loanIdToLoan. * @param _loanCoordinator - The loan coordinator used when creating the loan. */ function _resolveLoan( uint32 _loanId, address _nftReceiver, LoanTerms memory _loanTerms, IDirectLoanCoordinator _loanCoordinator ) internal { _resolveLoanNoNftTransfer(_loanId, _loanTerms, _loanCoordinator); // Transfer collateral from this contract to the lender, since the lender is seizing collateral for an overdue // loan _transferNFT(_loanTerms, address(this), _nftReceiver); } /** * @notice Resolving the loan without trasferring the nft to provide a base for the bundle * break up of the bundled loans * * @param _loanId A unique identifier for this particular loan, sourced from the Loan Coordinator. * @param _loanTerms - The main Loan Terms struct. This data is saved upon loan creation on loanIdToLoan. * @param _loanCoordinator - The loan coordinator used when creating the loan. */ function _resolveLoanNoNftTransfer( uint32 _loanId, LoanTerms memory _loanTerms, IDirectLoanCoordinator _loanCoordinator ) internal { // Mark loan as liquidated before doing any external transfers to follow the Checks-Effects-Interactions design // pattern loanRepaidOrLiquidated[_loanId] = true; _escrowTokens[_loanTerms.nftCollateralContract][_loanTerms.nftCollateralId] -= 1; // Destroy the lender's promissory note for this loan and borrower obligation receipt _loanCoordinator.resolveLoan(_loanId); } /** * @notice This function can be called by admins to change the permitted status of an ERC20 currency. This includes * both adding an ERC20 currency to the permitted list and removing it. * * @param _erc20 - The address of the ERC20 currency whose permit list status changed. * @param _permit - The new status of whether the currency is permitted or not. */ function _setERC20Permit(address _erc20, bool _permit) internal { require(_erc20 != address(0), "erc20 is zero address"); erc20Permits[_erc20] = _permit; emit ERC20Permit(_erc20, _permit); } /** * @dev Performs some validation checks over loan parameters * */ function _loanSanityChecks(LoanData.Offer memory _offer, address _nftWrapper) internal view { require(getERC20Permit(_offer.loanERC20Denomination), "Currency denomination is not permitted"); require(_nftWrapper != address(0), "NFT collateral contract is not permitted"); require(uint256(_offer.loanDuration) <= maximumLoanDuration, "Loan duration exceeds maximum loan duration"); require(uint256(_offer.loanDuration) != 0, "Loan duration cannot be zero"); require( _offer.loanAdminFeeInBasisPoints == adminFeeInBasisPoints, "The admin fee has changed since this order was signed." ); } /** * @dev reads some variable values of a loan for payback functions, created to reduce code repetition */ function _getPartiesAndData(uint32 _loanId) internal view returns ( address borrower, address lender, LoanTerms memory loan, IDirectLoanCoordinator loanCoordinator ) { loanCoordinator = IDirectLoanCoordinator(hub.getContract(LOAN_COORDINATOR)); IDirectLoanCoordinator.Loan memory loanCoordinatorData = loanCoordinator.getLoanData(_loanId); uint256 smartNftId = loanCoordinatorData.smartNftId; // Fetch loan details from storage, but store them in memory for the sake of saving gas. loan = loanIdToLoan[_loanId]; if (loan.borrower != address(0)) { borrower = loan.borrower; } else { // Fetch current owner of loan obligation note. borrower = IERC721(loanCoordinator.obligationReceiptToken()).ownerOf(smartNftId); } lender = IERC721(loanCoordinator.promissoryNoteToken()).ownerOf(smartNftId); } /** * @dev Creates a `LoanExtras` struct using data sent as the borrower's extra settings. * This is needed in order to avoid stack too deep issues. */ function _setupLoanExtras(address _revenueSharePartner, uint16 _referralFeeInBasisPoints) internal view returns (LoanExtras memory) { // Save loan details to a struct in memory first, to save on gas if any // of the below checks fail, and to avoid the "Stack Too Deep" error by // clumping the parameters together into one struct held in memory. return LoanExtras({ revenueSharePartner: _revenueSharePartner, revenueShareInBasisPoints: LoanChecksAndCalculations.getRevenueSharePercent(_revenueSharePartner, hub), referralFeeInBasisPoints: _referralFeeInBasisPoints }); } /** * @dev Calculates the payoff amount and admin fee */ function _payoffAndFee(LoanTerms memory _loanTerms) internal view virtual returns (uint256, uint256); /** * @dev Checks that the collateral is a supported contracts and returns what wrapper to use for the loan's NFT * collateral contract. * * @param _nftCollateralContract - The address of the the NFT collateral contract. * * @return Address of the NftWrapper to use for the loan's NFT collateral. */ function _getWrapper(address _nftCollateralContract) internal view returns (address) { return IPermittedNFTs(hub.getContract(ContractKeys.PERMITTED_NFTS)).getNFTWrapper(_nftCollateralContract); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; /** * @title ContractKeys * @author NFTfi * @dev Common library for contract keys */ library ContractKeys { bytes32 public constant PERMITTED_ERC20S = bytes32("PERMITTED_ERC20S"); bytes32 public constant PERMITTED_NFTS = bytes32("PERMITTED_NFTS"); bytes32 public constant PERMITTED_PARTNERS = bytes32("PERMITTED_PARTNERS"); bytes32 public constant NFT_TYPE_REGISTRY = bytes32("NFT_TYPE_REGISTRY"); bytes32 public constant LOAN_REGISTRY = bytes32("LOAN_REGISTRY"); bytes32 public constant PERMITTED_SNFT_RECEIVER = bytes32("PERMITTED_SNFT_RECEIVER"); bytes32 public constant PERMITTED_BUNDLE_ERC20S = bytes32("PERMITTED_BUNDLE_ERC20S"); bytes32 public constant PERMITTED_AIRDROPS = bytes32("PERMITTED_AIRDROPS"); bytes32 public constant AIRDROP_RECEIVER = bytes32("AIRDROP_RECEIVER"); bytes32 public constant AIRDROP_FACTORY = bytes32("AIRDROP_FACTORY"); bytes32 public constant AIRDROP_FLASH_LOAN = bytes32("AIRDROP_FLASH_LOAN"); bytes32 public constant NFTFI_BUNDLER = bytes32("NFTFI_BUNDLER"); string public constant AIRDROP_WRAPPER_STRING = "AirdropWrapper"; /** * @notice Returns the bytes32 representation of a string * @param _key the string key * @return id bytes32 representation */ function getIdFromStringKey(string memory _key) external pure returns (bytes32 id) { require(bytes(_key).length <= 32, "invalid key"); // solhint-disable-next-line no-inline-assembly assembly { id := mload(add(_key, 32)) } } } // SPDX-License-Identifier: BUSL-1.1 import "./LoanData.sol"; pragma solidity 0.8.4; interface IDirectLoanBase { function maximumLoanDuration() external view returns (uint256); function adminFeeInBasisPoints() external view returns (uint16); // solhint-disable-next-line func-name-mixedcase function LOAN_COORDINATOR() external view returns (bytes32); function loanIdToLoan(uint32) external view returns ( uint256, uint256, uint256, address, uint32, uint16, uint16, address, uint64, address, address ); function loanRepaidOrLiquidated(uint32) external view returns (bool); function getWhetherNonceHasBeenUsedForUser(address _user, uint256 _nonce) external view returns (bool); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; /** * @title LoanData * @author NFTfi * @notice An interface containg the main Loan struct shared by Direct Loans types. */ interface LoanData { /* ********** */ /* DATA TYPES */ /* ********** */ /** * @notice The main Loan Terms struct. This data is saved upon loan creation. * * @param loanERC20Denomination - The address of the ERC20 contract of the currency being used as principal/interest * for this loan. * @param loanPrincipalAmount - The original sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * @param maximumRepaymentAmount - The maximum amount of money that the borrower would be required to retrieve their * collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always have * to pay this amount to retrieve their collateral, regardless of whether they repay early. * @param nftCollateralContract - The address of the the NFT collateral contract. * @param nftCollateralWrapper - The NFTfi wrapper of the NFT collateral contract. * @param nftCollateralId - The ID within the NFTCollateralContract for the NFT being used as collateral for this * loan. The NFT is stored within this contract during the duration of the loan. * @param loanStartTime - The block.timestamp when the loan first began (measured in seconds). * @param loanDuration - The amount of time (measured in seconds) that can elapse before the lender can liquidate * the loan and seize the underlying collateral NFT. * @param loanInterestRateForDurationInBasisPoints - This is the interest rate (measured in basis points, e.g. * hundreths of a percent) for the loan, that must be repaid pro-rata by the borrower at the conclusion of the loan * or risk seizure of their nft collateral. Note if the type of the loan is fixed then this value is not used and * is irrelevant so it should be set to 0. * @param loanAdminFeeInBasisPoints - The percent (measured in basis points) of the interest earned that will be * taken as a fee by the contract admins when the loan is repaid. The fee is stored in the loan struct to prevent an * attack where the contract admins could adjust the fee right before a loan is repaid, and take all of the interest * earned. * @param borrower */ struct LoanTerms { uint256 loanPrincipalAmount; uint256 maximumRepaymentAmount; uint256 nftCollateralId; address loanERC20Denomination; uint32 loanDuration; uint16 loanInterestRateForDurationInBasisPoints; uint16 loanAdminFeeInBasisPoints; address nftCollateralWrapper; uint64 loanStartTime; address nftCollateralContract; address borrower; } /** * @notice Some extra Loan's settings struct. This data is saved upon loan creation. * We need this to avoid stack too deep errors. * * @param revenueSharePartner - The address of the partner that will receive the revenue share. * @param revenueShareInBasisPoints - The percent (measured in basis points) of the admin fee amount that will be * taken as a revenue share for a t * @param referralFeeInBasisPoints - The percent (measured in basis points) of the loan principal amount that will * be taken as a fee to pay to the referrer, 0 if the lender is not paying referral fee.he partner, at the moment * the loan is begun. */ struct LoanExtras { address revenueSharePartner; uint16 revenueShareInBasisPoints; uint16 referralFeeInBasisPoints; } /** * @notice The offer made by the lender. Used as parameter on both acceptOffer (initiated by the borrower) and * acceptListing (initiated by the lender). * * @param loanERC20Denomination - The address of the ERC20 contract of the currency being used as principal/interest * for this loan. * @param loanPrincipalAmount - The original sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * @param maximumRepaymentAmount - The maximum amount of money that the borrower would be required to retrieve their * collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always * have to pay this amount to retrieve their collateral, regardless of whether they repay early. * @param nftCollateralContract - The address of the ERC721 contract of the NFT collateral. * @param nftCollateralId - The ID within the NFTCollateralContract for the NFT being used as collateral for this * loan. The NFT is stored within this contract during the duration of the loan. * @param referrer - The address of the referrer who found the lender matching the listing, Zero address to signal * this there is no referrer. * @param loanDuration - The amount of time (measured in seconds) that can elapse before the lender can liquidate * the loan and seize the underlying collateral NFT. * @param loanAdminFeeInBasisPoints - The percent (measured in basis points) of the interest earned that will be * taken as a fee by the contract admins when the loan is repaid. The fee is stored in the loan struct to prevent an * attack where the contract admins could adjust the fee right before a loan is repaid, and take all of the interest * earned. */ struct Offer { uint256 loanPrincipalAmount; uint256 maximumRepaymentAmount; uint256 nftCollateralId; address nftCollateralContract; uint32 loanDuration; uint16 loanAdminFeeInBasisPoints; address loanERC20Denomination; address referrer; } /** * @notice Signature related params. Used as parameter on both acceptOffer (containing borrower signature) and * acceptListing (containing lender signature). * * @param signer - The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`. * @param nonce - The nonce referred here is not the same as an Ethereum account's nonce. * We are referring instead to a nonce that is used by the lender or the borrower when they are first signing * off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an * off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the * lender or the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling NFTfi.cancelLoanCommitmentBeforeLoanHasBegun() * , which marks the nonce as used and prevents any future loan from using the user's off-chain order that contains * that nonce. * @param expiry - Date when the signature expires * @param signature - The ECDSA signature of the borrower or the lender, obtained off-chain ahead of time, signing * the following combination of parameters: * - Borrower * - ListingTerms.loanERC20Denomination, * - ListingTerms.minLoanPrincipalAmount, * - ListingTerms.maxLoanPrincipalAmount, * - ListingTerms.nftCollateralContract, * - ListingTerms.nftCollateralId, * - ListingTerms.revenueSharePartner, * - ListingTerms.minLoanDuration, * - ListingTerms.maxLoanDuration, * - ListingTerms.maxInterestRateForDurationInBasisPoints, * - ListingTerms.referralFeeInBasisPoints, * - Signature.signer, * - Signature.nonce, * - Signature.expiry, * - address of the loan type contract * - chainId * - Lender: * - Offer.loanERC20Denomination * - Offer.loanPrincipalAmount * - Offer.maximumRepaymentAmount * - Offer.nftCollateralContract * - Offer.nftCollateralId * - Offer.referrer * - Offer.loanDuration * - Offer.loanAdminFeeInBasisPoints * - Signature.signer, * - Signature.nonce, * - Signature.expiry, * - address of the loan type contract * - chainId */ struct Signature { uint256 nonce; uint256 expiry; address signer; bytes signature; } /** * @notice Some extra parameters that the borrower needs to set when accepting an offer. * * @param revenueSharePartner - The address of the partner that will receive the revenue share. * @param referralFeeInBasisPoints - The percent (measured in basis points) of the loan principal amount that will * be taken as a fee to pay to the referrer, 0 if the lender is not paying referral fee. */ struct BorrowerSettings { address revenueSharePartner; uint16 referralFeeInBasisPoints; } /** * @notice Terms the borrower set off-chain and is willing to accept automatically when fulfiled by a lender's * offer. * * @param loanERC20Denomination - The address of the ERC20 contract of the currency being used as principal/interest * for this loan. * @param minLoanPrincipalAmount - The minumum sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * @param maxLoanPrincipalAmount - The sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * @param maximumRepaymentAmount - The maximum amount of money that the borrower would be required to retrieve their * collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always have * to pay this amount to retrieve their collateral, regardless of whether they repay early. * @param nftCollateralContract - The address of the ERC721 contract of the NFT collateral. * @param nftCollateralId - The ID within the NFTCollateralContract for the NFT being used as collateral for this * loan. The NFT is stored within this contract during the duration of the loan. * @param revenueSharePartner - The address of the partner that will receive the revenue share. * @param minLoanDuration - The minumum amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * @param maxLoanDuration - The maximum amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * @param maxInterestRateForDurationInBasisPoints - This is maximum the interest rate (measured in basis points, * e.g. hundreths of a percent) for the loan. * @param referralFeeInBasisPoints - The percent (measured in basis points) of the loan principal amount that will * be taken as a fee to pay to the referrer, 0 if the lender is not paying referral fee. */ struct ListingTerms { uint256 minLoanPrincipalAmount; uint256 maxLoanPrincipalAmount; uint256 nftCollateralId; address nftCollateralContract; uint32 minLoanDuration; uint32 maxLoanDuration; uint16 maxInterestRateForDurationInBasisPoints; uint16 referralFeeInBasisPoints; address revenueSharePartner; address loanERC20Denomination; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; import "./IDirectLoanBase.sol"; import "./LoanData.sol"; import "../../../interfaces/IDirectLoanCoordinator.sol"; import "../../../utils/ContractKeys.sol"; import "../../../interfaces/INftfiHub.sol"; import "../../../interfaces/IPermittedPartners.sol"; import "../../../interfaces/IPermittedERC20s.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; /** * @title LoanChecksAndCalculations * @author NFTfi * @notice Helper library for LoanBase */ library LoanChecksAndCalculations { uint16 private constant HUNDRED_PERCENT = 10000; /** * @dev Function that performs some validation checks before trying to repay a loan * * @param _loanId - The id of the loan being repaid */ function payBackChecks(uint32 _loanId, INftfiHub _hub) external view { checkLoanIdValidity(_loanId, _hub); // Sanity check that payBackLoan() and liquidateOverdueLoan() have never been called on this loanId. // Depending on how the rest of the code turns out, this check may be unnecessary. require(!IDirectLoanBase(address(this)).loanRepaidOrLiquidated(_loanId), "Loan already repaid/liquidated"); // Fetch loan details from storage, but store them in memory for the sake of saving gas. (, , , , uint32 loanDuration, , , , uint64 loanStartTime, , ) = IDirectLoanBase(address(this)).loanIdToLoan( _loanId ); // When a loan exceeds the loan term, it is expired. At this stage the Lender can call Liquidate Loan to resolve // the loan. require(block.timestamp <= (uint256(loanStartTime) + uint256(loanDuration)), "Loan is expired"); } function checkLoanIdValidity(uint32 _loanId, INftfiHub _hub) public view { require( IDirectLoanCoordinator(_hub.getContract(IDirectLoanBase(address(this)).LOAN_COORDINATOR())).isValidLoanId( _loanId, address(this) ), "invalid loanId" ); } /** * @dev Function that the partner is permitted and returns its shared percent. * * @param _revenueSharePartner - Partner's address * * @return The revenue share percent for the partner. */ function getRevenueSharePercent(address _revenueSharePartner, INftfiHub _hub) external view returns (uint16) { // return soon if no partner is set to avoid a public call if (_revenueSharePartner == address(0)) { return 0; } uint16 revenueSharePercent = IPermittedPartners(_hub.getContract(ContractKeys.PERMITTED_PARTNERS)) .getPartnerPermit(_revenueSharePartner); return revenueSharePercent; } /** * @dev Performs some validation checks before trying to renegotiate a loan. * Needed to avoid stack too deep. * * @param _loan - The main Loan Terms struct. * @param _loanId - The unique identifier for the loan to be renegotiated * @param _newLoanDuration - The new amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * @param _newMaximumRepaymentAmount - The new maximum amount of money that the borrower would be required to * retrieve their collateral, measured in the smallest units of the ERC20 currency used for the loan. The * borrower will always have to pay this amount to retrieve their collateral, regardless of whether they repay * early. * @param _lenderNonce - The nonce referred to here is not the same as an Ethereum account's nonce. We are * referring instead to nonces that are used by both the lender and the borrower when they are first signing * off-chain NFTfi orders. These nonces can be any uint256 value that the user has not previously used to sign an * off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the * lender or the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling NFTfi.cancelLoanCommitmentBeforeLoanHasBegun() , which marks the nonce as used and prevents any future loan from using the user's off-chain order that contains * that nonce. * @return Borrower and Lender addresses */ function renegotiationChecks( LoanData.LoanTerms memory _loan, uint32 _loanId, uint32 _newLoanDuration, uint256 _newMaximumRepaymentAmount, uint256 _lenderNonce, INftfiHub _hub ) external view returns (address, address) { checkLoanIdValidity(_loanId, _hub); IDirectLoanCoordinator loanCoordinator = IDirectLoanCoordinator( _hub.getContract(IDirectLoanBase(address(this)).LOAN_COORDINATOR()) ); uint256 smartNftId = loanCoordinator.getLoanData(_loanId).smartNftId; address borrower; if (_loan.borrower != address(0)) { borrower = _loan.borrower; } else { borrower = IERC721(loanCoordinator.obligationReceiptToken()).ownerOf(smartNftId); } require(msg.sender == borrower, "Only borrower can initiate"); require(block.timestamp <= (uint256(_loan.loanStartTime) + _newLoanDuration), "New duration already expired"); require( uint256(_newLoanDuration) <= IDirectLoanBase(address(this)).maximumLoanDuration(), "New duration exceeds maximum loan duration" ); require(!IDirectLoanBase(address(this)).loanRepaidOrLiquidated(_loanId), "Loan already repaid/liquidated"); require( _newMaximumRepaymentAmount >= _loan.loanPrincipalAmount, "Negative interest rate loans are not allowed." ); // Fetch current owner of loan promissory note. address lender = IERC721(loanCoordinator.promissoryNoteToken()).ownerOf(smartNftId); require( !IDirectLoanBase(address(this)).getWhetherNonceHasBeenUsedForUser(lender, _lenderNonce), "Lender nonce invalid" ); return (borrower, lender); } /** * @dev Performs some validation checks over loan parameters when accepting a listing * */ function bindingTermsSanityChecks(LoanData.ListingTerms memory _listingTerms, LoanData.Offer memory _offer) external pure { // offer vs listing validations require(_offer.loanERC20Denomination == _listingTerms.loanERC20Denomination, "Invalid loanERC20Denomination"); require( _offer.loanPrincipalAmount >= _listingTerms.minLoanPrincipalAmount && _offer.loanPrincipalAmount <= _listingTerms.maxLoanPrincipalAmount, "Invalid loanPrincipalAmount" ); uint256 maxRepaymentLimit = _offer.loanPrincipalAmount + (_offer.loanPrincipalAmount * _listingTerms.maxInterestRateForDurationInBasisPoints) / HUNDRED_PERCENT; require(_offer.maximumRepaymentAmount <= maxRepaymentLimit, "maxInterestRateForDurationInBasisPoints violated"); require( _offer.loanDuration >= _listingTerms.minLoanDuration && _offer.loanDuration <= _listingTerms.maxLoanDuration, "Invalid loanDuration" ); } /** * @notice A convenience function computing the revenue share taken from the admin fee to transferr to the permitted * partner. * * @param _adminFee - The quantity of ERC20 currency (measured in smalled units of that ERC20 currency) that is due * as an admin fee. * @param _revenueShareInBasisPoints - The percent (measured in basis points) of the admin fee amount that will be * taken as a revenue share for a the partner, at the moment the loan is begun. * * @return The quantity of ERC20 currency (measured in smalled units of that ERC20 currency) that should be sent to * the `revenueSharePartner`. */ function computeRevenueShare(uint256 _adminFee, uint256 _revenueShareInBasisPoints) external pure returns (uint256) { return (_adminFee * _revenueShareInBasisPoints) / HUNDRED_PERCENT; } /** * @notice A convenience function computing the adminFee taken from a specified quantity of interest. * * @param _interestDue - The amount of interest due, measured in the smallest quantity of the ERC20 currency being * used to pay the interest. * @param _adminFeeInBasisPoints - The percent (measured in basis points) of the interest earned that will be taken * as a fee by the contract admins when the loan is repaid. The fee is stored in the loan struct to prevent an * attack where the contract admins could adjust the fee right before a loan is repaid, and take all of the interest * earned. * * @return The quantity of ERC20 currency (measured in smalled units of that ERC20 currency) that is due as an admin * fee. */ function computeAdminFee(uint256 _interestDue, uint256 _adminFeeInBasisPoints) external pure returns (uint256) { return (_interestDue * _adminFeeInBasisPoints) / HUNDRED_PERCENT; } /** * @notice A convenience function computing the referral fee taken from the loan principal amount to transferr to * the referrer. * * @param _loanPrincipalAmount - The original sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * @param _referralFeeInBasisPoints - The percent (measured in basis points) of the loan principal amount that will * be taken as a fee to pay to the referrer, 0 if the lender is not paying referral fee. * @param _referrer - The address of the referrer who found the lender matching the listing, Zero address to signal * that there is no referrer. * * @return The quantity of ERC20 currency (measured in smalled units of that ERC20 currency) that should be sent to * the referrer. */ function computeReferralFee( uint256 _loanPrincipalAmount, uint256 _referralFeeInBasisPoints, address _referrer ) external pure returns (uint256) { if (_referralFeeInBasisPoints == 0 || _referrer == address(0)) { return 0; } return (_loanPrincipalAmount * _referralFeeInBasisPoints) / HUNDRED_PERCENT; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; import "./IDirectLoanBase.sol"; import "./LoanData.sol"; import "../../../interfaces/IDirectLoanCoordinator.sol"; import "../../../utils/ContractKeys.sol"; import "../../../interfaces/INftfiHub.sol"; import "../../../interfaces/IPermittedPartners.sol"; import "../../../interfaces/IPermittedERC20s.sol"; import "../../../interfaces/IAirdropFlashLoan.sol"; import "../../../interfaces/INftWrapper.sol"; import "../../../airdrop/IAirdropReceiverFactory.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/utils/Address.sol"; /** * @title LoanAirdropUtils * @author NFTfi * @notice Helper library for LoanBase */ library LoanAirdropUtils { /** * @notice This event is fired whenever a flashloan is initiated to pull an airdrop * * @param loanId - A unique identifier for this particular loan, sourced from the Loan Coordinator. * @param borrower - The address of the borrower. * @param nftCollateralId - The ID within the AirdropReceiver for the NFT being used as collateral for this * loan. * @param nftCollateralContract - The ERC721 contract of the NFT collateral * @param target - address of the airdropping contract * @param data - function selector to be called */ event AirdropPulledFlashloan( uint256 indexed loanId, address indexed borrower, uint256 nftCollateralId, address nftCollateralContract, address target, bytes data ); /** * @notice This event is fired whenever the collateral gets wrapped in an airdrop receiver * * @param loanId - A unique identifier for this particular loan, sourced from the Loan Coordinator. * @param borrower - The address of the borrower. * @param nftCollateralId - The ID within the AirdropReceiver for the NFT being used as collateral for this * loan. * @param nftCollateralContract - The contract of the NFT collateral * @param receiverId - id of the created AirdropReceiver, takes the place of nftCollateralId on the loan * @param receiverInstance - address of the created AirdropReceiver */ event CollateralWrapped( uint256 indexed loanId, address indexed borrower, uint256 nftCollateralId, address nftCollateralContract, uint256 receiverId, address receiverInstance ); function pullAirdrop( uint32 _loanId, LoanData.LoanTerms memory _loan, address _target, bytes calldata _data, address _nftAirdrop, uint256 _nftAirdropId, bool _is1155, uint256 _nftAirdropAmount, INftfiHub _hub ) external { IDirectLoanCoordinator loanCoordinator = IDirectLoanCoordinator( _hub.getContract(IDirectLoanBase(address(this)).LOAN_COORDINATOR()) ); address borrower; // scoped to aviod stack too deep { IDirectLoanCoordinator.Loan memory loanCoordinatorData = loanCoordinator.getLoanData(_loanId); uint256 smartNftId = loanCoordinatorData.smartNftId; if (_loan.borrower != address(0)) { borrower = _loan.borrower; } else { borrower = IERC721(loanCoordinator.obligationReceiptToken()).ownerOf(smartNftId); } } require(msg.sender == borrower, "Only borrower can airdrop"); { IAirdropFlashLoan airdropFlashLoan = IAirdropFlashLoan(_hub.getContract(ContractKeys.AIRDROP_FLASH_LOAN)); _transferNFT(_loan, address(this), address(airdropFlashLoan)); airdropFlashLoan.pullAirdrop( _loan.nftCollateralContract, _loan.nftCollateralId, _loan.nftCollateralWrapper, _target, _data, _nftAirdrop, _nftAirdropId, _is1155, _nftAirdropAmount, borrower ); } // revert if the collateral hasn't been transferred back before it ends require( INftWrapper(_loan.nftCollateralWrapper).isOwner( address(this), _loan.nftCollateralContract, _loan.nftCollateralId ), "Collateral should be returned" ); emit AirdropPulledFlashloan( _loanId, borrower, _loan.nftCollateralId, _loan.nftCollateralContract, _target, _data ); } function wrapCollateral( uint32 _loanId, LoanData.LoanTerms storage _loan, INftfiHub _hub ) external returns (address instance, uint256 receiverId) { IDirectLoanCoordinator loanCoordinator = IDirectLoanCoordinator( _hub.getContract(IDirectLoanBase(address(this)).LOAN_COORDINATOR()) ); // Fetch the current lender of the promissory note corresponding to this overdue loan. IDirectLoanCoordinator.Loan memory loanCoordinatorData = loanCoordinator.getLoanData(_loanId); uint256 smartNftId = loanCoordinatorData.smartNftId; address borrower; if (_loan.borrower != address(0)) { borrower = _loan.borrower; } else { borrower = IERC721(loanCoordinator.obligationReceiptToken()).ownerOf(smartNftId); } require(msg.sender == borrower, "Only borrower can wrapp"); IAirdropReceiverFactory factory = IAirdropReceiverFactory(_hub.getContract(ContractKeys.AIRDROP_FACTORY)); (instance, receiverId) = factory.createAirdropReceiver(address(this)); // transfer collateral to airdrop receiver wrapper _transferNFTtoAirdropReceiver(_loan, instance, borrower); emit CollateralWrapped( _loanId, borrower, _loan.nftCollateralId, _loan.nftCollateralContract, receiverId, instance ); // set the receiver as the new collateral _loan.nftCollateralContract = instance; _loan.nftCollateralId = receiverId; } /** * @dev Transfers several types of NFTs using a wrapper that knows how to handle each case. * * @param _loan - * @param _sender - Current owner of the NFT * @param _recipient - Recipient of the transfer */ function _transferNFT( LoanData.LoanTerms memory _loan, address _sender, address _recipient ) internal { Address.functionDelegateCall( _loan.nftCollateralWrapper, abi.encodeWithSelector( INftWrapper(_loan.nftCollateralWrapper).transferNFT.selector, _sender, _recipient, _loan.nftCollateralContract, _loan.nftCollateralId ), "NFT not successfully transferred" ); } /** * @dev Transfers several types of NFTs to an airdrop receiver with an airdrop beneficiary * address attached as supplementing data using a wrapper that knows how to handle each case. * * @param _loan - * @param _airdropReceiverInstance - Recipient of the transfer * @param _airdropBeneficiary - Beneficiary of the future airdops */ function _transferNFTtoAirdropReceiver( LoanData.LoanTerms memory _loan, address _airdropReceiverInstance, address _airdropBeneficiary ) internal { Address.functionDelegateCall( _loan.nftCollateralWrapper, abi.encodeWithSelector( INftWrapper(_loan.nftCollateralWrapper).wrapAirdropReceiver.selector, _airdropReceiverInstance, _loan.nftCollateralContract, _loan.nftCollateralId, _airdropBeneficiary ), "NFT was not successfully migrated" ); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; import "../utils/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; /** * @title BaseLoan * @author NFTfi * @dev Implements base functionalities common to all Loan types. * Mostly related to governance and security. */ abstract contract BaseLoan is Ownable, Pausable, ReentrancyGuard { /* *********** */ /* CONSTRUCTOR */ /* *********** */ /** * @notice Sets the admin of the contract. * * @param _admin - Initial admin of this contract. */ constructor(address _admin) Ownable(_admin) { // solhint-disable-previous-line no-empty-blocks } /* ********* */ /* FUNCTIONS */ /* ********* */ /** * @dev Triggers stopped state. * * Requirements: * * - Only the owner can call this method. * - The contract must not be paused. */ function pause() external onlyOwner { _pause(); } /** * @dev Returns to normal state. * * Requirements: * * - Only the owner can call this method. * - The contract must be paused. */ function unpause() external onlyOwner { _unpause(); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol"; /** * @title NftReceiver * @author NFTfi * @dev Base contract with capabilities for receiving ERC1155 and ERC721 tokens */ abstract contract NftReceiver is IERC1155Receiver, ERC721Holder { /** * @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a * `safeTransferFrom` after the balance has been updated. * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if allowed */ function onERC1155Received( address, address, uint256, uint256, bytes calldata ) external virtual override returns (bytes4) { return this.onERC1155Received.selector; } /** * @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a * `safeBatchTransferFrom` after the balances have been updated. * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if allowed */ function onERC1155BatchReceived( address, address, uint256[] calldata, uint256[] calldata, bytes calldata ) external virtual override returns (bytes4) { revert("ERC1155 batch not supported"); } /** * @dev Checks whether this contract implements the interface defined by `interfaceId`. * @param _interfaceId Id of the interface * @return true if this contract implements the interface */ function supportsInterface(bytes4 _interfaceId) public view virtual override returns (bool) { return _interfaceId == type(IERC1155Receiver).interfaceId || _interfaceId == type(IERC721Receiver).interfaceId || _interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; import "../interfaces/IBundleBuilder.sol"; import "../loans/direct/loanTypes/LoanData.sol"; import "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol"; /** * @title NFTfiSigningUtils * @author NFTfi * @notice Helper contract for NFTfi. This contract manages verifying signatures from off-chain NFTfi orders. * Based on the version of this same contract used on NFTfi V1 */ library NFTfiSigningUtils { /* ********* */ /* FUNCTIONS */ /* ********* */ /** * @dev This function gets the current chain ID. */ function getChainID() public view returns (uint256) { uint256 id; // solhint-disable-next-line no-inline-assembly assembly { id := chainid() } return id; } /** * @notice This function is when the lender accepts a borrower's binding listing terms, to validate the lender's * signature that the borrower provided off-chain to verify that it did indeed made such listing. * * @param _listingTerms - The listing terms struct containing: * - loanERC20Denomination: The address of the ERC20 contract of the currency being used as principal/interest * for this loan. * - minLoanPrincipalAmount: The minumum sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * - maxLoanPrincipalAmount: The sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * - maximumRepaymentAmount: The maximum amount of money that the borrower would be required to retrieve their * collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always have * to pay this amount to retrieve their collateral, regardless of whether they repay early. * - nftCollateralContract: The address of the ERC721 contract of the NFT collateral. * - nftCollateralId: The ID within the NFTCollateralContract for the NFT being used as collateral for this * loan. The NFT is stored within this contract during the duration of the loan. * - revenueSharePartner: The address of the partner that will receive the revenue share. * - minLoanDuration: The minumum amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * - maxLoanDuration: The maximum amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * - maxInterestRateForDurationInBasisPoints: This is maximum the interest rate (measured in basis points, e.g. * hundreths of a percent) for the loan, that must be repaid pro-rata by the borrower at the conclusion of the loan * or risk seizure of their nft collateral. Note if the type of the loan is fixed then this value is not used and * is irrelevant so it should be set to 0. * - referralFeeInBasisPoints: The percent (measured in basis points) of the loan principal amount that will be * taken as a fee to pay to the referrer, 0 if the lender is not paying referral fee. * @param _signature - The offer struct containing: * - signer: The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`. * - nonce: The nonce referred here is not the same as an Ethereum account's nonce. * We are referring instead to a nonce that is used by the lender or the borrower when they are first signing * off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an * off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the * lender or the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling * NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the nonce as used and prevents any future loan from * using the user's off-chain order that contains that nonce. * - expiry: Date when the signature expires * - signature: The ECDSA signature of the borrower, obtained off-chain ahead of time, signing the following * combination of parameters: * - listingTerms.loanERC20Denomination, * - listingTerms.minLoanPrincipalAmount, * - listingTerms.maxLoanPrincipalAmount, * - listingTerms.nftCollateralContract, * - listingTerms.nftCollateralId, * - listingTerms.revenueSharePartner, * - listingTerms.minLoanDuration, * - listingTerms.maxLoanDuration, * - listingTerms.maxInterestRateForDurationInBasisPoints, * - listingTerms.referralFeeInBasisPoints, * - signature.signer, * - signature.nonce, * - signature.expiry, * - address of this contract * - chainId */ function isValidBorrowerSignature(LoanData.ListingTerms memory _listingTerms, LoanData.Signature memory _signature) external view returns (bool) { return isValidBorrowerSignature(_listingTerms, _signature, address(this)); } /** * @dev This function overload the previous function to allow the caller to specify the address of the contract * */ function isValidBorrowerSignature( LoanData.ListingTerms memory _listingTerms, LoanData.Signature memory _signature, address _loanContract ) public view returns (bool) { require(block.timestamp <= _signature.expiry, "Borrower Signature has expired"); require(_loanContract != address(0), "Loan is zero address"); if (_signature.signer == address(0)) { return false; } else { bytes32 message = keccak256( abi.encodePacked( getEncodedListing(_listingTerms), getEncodedSignature(_signature), _loanContract, getChainID() ) ); return SignatureChecker.isValidSignatureNow( _signature.signer, ECDSA.toEthSignedMessageHash(message), _signature.signature ); } } /** * @notice This function is when the lender accepts a borrower's binding listing terms, to validate the lender's * signature that the borrower provided off-chain to verify that it did indeed made such listing. * * @param _listingTerms - The listing terms struct containing: * - loanERC20Denomination: The address of the ERC20 contract of the currency being used as principal/interest * for this loan. * - minLoanPrincipalAmount: The minumum sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * - maxLoanPrincipalAmount: The sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * - maximumRepaymentAmount: The maximum amount of money that the borrower would be required to retrieve their * collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always have * to pay this amount to retrieve their collateral, regardless of whether they repay early. * - nftCollateralContract: The address of the ERC721 contract of the NFT collateral. * - nftCollateralId: The ID within the NFTCollateralContract for the NFT being used as collateral for this * loan. The NFT is stored within this contract during the duration of the loan. * - revenueSharePartner: The address of the partner that will receive the revenue share. * - minLoanDuration: The minumum amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * - maxLoanDuration: The maximum amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * - maxInterestRateForDurationInBasisPoints: This is maximum the interest rate (measured in basis points, e.g. * hundreths of a percent) for the loan, that must be repaid pro-rata by the borrower at the conclusion of the loan * or risk seizure of their nft collateral. Note if the type of the loan is fixed then this value is not used and * is irrelevant so it should be set to 0. * - referralFeeInBasisPoints: The percent (measured in basis points) of the loan principal amount that will be * taken as a fee to pay to the referrer, 0 if the lender is not paying referral fee. * @param _bundleElements - the lists of erc721-20-1155 tokens that are to be bundled * @param _signature - The offer struct containing: * - signer: The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`. * - nonce: The nonce referred here is not the same as an Ethereum account's nonce. * We are referring instead to a nonce that is used by the lender or the borrower when they are first signing * off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an * off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the * lender or the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling * NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the nonce as used and prevents any future loan from * using the user's off-chain order that contains that nonce. * - expiry: Date when the signature expires * - signature: The ECDSA signature of the borrower, obtained off-chain ahead of time, signing the following * combination of parameters: * - listingTerms.loanERC20Denomination, * - listingTerms.minLoanPrincipalAmount, * - listingTerms.maxLoanPrincipalAmount, * - listingTerms.nftCollateralContract, * - listingTerms.nftCollateralId, * - listingTerms.revenueSharePartner, * - listingTerms.minLoanDuration, * - listingTerms.maxLoanDuration, * - listingTerms.maxInterestRateForDurationInBasisPoints, * - listingTerms.referralFeeInBasisPoints, * - bundleElements * - signature.signer, * - signature.nonce, * - signature.expiry, * - address of this contract * - chainId */ function isValidBorrowerSignatureBundle( LoanData.ListingTerms memory _listingTerms, IBundleBuilder.BundleElements memory _bundleElements, LoanData.Signature memory _signature ) external view returns (bool) { return isValidBorrowerSignatureBundle(_listingTerms, _bundleElements, _signature, address(this)); } /** * @dev This function overload the previous function to allow the caller to specify the address of the contract * */ function isValidBorrowerSignatureBundle( LoanData.ListingTerms memory _listingTerms, IBundleBuilder.BundleElements memory _bundleElements, LoanData.Signature memory _signature, address _loanContract ) public view returns (bool) { require(block.timestamp <= _signature.expiry, "Borrower Signature has expired"); require(_loanContract != address(0), "Loan is zero address"); if (_signature.signer == address(0)) { return false; } else { bytes32 message = keccak256( abi.encodePacked( getEncodedListing(_listingTerms), abi.encode(_bundleElements), getEncodedSignature(_signature), _loanContract, getChainID() ) ); return SignatureChecker.isValidSignatureNow( _signature.signer, ECDSA.toEthSignedMessageHash(message), _signature.signature ); } } /** * @notice This function is when the borrower accepts a lender's offer, to validate the lender's signature that the * lender provided off-chain to verify that it did indeed made such offer. * * @param _offer - The offer struct containing: * - loanERC20Denomination: The address of the ERC20 contract of the currency being used as principal/interest * for this loan. * - loanPrincipalAmount: The original sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * - maximumRepaymentAmount: The maximum amount of money that the borrower would be required to retrieve their * collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always have * to pay this amount to retrieve their collateral, regardless of whether they repay early. * - nftCollateralContract: The address of the ERC721 contract of the NFT collateral. * - nftCollateralId: The ID within the NFTCollateralContract for the NFT being used as collateral for this * loan. The NFT is stored within this contract during the duration of the loan. * - referrer: The address of the referrer who found the lender matching the listing, Zero address to signal * this there is no referrer. * - loanDuration: The amount of time (measured in seconds) that can elapse before the lender can liquidate the * loan and seize the underlying collateral NFT. * - loanInterestRateForDurationInBasisPoints: This is the interest rate (measured in basis points, e.g. * hundreths of a percent) for the loan, that must be repaid pro-rata by the borrower at the conclusion of the loan * or risk seizure of their nft collateral. Note if the type of the loan is fixed then this value is not used and * is irrelevant so it should be set to 0. * - loanAdminFeeInBasisPoints: The percent (measured in basis points) of the interest earned that will be * taken as a fee by the contract admins when the loan is repaid. The fee is stored in the loan struct to prevent an * attack where the contract admins could adjust the fee right before a loan is repaid, and take all of the interest * earned. * @param _signature - The signature structure containing: * - signer: The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`. * - nonce: The nonce referred here is not the same as an Ethereum account's nonce. * We are referring instead to a nonce that is used by the lender or the borrower when they are first signing * off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an * off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the * lender or the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling * NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the nonce as used and prevents any future loan from * using the user's off-chain order that contains that nonce. * - expiry: Date when the signature expires * - signature: The ECDSA signature of the lender, obtained off-chain ahead of time, signing the following * combination of parameters: * - offer.loanERC20Denomination * - offer.loanPrincipalAmount * - offer.maximumRepaymentAmount * - offer.nftCollateralContract * - offer.nftCollateralId * - offer.referrer * - offer.loanDuration * - offer.loanAdminFeeInBasisPoints * - signature.signer, * - signature.nonce, * - signature.expiry, * - address of this contract * - chainId */ function isValidLenderSignature(LoanData.Offer memory _offer, LoanData.Signature memory _signature) external view returns (bool) { return isValidLenderSignature(_offer, _signature, address(this)); } /** * @dev This function overload the previous function to allow the caller to specify the address of the contract * */ function isValidLenderSignature( LoanData.Offer memory _offer, LoanData.Signature memory _signature, address _loanContract ) public view returns (bool) { require(block.timestamp <= _signature.expiry, "Lender Signature has expired"); require(_loanContract != address(0), "Loan is zero address"); if (_signature.signer == address(0)) { return false; } else { bytes32 message = keccak256( abi.encodePacked(getEncodedOffer(_offer), getEncodedSignature(_signature), _loanContract, getChainID()) ); return SignatureChecker.isValidSignatureNow( _signature.signer, ECDSA.toEthSignedMessageHash(message), _signature.signature ); } } /** * @notice This function is when the borrower accepts a lender's offer, to validate the lender's signature that the * lender provided off-chain to verify that it did indeed made such offer. * * @param _offer - The offer struct containing: * - loanERC20Denomination: The address of the ERC20 contract of the currency being used as principal/interest * for this loan. * - loanPrincipalAmount: The original sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * - maximumRepaymentAmount: The maximum amount of money that the borrower would be required to retrieve their * collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always have * to pay this amount to retrieve their collateral, regardless of whether they repay early. * - nftCollateralContract: The address of the ERC721 contract of the NFT collateral. * - nftCollateralId: The ID within the NFTCollateralContract for the NFT being used as collateral for this * loan. The NFT is stored within this contract during the duration of the loan. * - referrer: The address of the referrer who found the lender matching the listing, Zero address to signal * this there is no referrer. * - loanDuration: The amount of time (measured in seconds) that can elapse before the lender can liquidate the * loan and seize the underlying collateral NFT. * - loanInterestRateForDurationInBasisPoints: This is the interest rate (measured in basis points, e.g. * hundreths of a percent) for the loan, that must be repaid pro-rata by the borrower at the conclusion of the loan * or risk seizure of their nft collateral. Note if the type of the loan is fixed then this value is not used and * is irrelevant so it should be set to 0. * - loanAdminFeeInBasisPoints: The percent (measured in basis points) of the interest earned that will be * taken as a fee by the contract admins when the loan is repaid. The fee is stored in the loan struct to prevent an * attack where the contract admins could adjust the fee right before a loan is repaid, and take all of the interest * earned. * @param _bundleElements - the lists of erc721-20-1155 tokens that are to be bundled * @param _signature - The signature structure containing: * - signer: The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`. * - nonce: The nonce referred here is not the same as an Ethereum account's nonce. * We are referring instead to a nonce that is used by the lender or the borrower when they are first signing * off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an * off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the * lender or the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling * NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the nonce as used and prevents any future loan from * using the user's off-chain order that contains that nonce. * - expiry: Date when the signature expires * - signature: The ECDSA signature of the lender, obtained off-chain ahead of time, signing the following * combination of parameters: * - offer.loanERC20Denomination * - offer.loanPrincipalAmount * - offer.maximumRepaymentAmount * - offer.nftCollateralContract * - offer.nftCollateralId * - offer.referrer * - offer.loanDuration * - offer.loanAdminFeeInBasisPoints * - bundleElements * - signature.signer, * - signature.nonce, * - signature.expiry, * - address of this contract * - chainId */ function isValidLenderSignatureBundle( LoanData.Offer memory _offer, IBundleBuilder.BundleElements memory _bundleElements, LoanData.Signature memory _signature ) external view returns (bool) { return isValidLenderSignatureBundle(_offer, _bundleElements, _signature, address(this)); } /** * @dev This function overload the previous function to allow the caller to specify the address of the contract * */ function isValidLenderSignatureBundle( LoanData.Offer memory _offer, IBundleBuilder.BundleElements memory _bundleElements, LoanData.Signature memory _signature, address _loanContract ) public view returns (bool) { require(block.timestamp <= _signature.expiry, "Lender Signature has expired"); require(_loanContract != address(0), "Loan is zero address"); if (_signature.signer == address(0)) { return false; } else { bytes32 message = keccak256( abi.encodePacked( getEncodedOffer(_offer), abi.encode(_bundleElements), getEncodedSignature(_signature), _loanContract, getChainID() ) ); return SignatureChecker.isValidSignatureNow( _signature.signer, ECDSA.toEthSignedMessageHash(message), _signature.signature ); } } /** * @notice This function is called in renegotiateLoan() to validate the lender's signature that the lender provided * off-chain to verify that they did indeed want to agree to this loan renegotiation according to these terms. * * @param _loanId - The unique identifier for the loan to be renegotiated * @param _newLoanDuration - The new amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * @param _newMaximumRepaymentAmount - The new maximum amount of money that the borrower would be required to * retrieve their collateral, measured in the smallest units of the ERC20 currency used for the loan. The * borrower will always have to pay this amount to retrieve their collateral, regardless of whether they repay * early. * @param _renegotiationFee Agreed upon fee in ether that borrower pays for the lender for the renegitiation * @param _signature - The signature structure containing: * - signer: The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`. * - nonce: The nonce referred here is not the same as an Ethereum account's nonce. * We are referring instead to a nonce that is used by the lender or the borrower when they are first signing * off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an * off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the * lender or the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling NFTfi.cancelLoanCommitmentBeforeLoanHasBegun() * , which marks the nonce as used and prevents any future loan from using the user's off-chain order that contains * that nonce. * - expiry - The date when the renegotiation offer expires * - lenderSignature - The ECDSA signature of the lender, obtained off-chain ahead of time, signing the * following combination of parameters: * - _loanId * - _newLoanDuration * - _newMaximumRepaymentAmount * - _lender * - _lenderNonce * - _expiry * - address of this contract * - chainId */ function isValidLenderRenegotiationSignature( uint256 _loanId, uint32 _newLoanDuration, uint256 _newMaximumRepaymentAmount, uint256 _renegotiationFee, LoanData.Signature memory _signature ) external view returns (bool) { return isValidLenderRenegotiationSignature( _loanId, _newLoanDuration, _newMaximumRepaymentAmount, _renegotiationFee, _signature, address(this) ); } /** * @dev This function overload the previous function to allow the caller to specify the address of the contract * */ function isValidLenderRenegotiationSignature( uint256 _loanId, uint32 _newLoanDuration, uint256 _newMaximumRepaymentAmount, uint256 _renegotiationFee, LoanData.Signature memory _signature, address _loanContract ) public view returns (bool) { require(block.timestamp <= _signature.expiry, "Renegotiation Signature has expired"); require(_loanContract != address(0), "Loan is zero address"); if (_signature.signer == address(0)) { return false; } else { bytes32 message = keccak256( abi.encodePacked( _loanId, _newLoanDuration, _newMaximumRepaymentAmount, _renegotiationFee, getEncodedSignature(_signature), _loanContract, getChainID() ) ); return SignatureChecker.isValidSignatureNow( _signature.signer, ECDSA.toEthSignedMessageHash(message), _signature.signature ); } } /** * @dev We need this to avoid stack too deep errors. */ function getEncodedListing(LoanData.ListingTerms memory _listingTerms) internal pure returns (bytes memory) { return abi.encodePacked( _listingTerms.loanERC20Denomination, _listingTerms.minLoanPrincipalAmount, _listingTerms.maxLoanPrincipalAmount, _listingTerms.nftCollateralContract, _listingTerms.nftCollateralId, _listingTerms.revenueSharePartner, _listingTerms.minLoanDuration, _listingTerms.maxLoanDuration, _listingTerms.maxInterestRateForDurationInBasisPoints, _listingTerms.referralFeeInBasisPoints ); } /** * @dev We need this to avoid stack too deep errors. */ function getEncodedOffer(LoanData.Offer memory _offer) internal pure returns (bytes memory) { return abi.encodePacked( _offer.loanERC20Denomination, _offer.loanPrincipalAmount, _offer.maximumRepaymentAmount, _offer.nftCollateralContract, _offer.nftCollateralId, _offer.referrer, _offer.loanDuration, _offer.loanAdminFeeInBasisPoints ); } /** * @dev We need this to avoid stack too deep errors. */ function getEncodedSignature(LoanData.Signature memory _signature) internal pure returns (bytes memory) { return abi.encodePacked(_signature.signer, _signature.nonce, _signature.expiry); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; /** * @title INftfiHub * @author NFTfi * @dev NftfiHub interface */ interface INftfiHub { function setContract(string calldata _contractKey, address _contractAddress) external; function getContract(bytes32 _contractKey) external view returns (address); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; /** * @title IDirectLoanCoordinator * @author NFTfi * @dev DirectLoanCoordinator interface. */ interface IDirectLoanCoordinator { enum StatusType { NOT_EXISTS, NEW, RESOLVED } /** * @notice This struct contains data related to a loan * * @param smartNftId - The id of both the promissory note and obligation receipt. * @param status - The status in which the loan currently is. * @param loanContract - Address of the LoanType contract that created the loan. */ struct Loan { address loanContract; uint64 smartNftId; StatusType status; } function registerLoan(address _lender, bytes32 _loanType) external returns (uint32); function mintObligationReceipt(uint32 _loanId, address _borrower) external; function resolveLoan(uint32 _loanId) external; function promissoryNoteToken() external view returns (address); function obligationReceiptToken() external view returns (address); function getLoanData(uint32 _loanId) external view returns (Loan memory); function isValidLoanId(uint32 _loanId, address _loanContract) external view returns (bool); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; /** * @title INftTypeRegistry * @author NFTfi * @dev Interface for NFT Wrappers. */ interface INftWrapper { function transferNFT( address from, address to, address nftContract, uint256 tokenId ) external returns (bool); function isOwner( address owner, address nftContract, uint256 tokenId ) external view returns (bool); function wrapAirdropReceiver( address _recipient, address _nftContract, uint256 _nftId, address _beneficiary ) external returns (bool); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; interface IPermittedPartners { function getPartnerPermit(address _partner) external view returns (uint16); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; interface IPermittedERC20s { function getERC20Permit(address _erc20) external view returns (bool); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; interface IPermittedNFTs { function setNFTPermit(address _nftContract, string memory _nftType) external; function getNFTPermit(address _nftContract) external view returns (bytes32); function getNFTWrapper(address _nftContract) external view returns (address); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, 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; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @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); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://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); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; 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' 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) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _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 require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; interface IAirdropFlashLoan { function pullAirdrop( address _nftCollateralContract, uint256 _nftCollateralId, address _nftWrapper, address _target, bytes calldata _data, address _nftAirdrop, uint256 _nftAirdropId, bool _is1155, uint256 _nftAirdropAmount, address _beneficiary ) external; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; /** * @title IAirdropReceiver * @author NFTfi * @dev */ interface IAirdropReceiverFactory { function createAirdropReceiver(address _to) external returns (address, uint256); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; import "@openzeppelin/contracts/utils/Context.sol"; /** * @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. * * Modified version from openzeppelin/contracts/access/Ownable.sol that allows to * initialize the owner using a parameter in the constructor */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor(address _initialOwner) { _setOwner(_initialOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address _newOwner) public virtual onlyOwner { require(_newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(_newOwner); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Sets the owner. */ function _setOwner(address _newOwner) private { address oldOwner = _owner; _owner = _newOwner; emit OwnershipTransferred(oldOwner, _newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @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 Pausable is Context { /** * @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. */ constructor() { _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()); } } // SPDX-License-Identifier: MIT // 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; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** * @dev Handles the receipt of a single ERC1155 token type. This function is * called at the end of a `safeTransferFrom` after the balance has been updated. * * NOTE: To accept the transfer, this must return * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` * (i.e. 0xf23a6e61, or its own function selector). * * @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)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** * @dev Handles the receipt of a multiple ERC1155 token types. This function * is called at the end of a `safeBatchTransferFrom` after the balances have * been updated. * * NOTE: To accept the transfer(s), this must return * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * (i.e. 0xbc197c81, or its own function selector). * * @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)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/utils/ERC721Holder.sol) pragma solidity ^0.8.0; import "../IERC721Receiver.sol"; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721Holder is IERC721Receiver { /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address, address, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } } // SPDX-License-Identifier: MIT // 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 IERC721Receiver { /** * @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); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; interface IBundleBuilder { /** * @notice data of a erc721 bundle element * * @param tokenContract - address of the token contract * @param id - id of the token * @param safeTransferable - wether the implementing token contract has a safeTransfer function or not */ struct BundleElementERC721 { address tokenContract; uint256 id; bool safeTransferable; } /** * @notice data of a erc20 bundle element * * @param tokenContract - address of the token contract * @param amount - amount of the token */ struct BundleElementERC20 { address tokenContract; uint256 amount; } /** * @notice data of a erc20 bundle element * * @param tokenContract - address of the token contract * @param ids - list of ids of the tokens * @param amounts - list amounts of the tokens */ struct BundleElementERC1155 { address tokenContract; uint256[] ids; uint256[] amounts; } /** * @notice the lists of erc721-20-1155 tokens that are to be bundled * * @param erc721s list of erc721 tokens * @param erc20s list of erc20 tokens * @param erc1155s list of erc1155 tokens */ struct BundleElements { BundleElementERC721[] erc721s; BundleElementERC20[] erc20s; BundleElementERC1155[] erc1155s; } /** * @notice used by the loan contract to build a bundle from the BundleElements struct at the beginning of a loan, * returns the id of the created bundle * * @param _bundleElements - the lists of erc721-20-1155 tokens that are to be bundled * @param _sender sender of the tokens in the bundle - the borrower * @param _receiver receiver of the created bundle, normally the loan contract */ function buildBundle( BundleElements memory _bundleElements, address _sender, address _receiver ) external returns (uint256); /** * @notice Remove all the children from the bundle * @dev This method may run out of gas if the list of children is too big. In that case, children can be removed * individually. * @param _tokenId the id of the bundle * @param _receiver address of the receiver of the children */ function decomposeBundle(uint256 _tokenId, address _receiver) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/SignatureChecker.sol) pragma solidity ^0.8.0; import "./ECDSA.sol"; import "../Address.sol"; import "../../interfaces/IERC1271.sol"; /** * @dev Signature verification helper that can be used instead of `ECDSA.recover` to seamlessly support both ECDSA * signatures from externally owned accounts (EOAs) as well as ERC1271 signatures from smart contract wallets like * Argent and Gnosis Safe. * * _Available since v4.1._ */ library SignatureChecker { /** * @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the * signature is validated against that smart contract using ERC1271, otherwise it's validated using `ECDSA.recover`. * * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus * change through time. It could return true at block N and false at block N+1 (or the opposite). */ function isValidSignatureNow( address signer, bytes32 hash, bytes memory signature ) internal view returns (bool) { (address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(hash, signature); if (error == ECDSA.RecoverError.NoError && recovered == signer) { return true; } (bool success, bytes memory result) = signer.staticcall( abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature) ); return (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271.isValidSignature.selector); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @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. * * 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) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * 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)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC1271 standard signature validation method for * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271]. * * _Available since v4.1._ */ interface IERC1271 { /** * @dev Should return whether the signature provided is valid for the provided data * @param hash Hash of the data to be signed * @param signature Signature byte array associated with _data */ function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { 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); } }
We need this to avoid stack too deep errors./
function getEncodedListing(LoanData.ListingTerms memory _listingTerms) internal pure returns (bytes memory) { return abi.encodePacked( _listingTerms.loanERC20Denomination, _listingTerms.minLoanPrincipalAmount, _listingTerms.maxLoanPrincipalAmount, _listingTerms.nftCollateralContract, _listingTerms.nftCollateralId, _listingTerms.revenueSharePartner, _listingTerms.minLoanDuration, _listingTerms.maxLoanDuration, _listingTerms.maxInterestRateForDurationInBasisPoints, _listingTerms.referralFeeInBasisPoints ); }
1,474,592
/** *Submitted for verification at Etherscan.io on 2020-09-07 */ // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.4; interface IInterestRateModel { function utilizationRate( uint256 cash, uint256 borrows, uint256 reserves ) external pure returns (uint256); function getBorrowRate( uint256 cash, uint256 borrows, uint256 reserves ) external view returns (uint256); function getSupplyRate( uint256 cash, uint256 borrows, uint256 reserves, uint256 reserveFactorMantissa ) external view returns (uint256); function APR( uint256 cash, uint256 borrows, uint256 reserves ) external view returns (uint256); function APY( uint256 cash, uint256 borrows, uint256 reserves, uint256 reserveFactorMantissa ) external view returns (uint256); } interface IBankController { function getCashPrior(address underlying) external view returns (uint256); function getCashAfter(address underlying, uint256 msgValue) external view returns (uint256); function getFTokeAddress(address underlying) external view returns (address); function transferToUser( address token, address payable user, uint256 amount ) external; function transferIn( address account, address underlying, uint256 amount ) external payable; function borrowCheck( address account, address underlying, address fToken, uint256 borrowAmount ) external; function repayCheck(address underlying) external; function rewardForByType( address account, uint256 gasSpend, uint256 gasPrice, uint256 rewardType ) external; function liquidateBorrowCheck( address fTokenBorrowed, address fTokenCollateral, address borrower, address liquidator, uint256 repayAmount ) external; function liquidateTokens( address fTokenBorrowed, address fTokenCollateral, uint256 actualRepayAmount ) external view returns (uint256); function withdrawCheck( address fToken, address withdrawer, uint256 withdrawTokens ) external view returns (uint256); function transferCheck( address fToken, address src, address dst, uint256 transferTokens ) external; function marketsContains(address fToken) external view returns (bool); function seizeCheck(address cTokenCollateral, address cTokenBorrowed) external; function mintCheck(address underlying, address minter) external; function addReserves(address underlying, uint256 addAmount) external payable; function reduceReserves( address underlying, address payable account, uint256 reduceAmount ) external; function calcMaxBorrowAmount(address user, address token) external view returns (uint256); function calcMaxWithdrawAmount(address user, address token) external view returns (uint256); function calcMaxCashOutAmount(address user, address token) external view returns (uint256); function calcMaxBorrowAmountWithRatio(address user, address token) external view returns (uint256); function transferEthGasCost() external view returns (uint256); function isFTokenValid(address fToken) external view returns (bool); } 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; } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a <= b ? a : b; } function abs(uint256 a, uint256 b) internal pure returns (uint256) { if (a < b) { return b - a; } return a - b; } } contract Exponential { uint256 constant expScale = 1e18; uint256 constant doubleScale = 1e36; uint256 constant halfExpScale = expScale / 2; using SafeMath for uint256; function getExp(uint256 num, uint256 denom) public pure returns (uint256 rational) { rational = num.mul(expScale).div(denom); } function getDiv(uint256 num, uint256 denom) public pure returns (uint256 rational) { rational = num.mul(expScale).div(denom); } function addExp(uint256 a, uint256 b) public pure returns (uint256 result) { result = a.add(b); //injected INTEGER OVERFLOW OR UNDERFLOW } function subExp(uint256 a, uint256 b) public pure returns (uint256 result) { result = a.sub(b); //injected INTEGER OVERFLOW OR UNDERFLOW } function mulExp(uint256 a, uint256 b) public pure returns (uint256) { uint256 doubleScaledProduct = a.mul(b); uint256 doubleScaledProductWithHalfScale = halfExpScale.add( doubleScaledProduct ); return doubleScaledProductWithHalfScale.div(expScale); } function divExp(uint256 a, uint256 b) public pure returns (uint256) { return getDiv(a, b); } function mulExp3( uint256 a, uint256 b, uint256 c ) public pure returns (uint256) { return mulExp(mulExp(a, b), c); } function mulScalar(uint256 a, uint256 scalar) public pure returns (uint256 scaled) { scaled = a.mul(scalar); } function mulScalarTruncate(uint256 a, uint256 scalar) public pure returns (uint256) { uint256 product = mulScalar(a, scalar); return truncate(product); } function mulScalarTruncateAddUInt( uint256 a, uint256 scalar, uint256 addend ) public pure returns (uint256) { uint256 product = mulScalar(a, scalar); return truncate(product).add(addend); } function divScalarByExpTruncate(uint256 scalar, uint256 divisor) public pure returns (uint256) { uint256 fraction = divScalarByExp(scalar, divisor); return truncate(fraction); } function divScalarByExp(uint256 scalar, uint256 divisor) public pure returns (uint256) { uint256 numerator = expScale.mul(scalar); return getExp(numerator, divisor); } function divScalar(uint256 a, uint256 scalar) public pure returns (uint256) { return a.div(scalar); } function truncate(uint256 exp) public pure returns (uint256) { return exp.div(expScale); } } 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. */ function decimals() external view returns (uint8); event Approval( address indexed owner, address indexed spender, uint256 value ); } 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); } } } } 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" ); } } } library EthAddressLib { /** * @dev returns the address used within the protocol to identify ETH * @return the address assigned to ETH */ function ethAddress() internal pure returns (address) { return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } } interface IFToken is IERC20 { function mint(address user, uint256 amount) external returns (bytes memory); function borrow(address borrower, uint256 borrowAmount) external returns (bytes memory); function withdraw( address payable withdrawer, uint256 withdrawTokensIn, uint256 withdrawAmountIn ) external returns (uint256, bytes memory); function underlying() external view returns (address); function accrueInterest() external; function getAccountState(address account) external view returns ( uint256, uint256, uint256 ); function MonitorEventCallback( address who, bytes32 funcName, bytes calldata payload ) external; //1111111111111 function exchangeRateCurrent() external view returns (uint256 exchangeRate); function repay(address borrower, uint256 repayAmount) external returns (uint256, bytes memory); function borrowBalanceStored(address account) external view returns (uint256); function exchangeRateStored() external view returns (uint256 exchangeRate); function liquidateBorrow( address liquidator, address borrower, uint256 repayAmount, address fTokenCollateral ) external returns (bytes memory); function borrowBalanceCurrent(address account) external returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function _reduceReserves(uint256 reduceAmount) external; function _addReservesFresh(uint256 addAmount) external; function cancellingOut(address striker) external returns (bool strikeOk, bytes memory strikeLog); function APR() external view returns (uint256); function APY() external view returns (uint256); function calcBalanceOfUnderlying(address owner) external view returns (uint256); function borrowSafeRatio() external view returns (uint256); function tokenCash(address token, address account) external view returns (uint256); function getBorrowRate() external view returns (uint256); function addTotalCash(uint256 _addAmount) external; function subTotalCash(uint256 _subAmount) external; function totalCash() external view returns (uint256); } interface IBank { function MonitorEventCallback(bytes32 funcName, bytes calldata payload) external; function deposit(address token, uint256 amount) external payable; function borrow(address token, uint256 amount) external; function withdraw(address underlying, uint256 withdrawTokens) external; function withdrawUnderlying(address underlying, uint256 amount) external; function repay(address token, uint256 amount) external payable; function liquidateBorrow( address borrower, address underlyingBorrow, address underlyingCollateral, uint256 repayAmount ) external payable; function tokenIn(address token, uint256 amountIn) external payable; function tokenOut(address token, uint256 amountOut) external; function cancellingOut(address token) external; function paused() external view returns (bool); } 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 use in the initializer function of a contract. */ modifier initializer() { require( initializing || isConstructor() || !initialized, "Contract instance has already been initialized" ); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } contract FToken is Exponential, Initializable { using SafeERC20 for IERC20; uint256 public totalSupply; string public name; string public symbol; uint8 public decimals; mapping(address => mapping(address => uint256)) internal transferAllowances; uint256 public initialExchangeRate; address public admin; uint256 public totalBorrows; uint256 public totalReserves; uint256 public reserveFactor; uint256 public borrowIndex; uint256 internal constant borrowRateMax = 0.0005e16; uint256 public accrualBlockNumber; IInterestRateModel public interestRateModel; // 1 fToken 11111111 address public underlying; mapping(address => uint256) public accountTokens; IBankController public controller; uint256 public borrowSafeRatio; address public bank; // bank1111111 bool internal _notEntered; uint256 public constant ONE = 1e18; // 11111 struct BorrowSnapshot { uint256 principal; uint256 interestIndex; } mapping(address => BorrowSnapshot) public accountBorrows; uint256 public totalCash; event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); function initialize( uint256 _initialExchangeRate, address _controller, address _initialInterestRateModel, address _underlying, address _bank, uint256 _borrowSafeRatio, string memory _name, string memory _symbol, uint8 _decimals ) public initializer { initialExchangeRate = _initialExchangeRate; controller = IBankController(_controller); interestRateModel = IInterestRateModel(_initialInterestRateModel); admin = msg.sender; underlying = _underlying; borrowSafeRatio = _borrowSafeRatio; accrualBlockNumber = getBlockNumber(); borrowIndex = ONE; bank = _bank; name = _name; symbol = _symbol; decimals = _decimals; _notEntered = true; } modifier onlyAdmin { require(msg.sender == admin, "require admin"); _; } modifier onlyBank { require(msg.sender == bank, "require admin"); _; } modifier onlyController { require(msg.sender == address(controller), "require controller"); _; } modifier onlyRestricted { require( msg.sender == admin || msg.sender == bank || msg.sender == address(controller) || controller.marketsContains(msg.sender), "only restricted user" ); _; } modifier onlyBankComponent { require( msg.sender == bank || msg.sender == address(controller) || msg.sender == address(this) || controller.marketsContains(msg.sender), "only bank component" ); _; } modifier whenUnpaused { require(!IBank(bank).paused(), "System paused"); _; } function _setController(address _controller) external onlyAdmin { controller = IBankController(_controller); } function tokenCash(address token, address account) public view returns (uint256) { return token != EthAddressLib.ethAddress() ? IERC20(token).balanceOf(account) : address(account).balance; } struct TransferLogStruct { address user_address; address token_address; address cheque_token_address; uint256 amount_transferred; uint256 account_balance; address payee_address; uint256 payee_balance; uint256 global_token_reserved; } /** * @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 */ function transfer(address dst, uint256 amount) external nonReentrant returns (bool) { // spender - src - dst transferTokens(msg.sender, msg.sender, dst, amount); TransferLogStruct memory tls = TransferLogStruct( msg.sender, underlying, address(this), amount, balanceOf(msg.sender), dst, balanceOf(dst), tokenCash(underlying, address(controller)) ); IBank(bank).MonitorEventCallback("Transfer", abi.encode(tls)); return true; } /** * @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 */ function transferFrom( address src, address dst, uint256 amount ) external nonReentrant returns (bool) { // spender - src - dst transferTokens(msg.sender, src, dst, amount); TransferLogStruct memory tls = TransferLogStruct( msg.sender, underlying, address(this), amount, balanceOf(msg.sender), dst, balanceOf(dst), tokenCash(underlying, address(controller)) ); IBank(bank).MonitorEventCallback("TransferFrom", abi.encode(tls)); return true; } // tokens -> 111 fToken 111 function transferTokens( address spender, address src, address dst, uint256 tokens ) internal whenUnpaused returns (bool) { //accrueInterest(); controller.transferCheck(address(this), src, dst, tokens); require(src != dst, "Cannot transfer to self"); uint256 startingAllowance = 0; if (spender == src) { startingAllowance = uint256(-1); } else { startingAllowance = transferAllowances[src][spender]; } uint256 allowanceNew = startingAllowance.sub(tokens); accountTokens[src] = accountTokens[src].sub(tokens); accountTokens[dst] = accountTokens[dst].add(tokens); if (startingAllowance != uint256(-1)) { transferAllowances[src][spender] = allowanceNew; } emit Transfer(src, dst, tokens); return true; } /** * @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) */ function approve(address spender, uint256 amount) external returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @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 */ function allowance(address owner, address spender) external view returns (uint256) { return transferAllowances[owner][spender]; } struct MintLocals { uint256 exchangeRate; uint256 mintTokens; uint256 totalSupplyNew; uint256 accountTokensNew; uint256 actualMintAmount; } struct DepositLogStruct { address user_address; address token_address; address cheque_token_address; uint256 amount_deposited; uint256 underlying_deposited; uint256 cheque_token_value; uint256 loan_interest_rate; uint256 account_balance; uint256 global_token_reserved; } // 1111 function mint(address user, uint256 amount) external onlyBank nonReentrant returns (bytes memory) { accrueInterest(); return mintInternal(user, amount); } // 1111 function mintInternal(address user, uint256 amount) internal returns (bytes memory) { require(accrualBlockNumber == getBlockNumber(), "Blocknumber fails"); MintLocals memory tmp; controller.mintCheck(underlying, user); tmp.exchangeRate = exchangeRateStored(); tmp.mintTokens = divScalarByExpTruncate(amount, tmp.exchangeRate); tmp.totalSupplyNew = addExp(totalSupply, tmp.mintTokens); tmp.accountTokensNew = addExp(accountTokens[user], tmp.mintTokens); totalSupply = tmp.totalSupplyNew; accountTokens[user] = tmp.accountTokensNew; uint256 preCalcTokenCash = tokenCash(underlying, address(controller)) .add(amount); DepositLogStruct memory dls = DepositLogStruct( user, underlying, address(this), tmp.mintTokens, amount, exchangeRateAfter(amount), //cheque_token_value, 11111111111 interestRateModel.getBorrowRate( preCalcTokenCash, totalBorrows, totalReserves ), //loan_interest_rate 1111,11111111 tokenCash(address(this), user), preCalcTokenCash ); emit Transfer(address(0), user, tmp.mintTokens); return abi.encode(dls); } struct BorrowLocals { uint256 accountBorrows; uint256 accountBorrowsNew; uint256 totalBorrowsNew; } struct BorrowLogStruct { address user_address; address token_address; address cheque_token_address; uint256 amount_borrowed; uint256 interest_accrued; uint256 cheque_token_value; uint256 loan_interest_rate; uint256 account_debt; uint256 global_token_reserved; } // 1111 function borrow(address payable borrower, uint256 borrowAmount) external onlyBank nonReentrant returns (bytes memory) { accrueInterest(); return borrowInternal(borrower, borrowAmount); } // 1111 function borrowInternal(address payable borrower, uint256 borrowAmount) internal returns (bytes memory) { controller.borrowCheck( borrower, underlying, address(this), mulScalarTruncate(borrowAmount, borrowSafeRatio) ); require( controller.getCashPrior(underlying) >= borrowAmount, "Insufficient balance" ); BorrowLocals memory tmp; uint256 lastPrincipal = accountBorrows[borrower].principal; tmp.accountBorrows = borrowBalanceStoredInternal(borrower); tmp.accountBorrowsNew = addExp(tmp.accountBorrows, borrowAmount); tmp.totalBorrowsNew = addExp(totalBorrows, borrowAmount); accountBorrows[borrower].principal = tmp.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = tmp.totalBorrowsNew; controller.transferToUser(underlying, borrower, borrowAmount); subTotalCash(borrowAmount); BorrowLogStruct memory bls = BorrowLogStruct( borrower, underlying, address(this), borrowAmount, SafeMath.abs(tmp.accountBorrows, lastPrincipal), exchangeRateStored(), getBorrowRate(), accountBorrows[borrower].principal, tokenCash(underlying, address(controller)) ); return abi.encode(bls); } struct RepayLocals { uint256 repayAmount; uint256 borrowerIndex; uint256 accountBorrows; uint256 accountBorrowsNew; uint256 totalBorrowsNew; uint256 actualRepayAmount; } // 11111 function exchangeRateStored() public view returns (uint256 exchangeRate) { return calcExchangeRate(totalBorrows, totalReserves); } function calcExchangeRate(uint256 _totalBorrows, uint256 _totalReserves) public view returns (uint256 exchangeRate) { uint256 _totalSupply = totalSupply; if (_totalSupply == 0) { return initialExchangeRate; } else { /* * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint256 totalCash = controller.getCashPrior(underlying); uint256 cashPlusBorrowsMinusReserves = subExp( addExp(totalCash, _totalBorrows), _totalReserves ); exchangeRate = getDiv(cashPlusBorrowsMinusReserves, _totalSupply); } } // 11111(11)1111111111111111111111111 function exchangeRateAfter(uint256 transferInAmout) public view returns (uint256 exchangeRate) { uint256 _totalSupply = totalSupply; if (_totalSupply == 0) { // 11111111111111111111 return initialExchangeRate; } else { /* * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint256 totalCash = controller.getCashAfter( underlying, transferInAmout ); uint256 cashPlusBorrowsMinusReserves = subExp( addExp(totalCash, totalBorrows), totalReserves ); exchangeRate = getDiv(cashPlusBorrowsMinusReserves, _totalSupply); } } function balanceOfUnderlying(address owner) external returns (uint256) { // 1111 uint256 exchangeRate = exchangeRateCurrent(); // 11111 uint256 balance = mulScalarTruncate(exchangeRate, accountTokens[owner]); return balance; } function calcBalanceOfUnderlying(address owner) public view returns (uint256) { (, , uint256 _totalBorrows, uint256 _trotalReserves) = peekInterest(); uint256 _exchangeRate = calcExchangeRate( _totalBorrows, _trotalReserves ); // 11111 uint256 balance = mulScalarTruncate( _exchangeRate, accountTokens[owner] ); return balance; } function exchangeRateCurrent() public nonReentrant returns (uint256) { accrueInterest(); return exchangeRateStored(); } // 111111 function getAccountState(address account) external view returns ( uint256, uint256, uint256 ) { uint256 fTokenBalance = accountTokens[account]; uint256 borrowBalance = borrowBalanceStoredInternal(account); uint256 exchangeRate = exchangeRateStored(); return (fTokenBalance, borrowBalance, exchangeRate); } struct WithdrawLocals { uint256 exchangeRate; uint256 withdrawTokens; uint256 withdrawAmount; uint256 totalSupplyNew; uint256 accountTokensNew; } struct WithdrawLogStruct { address user_address; address token_address; address cheque_token_address; uint256 amount_withdrawed; uint256 underlying_withdrawed; uint256 cheque_token_value; uint256 loan_interest_rate; uint256 account_balance; uint256 global_token_reserved; } // todo onlyController function withdraw( address payable withdrawer, uint256 withdrawTokensIn, uint256 withdrawAmountIn ) external onlyBank nonReentrant returns (uint256, bytes memory) { accrueInterest(); return withdrawInternal(withdrawer, withdrawTokensIn, withdrawAmountIn); } function withdrawInternal( address payable withdrawer, uint256 withdrawTokensIn, uint256 withdrawAmountIn ) internal returns (uint256, bytes memory) { // 1111111 cTokens 11111111111 asset 1111111111 0 require( withdrawTokensIn == 0 || withdrawAmountIn == 0, "withdraw parameter not valid" ); WithdrawLocals memory tmp; tmp.exchangeRate = exchangeRateStored(); if (withdrawTokensIn > 0) { tmp.withdrawTokens = withdrawTokensIn; tmp.withdrawAmount = mulScalarTruncate( tmp.exchangeRate, withdrawTokensIn ); } else { tmp.withdrawTokens = divScalarByExpTruncate( withdrawAmountIn, tmp.exchangeRate ); tmp.withdrawAmount = withdrawAmountIn; } controller.withdrawCheck(address(this), withdrawer, tmp.withdrawTokens); require(accrualBlockNumber == getBlockNumber(), "Blocknumber fails"); tmp.totalSupplyNew = totalSupply.sub(tmp.withdrawTokens); tmp.accountTokensNew = accountTokens[withdrawer].sub( tmp.withdrawTokens ); require( controller.getCashPrior(underlying) >= tmp.withdrawAmount, "Insufficient money" ); controller.transferToUser(underlying, withdrawer, tmp.withdrawAmount); subTotalCash(tmp.withdrawAmount); totalSupply = tmp.totalSupplyNew; accountTokens[withdrawer] = tmp.accountTokensNew; WithdrawLogStruct memory wls = WithdrawLogStruct( withdrawer, underlying, address(this), tmp.withdrawTokens, tmp.withdrawAmount, exchangeRateStored(), getBorrowRate(), tokenCash(address(this), withdrawer), tokenCash(underlying, address(controller)) ); emit Transfer(withdrawer, address(0), tmp.withdrawTokens); return (tmp.withdrawAmount, abi.encode(wls)); } function strikeWithdrawInternal( address withdrawer, uint256 withdrawTokensIn, uint256 withdrawAmountIn ) internal returns (uint256, bytes memory) { // 1111111 cTokens 11111111111 asset 1111111111 0 require( withdrawTokensIn == 0 || withdrawAmountIn == 0, "withdraw parameter not valid" ); WithdrawLocals memory tmp; tmp.exchangeRate = exchangeRateStored(); if (withdrawTokensIn > 0) { tmp.withdrawTokens = withdrawTokensIn; tmp.withdrawAmount = mulScalarTruncate( tmp.exchangeRate, withdrawTokensIn ); } else { tmp.withdrawTokens = divScalarByExpTruncate( withdrawAmountIn, tmp.exchangeRate ); tmp.withdrawAmount = withdrawAmountIn; } require(accrualBlockNumber == getBlockNumber(), "Blocknumber fails"); tmp.totalSupplyNew = totalSupply.sub(tmp.withdrawTokens); tmp.accountTokensNew = accountTokens[withdrawer].sub( tmp.withdrawTokens ); totalSupply = tmp.totalSupplyNew; accountTokens[withdrawer] = tmp.accountTokensNew; uint256 preCalcTokenCash = tokenCash(underlying, address(controller)) .add(tmp.withdrawAmount); WithdrawLogStruct memory wls = WithdrawLogStruct( withdrawer, underlying, address(this), tmp.withdrawTokens, tmp.withdrawAmount, exchangeRateStored(), interestRateModel.getBorrowRate( preCalcTokenCash, totalBorrows, totalReserves ), tokenCash(address(this), withdrawer), preCalcTokenCash ); emit Transfer(withdrawer, address(0), tmp.withdrawTokens); return (tmp.withdrawAmount, abi.encode(wls)); } // 1111 function accrueInterest() public onlyRestricted { uint256 currentBlockNumber = getBlockNumber(); uint256 accrualBlockNumberPrior = accrualBlockNumber; // 11 111 if (accrualBlockNumberPrior == currentBlockNumber) { return; } uint256 cashPrior = controller.getCashPrior(underlying); uint256 borrowsPrior = totalBorrows; uint256 reservesPrior = totalReserves; uint256 borrowIndexPrior = borrowIndex; // // 111111 uint256 borrowRate = interestRateModel.getBorrowRate( cashPrior, borrowsPrior, reservesPrior ); // // 11111111 require(borrowRate <= borrowRateMax, "borrow rate is too high"); // // 1111 uint256 blockDelta = currentBlockNumber.sub(accrualBlockNumberPrior); /* * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ uint256 simpleInterestFactor; uint256 interestAccumulated; uint256 totalBorrowsNew; uint256 totalReservesNew; uint256 borrowIndexNew; simpleInterestFactor = mulScalar(borrowRate, blockDelta); interestAccumulated = divExp( mulExp(simpleInterestFactor, borrowsPrior), expScale ); totalBorrowsNew = addExp(interestAccumulated, borrowsPrior); totalReservesNew = addExp( divExp(mulExp(reserveFactor, interestAccumulated), expScale), reservesPrior ); borrowIndexNew = addExp( divExp(mulExp(simpleInterestFactor, borrowIndexPrior), expScale), borrowIndexPrior ); accrualBlockNumber = currentBlockNumber; borrowIndex = borrowIndexNew; totalBorrows = totalBorrowsNew; totalReserves = totalReservesNew; borrowRate = interestRateModel.getBorrowRate( cashPrior, totalBorrows, totalReserves ); // 11111111 require(borrowRate <= borrowRateMax, "borrow rate is too high"); } function peekInterest() public view returns ( uint256 _accrualBlockNumber, uint256 _borrowIndex, uint256 _totalBorrows, uint256 _totalReserves ) { _accrualBlockNumber = getBlockNumber(); uint256 accrualBlockNumberPrior = accrualBlockNumber; // 11 111 if (accrualBlockNumberPrior == _accrualBlockNumber) { return ( accrualBlockNumber, borrowIndex, totalBorrows, totalReserves ); } uint256 cashPrior = controller.getCashPrior(underlying); uint256 borrowsPrior = totalBorrows; uint256 reservesPrior = totalReserves; uint256 borrowIndexPrior = borrowIndex; // // 111111 uint256 borrowRate = interestRateModel.getBorrowRate( cashPrior, borrowsPrior, reservesPrior ); // // 11111111 require(borrowRate <= borrowRateMax, "borrow rate is too high"); // // 1111 uint256 blockDelta = _accrualBlockNumber.sub(accrualBlockNumberPrior); /* * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ uint256 simpleInterestFactor; uint256 interestAccumulated; uint256 totalBorrowsNew; uint256 totalReservesNew; uint256 borrowIndexNew; simpleInterestFactor = mulScalar(borrowRate, blockDelta); interestAccumulated = divExp( mulExp(simpleInterestFactor, borrowsPrior), expScale ); totalBorrowsNew = addExp(interestAccumulated, borrowsPrior); totalReservesNew = addExp( divExp(mulExp(reserveFactor, interestAccumulated), expScale), reservesPrior ); borrowIndexNew = addExp( divExp(mulExp(simpleInterestFactor, borrowIndexPrior), expScale), borrowIndexPrior ); _borrowIndex = borrowIndexNew; _totalBorrows = totalBorrowsNew; _totalReserves = totalReservesNew; borrowRate = interestRateModel.getBorrowRate( cashPrior, totalBorrows, totalReserves ); // 11111111 require(borrowRate <= borrowRateMax, "borrow rate is too high"); } function borrowBalanceCurrent(address account) external nonReentrant returns (uint256) { accrueInterest(); BorrowSnapshot memory borrowSnapshot = accountBorrows[account]; require(borrowSnapshot.interestIndex <= borrowIndex, "borrowIndex error"); return borrowBalanceStoredInternal(account); } function borrowBalanceStoredInternal(address user) internal view returns (uint256 result) { // 1111 BorrowSnapshot memory borrowSnapshot = accountBorrows[user]; if (borrowSnapshot.principal == 0) { return 0; } result = mulExp(borrowSnapshot.principal, divExp(borrowIndex, borrowSnapshot.interestIndex)); } function _setReserveFactorFresh(uint256 newReserveFactor) external onlyAdmin nonReentrant { accrueInterest(); require(accrualBlockNumber == getBlockNumber(), "Blocknumber fails"); reserveFactor = newReserveFactor; } function _setInterestRateModel(IInterestRateModel newInterestRateModel) external onlyAdmin { accrueInterest(); require(accrualBlockNumber == getBlockNumber(), "Blocknumber fails"); interestRateModel = newInterestRateModel; } function getBlockNumber() internal view returns (uint256) { return block.number; } function repay(address borrower, uint256 repayAmount) external onlyBank nonReentrant returns (uint256, bytes memory) { accrueInterest(); return repayInternal(borrower, repayAmount); } struct RepayLogStruct { address user_address; address token_address; address cheque_token_address; uint256 amount_repayed; uint256 interest_accrued; uint256 cheque_token_value; uint256 loan_interest_rate; uint256 account_debt; uint256 global_token_reserved; } function repayInternal(address borrower, uint256 repayAmount) internal returns (uint256, bytes memory) { controller.repayCheck(underlying); require(accrualBlockNumber == getBlockNumber(), "Blocknumber fails"); RepayLocals memory tmp; uint256 lastPrincipal = accountBorrows[borrower].principal; tmp.borrowerIndex = accountBorrows[borrower].interestIndex; tmp.accountBorrows = borrowBalanceStoredInternal(borrower); // -1 11111 if (repayAmount == uint256(-1)) { tmp.repayAmount = tmp.accountBorrows; } else { tmp.repayAmount = repayAmount; } tmp.accountBorrowsNew = tmp.accountBorrows.sub(tmp.repayAmount); if (totalBorrows < tmp.repayAmount) { tmp.totalBorrowsNew = 0; } else { tmp.totalBorrowsNew = totalBorrows.sub(tmp.repayAmount); } accountBorrows[borrower].principal = tmp.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = tmp.totalBorrowsNew; uint256 preCalcTokenCash = tokenCash(underlying, address(controller)) .add(tmp.repayAmount); RepayLogStruct memory rls = RepayLogStruct( borrower, underlying, address(this), tmp.repayAmount, SafeMath.abs(tmp.accountBorrows, lastPrincipal), exchangeRateAfter(tmp.repayAmount), //repay111111 interestRateModel.getBorrowRate( preCalcTokenCash, totalBorrows, totalReserves ), //repay1111111 accountBorrows[borrower].principal, preCalcTokenCash ); return (tmp.repayAmount, abi.encode(rls)); } function borrowBalanceStored(address account) external view returns (uint256) { return borrowBalanceStoredInternal(account); } struct LiquidateBorrowLogStruct { address user_address; address token_address; address cheque_token_address; uint256 debt_written_off; uint256 interest_accrued; address debtor_address; uint256 collateral_purchased; address collateral_cheque_token_address; uint256 debtor_balance; uint256 debt_remaining; uint256 cheque_token_value; uint256 loan_interest_rate; uint256 account_balance; uint256 global_token_reserved; } function liquidateBorrow( address liquidator, address borrower, uint256 repayAmount, FToken fTokenCollateral ) public onlyBank nonReentrant returns (bytes memory) { require( controller.isFTokenValid(address(this)) && controller.isFTokenValid(address(fTokenCollateral)), "Market not listed" ); accrueInterest(); fTokenCollateral.accrueInterest(); uint256 lastPrincipal = accountBorrows[borrower].principal; uint256 newPrincipal = borrowBalanceStoredInternal(borrower); controller.liquidateBorrowCheck( address(this), address(fTokenCollateral), borrower, liquidator, repayAmount ); require(accrualBlockNumber == getBlockNumber(), "Blocknumber fails"); require( fTokenCollateral.accrualBlockNumber() == getBlockNumber(), "Blocknumber fails" ); // 11 (uint256 actualRepayAmount, ) = repayInternal(borrower, repayAmount); // 11111111111fToken111 uint256 seizeTokens = controller.liquidateTokens( address(this), address(fTokenCollateral), actualRepayAmount ); // 1111111111111 require( fTokenCollateral.balanceOf(borrower) >= seizeTokens, "Seize too much" ); if (address(fTokenCollateral) == address(this)) { seizeInternal(address(this), liquidator, borrower, seizeTokens); } else { fTokenCollateral.seize(liquidator, borrower, seizeTokens); } uint256 preCalcTokenCash = tokenCash(underlying, address(controller)) .add(actualRepayAmount); LiquidateBorrowLogStruct memory lbls = LiquidateBorrowLogStruct( liquidator, underlying, address(this), actualRepayAmount, SafeMath.abs(newPrincipal, lastPrincipal), borrower, seizeTokens, address(fTokenCollateral), tokenCash(address(fTokenCollateral), borrower), accountBorrows[borrower].principal, //debt_remaining exchangeRateAfter(actualRepayAmount), interestRateModel.getBorrowRate( preCalcTokenCash, totalBorrows, totalReserves ), tokenCash(address(fTokenCollateral), liquidator), preCalcTokenCash ); return abi.encode(lbls); } function seize( address liquidator, address borrower, uint256 seizeTokens ) external nonReentrant { return seizeInternal(msg.sender, liquidator, borrower, seizeTokens); } struct CallingOutLogStruct { address user_address; address token_address; address cheque_token_address; uint256 amount_wiped_out; uint256 debt_cancelled_out; uint256 interest_accrued; uint256 cheque_token_value; uint256 loan_interest_rate; uint256 account_balance; uint256 account_debt; uint256 global_token_reserved; } //1111 function cancellingOut(address striker) public onlyBank nonReentrant returns (bool strikeOk, bytes memory strikeLog) { // 1111111111 if ( borrowBalanceStoredInternal(striker) > 0 && balanceOf(striker) > 0 ) { accrueInterest(); uint256 lastPrincipal = accountBorrows[striker].principal; uint256 curBorrowBalance = borrowBalanceStoredInternal(striker); uint256 userSupplyBalance = calcBalanceOfUnderlying(striker); uint256 lastFtokenBalance = balanceOf(striker); uint256 actualRepayAmount; bytes memory repayLog; uint256 withdrawAmount; bytes memory withdrawLog; // 111111(fToken) if (curBorrowBalance > 0 && userSupplyBalance > 0) { //11111111111111 if (userSupplyBalance > curBorrowBalance) { (withdrawAmount, withdrawLog) = strikeWithdrawInternal( striker, 0, curBorrowBalance ); } else { (withdrawAmount, withdrawLog) = strikeWithdrawInternal( striker, balanceOf(striker), 0 ); } (actualRepayAmount, repayLog) = repayInternal( striker, withdrawAmount ); CallingOutLogStruct memory cols; cols.user_address = striker; cols.token_address = underlying; cols.cheque_token_address = address(this); cols.amount_wiped_out = SafeMath.abs( lastFtokenBalance, balanceOf(striker) ); cols.debt_cancelled_out = actualRepayAmount; cols.interest_accrued = SafeMath.abs( curBorrowBalance, lastPrincipal ); cols.cheque_token_value = exchangeRateStored(); cols.loan_interest_rate = interestRateModel.getBorrowRate( tokenCash(underlying, address(controller)), totalBorrows, totalReserves ); cols.account_balance = tokenCash(address(this), striker); cols.account_debt = accountBorrows[striker].principal; cols.global_token_reserved = tokenCash( underlying, address(controller) ); strikeLog = abi.encode(cols); strikeOk = true; } } } function balanceOf(address owner) public view returns (uint256) { return accountTokens[owner]; } function _setBorrowSafeRatio(uint256 _borrowSafeRatio) public onlyAdmin { borrowSafeRatio = _borrowSafeRatio; } function seizeInternal( address seizerToken, address liquidator, address borrower, uint256 seizeTokens ) internal { require(borrower != liquidator, "Liquidator cannot be borrower"); controller.seizeCheck(msg.sender, seizerToken); accountTokens[borrower] = accountTokens[borrower].sub(seizeTokens); accountTokens[liquidator] = accountTokens[liquidator].add(seizeTokens); emit Transfer(borrower, liquidator, seizeTokens); } // onlyController function _reduceReserves(uint256 reduceAmount) external onlyController { accrueInterest(); require(accrualBlockNumber == getBlockNumber(), "Blocknumber fails"); require( controller.getCashPrior(underlying) >= reduceAmount, "Insufficient cash" ); require(totalReserves >= reduceAmount, "Insufficient reserves"); totalReserves = SafeMath.sub( totalReserves, reduceAmount, "reduce reserves underflow" ); } function _addReservesFresh(uint256 addAmount) external onlyController { accrueInterest(); require(accrualBlockNumber == getBlockNumber(), "Blocknumber fails"); totalReserves = SafeMath.add(totalReserves, addAmount); } function addTotalCash(uint256 _addAmount) public onlyBankComponent { totalCash = totalCash.add(_addAmount); //injected INTEGER OVERFLOW OR UNDERFLOW } function subTotalCash(uint256 _subAmount) public onlyBankComponent { totalCash = totalCash.sub(_subAmount); //injected INTEGER OVERFLOW OR UNDERFLOW } modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; } // 11111 function APR() public view returns (uint256) { uint256 cash = tokenCash(underlying, address(controller)); return interestRateModel.APR(cash, totalBorrows, totalReserves); } // 11111 function APY() external view returns (uint256) { uint256 cash = tokenCash(underlying, address(controller)); return interestRateModel.APY( cash, totalBorrows, totalReserves, reserveFactor ); } // 11111 function getBorrowRate() public view returns (uint256) { uint256 cash = tokenCash(underlying, address(controller)); return interestRateModel.getBorrowRate(cash, totalBorrows, totalReserves); } // 11111 function getSupplyRate() public view returns (uint256) { uint256 cash = tokenCash(underlying, address(controller)); return interestRateModel.getSupplyRate( cash, totalBorrows, totalReserves, reserveFactor ); } }
tokens -> 111 fToken 111accrueInterest();
function transferTokens( address spender, address src, address dst, uint256 tokens ) internal whenUnpaused returns (bool) { controller.transferCheck(address(this), src, dst, tokens); require(src != dst, "Cannot transfer to self"); uint256 startingAllowance = 0; if (spender == src) { startingAllowance = uint256(-1); startingAllowance = transferAllowances[src][spender]; } uint256 allowanceNew = startingAllowance.sub(tokens); accountTokens[src] = accountTokens[src].sub(tokens); accountTokens[dst] = accountTokens[dst].add(tokens); if (startingAllowance != uint256(-1)) { transferAllowances[src][spender] = allowanceNew; } emit Transfer(src, dst, tokens); return true; }
966,150
pragma solidity ^0.6.0; import "./IERC20.sol"; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint256) external; }
Interface of the ERC20 standard as defined in the EIP./
interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint256) external; }
2,482,278
pragma solidity 0.6.1; pragma experimental ABIEncoderV2; import "../lib/Ownable.sol"; import "../ZeroOne/IZeroOne.sol"; /** * @title CustomToken * @dev Contract implements custom tokens for ZeroOne */ contract CustomToken is Ownable { mapping (address => uint256) private balances; mapping (address => mapping (address => bool)) private tokenLocks; mapping (address => bool) private projectExists; mapping (address => uint) private projectsIndexes; mapping (address => uint) holdersIndexes; uint256 private _totalSupply; string private _name; string private _symbol; address[] holders; address[] projects; uint PROJECTS_LIMIT = 10; event Transfer(address from, address to, uint256 count); event TokensLocked(address project, address user); event TokensUnlocked(address project, address user); event HolderRemoved(address holder); event HolderAdded(address holder); event ProjectAdded(address project); event ProjectRemoved(address project); /** * @dev Contrsuctor of tokens * @param name name of token * @param symbol short name of token * @param totalSupply count of tokens */ constructor( string memory name, string memory symbol, uint256 totalSupply ) public { _totalSupply = totalSupply; _name = name; _symbol = symbol; balances[msg.sender] = totalSupply; holders.push(msg.sender); projects.push(address(0)); // skip first } modifier onlyZeroOne { require(projectExists[msg.sender] == true, "Project list does not contain provided address"); _; } /** * @dev returns amount of tokens * @return totalSupply */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev returns name of tokens * @return name of token */ function name() public view returns(string memory) { return _name; } /** * @dev returns symbol of tokens * @return symbol of token */ function symbol() public view returns(string memory) { return _symbol; } /** * @dev gets balance of tokens for {_user} * @param _user address of user * @return balance */ function balanceOf( address _user ) public view returns (uint256 balance) { return balances[_user]; } /** * @dev adds project to list * @param _project address of ballot project * @return success */ function addToProjects( address _project ) public onlyOwner returns (bool success) { require(_project != address(0), "Address must be non-empty"); require(!projectExists[_project], "Project is already in the list"); require(projects.length < PROJECTS_LIMIT+1, "Limit of projects are riched"); projects.push(_project); projectExists[_project] = true; projectsIndexes[_project] = projects.length - 1; emit ProjectAdded(_project); return true; } /** * @dev removes project from list * can called only by project, which will be removed * @param _project address of ZeroOne project */ function removeFromProjects( address _project ) public onlyZeroOne { require(isProjectAddress(_project), "Provided address is not in projects list"); uint index = projectsIndexes[_project]; address lastProjectInList = projects[projects.length - 1]; projectExists[_project] = false; projectsIndexes[_project] = 0; projects[index] = lastProjectInList; projectsIndexes[lastProjectInList] = index; projects.pop(); emit ProjectRemoved(_project); } /** * @dev Transfers tokens from _sender to _recipient * @param _sender address of token sender * @param _recipient address of recipient of tokens * @param _count count of tokens, which will be transferred */ function transfer( address _sender, address _recipient, uint256 _count ) internal { require(balances[_sender] >= _count, "Value must be less or equal user balance"); uint256 newSenderBalance = balances[_sender] - _count; uint256 newRecipientBalance = balances[_recipient] + _count; if (balances[_recipient] == 0) { addHolder(_recipient); } balances[_sender] = newSenderBalance; balances[_recipient] = newRecipientBalance; if (newSenderBalance == 0) { removeHolder(_sender); } emit Transfer(_sender, _recipient, _count); } /** * @dev finds ZeroOne projects, where user has voted and updates its votes in this project * @param _user address of user, which vote will be updated */ function onTokenTransfer( address _user ) internal { for (uint i = 1; i < projects.length - 1; i++) { if (isTokenLocked(projects[i], _user)) { IZeroOne project = IZeroOne(projects[i]); project.updateUserVote(address(this), _user, balanceOf(_user)); } } } /** * @dev Removes holder from the list * @param _holder holder, which will be removed from list */ function removeHolder( address _holder ) internal { uint index = holdersIndexes[_holder]; address lastHolderInList = holders[holders.length - 1]; holders[index] = lastHolderInList; holdersIndexes[lastHolderInList] = index; holders.pop(); emit HolderRemoved(_holder); } /** * @dev Adds holder to the list * @param _newHolder new holder, which will be added to list */ function addHolder( address _newHolder ) internal { holders.push(_newHolder); holdersIndexes[_newHolder] = holders.length - 1; emit HolderAdded(_newHolder); } /** * @dev Locks user tokens in project * @param _project address of ZeroOne project * @param _user address of user * @return status */ function lockTokens( address _project, address _user ) internal returns (bool status) { require(isProjectAddress(_project), "Provided address is not in project list"); require(!tokenLocks[_project][_user], "Tokens in this project is already locked"); tokenLocks[_project][_user] = true; emit TokensLocked(_project, _user); return tokenLocks[_project][_user]; } /** * @dev Unlocks user tokens in project * @param _project address of ZeroOne project * @param _user address of user * @return status */ function unlockTokens( address _project, address _user ) internal returns (bool status) { require(isProjectAddress(_project), "Provided address is not in project list"); tokenLocks[_project][_user] = false; emit TokensUnlocked(_project, _user); return !tokenLocks[_project][_user]; } /** * @dev getter for status of user tokens lock in project * @param _project address of ZeroOne project * @param _user address of user * @return isLocked */ function isTokenLocked( address _project, address _user ) public view returns (bool isLocked) { require(isProjectAddress(_project), "Address is not in project list"); return tokenLocks[_project][_user]; } /** * @dev Gets projects list * @return project list */ function getProjects() public view returns(address[] memory) { return projects; } /** * @dev Checks if address is used as project * @param _address address, which will be checked * @return isProject */ function isProjectAddress( address _address ) public view returns (bool isProject) { isProject = projectExists[_address]; } /** * @dev Locks tokens of msg.sender and sends vote to ballot * @param _sender address of user, which token will be locked * @param _reciepient address of ZeroOne project * @param _count count of tokens */ function transferFrom( address _sender, address _reciepient, uint256 _count ) public returns (bool) { require( (msg.sender == owner() || isProjectAddress(msg.sender)), "This operation is not allowed for this address" ); require(_sender != address(0), "Address must be non-empty"); require(balanceOf(_sender) > 0, "Balance of sender must be greater, then zero"); if (msg.sender == owner()) { transfer(_sender, _reciepient, _count); onTokenTransfer(_sender); onTokenTransfer(_reciepient); } else if (isProjectAddress(msg.sender)) { lockTokens(_reciepient, _sender); } return true; } /** * @dev unlocks the tokens of msg.sender * @param _project address of project * @return isUnlocked */ function revoke( address _project ) public returns(bool isUnlocked) { require(isProjectAddress(_project), "Address is not in project list"); IZeroOne project = IZeroOne(_project); require( project.didUserVote(address(this), msg.sender) == true, "User not voted, nothing to unlock" ); project.updateUserVote(address(this), msg.sender, 0); unlockTokens(_project, msg.sender); return !isTokenLocked(_project, msg.sender); } /** * @dev Transfers ownership of the contract to a new account (`_newOwner`). * Can only be called by the ZeroOne project. * @param _newOwner account, which will be setted as new owner */ function transferOwnership(address _newOwner) public onlyZeroOne { _transferOwnership(_newOwner); } // TODO:implements this after making Ballot // add check for address (address is project ?) }
Transfers ownership of the contract to a new account (`_newOwner`). Can only be called by the ZeroOne project. _newOwner account, which will be setted as new owner/
function transferOwnership(address _newOwner) public onlyZeroOne { _transferOwnership(_newOwner); }
13,050,877
./full_match/43113/0xCe2D11BCc11eC1ba2e6D2d1c86d72fe4bFa902E6/sources/avalance/black.sol
setMaxLiquidityAmount ./
function setMaxLiquidityAmount(uint256 maxTxPercent) external onlyOwner() { _maxLiquidityAmount = maxTxPercent; emit MaxLiquidityAmount(_maxLiquidityAmount); }
7,117,296
// SPDX-License-Identifier: MIT pragma solidity ^0.8.3; import "./UbiquityAlgorithmicDollarManager.sol"; import "./interfaces/IDollarMintingCalculator.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./TWAPOracle.sol"; import "./libs/ABDKMathQuad.sol"; /// @title A mock coupon calculator that always returns a constant contract DollarMintingCalculator is IDollarMintingCalculator { using ABDKMathQuad for uint256; using ABDKMathQuad for bytes16; bytes16 private immutable _one = (uint256(1 ether)).fromUInt(); UbiquityAlgorithmicDollarManager public manager; /// @param _manager the address of the manager contract so we can fetch variables constructor(address _manager) { manager = UbiquityAlgorithmicDollarManager(_manager); } /// @notice returns (TWAP_PRICE -1) * UAD_Total_Supply function getDollarsToMint() external view override returns (uint256) { TWAPOracle oracle = TWAPOracle(manager.twapOracleAddress()); uint256 twapPrice = oracle.consult(manager.dollarTokenAddress()); require(twapPrice > 1, "DollarMintingCalculator: not > 1"); return twapPrice .fromUInt() .sub(_one) .mul( ( IERC20(manager.dollarTokenAddress()) .totalSupply() .fromUInt() .div(_one) ) ) .toUInt(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.3; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./interfaces/IUbiquityAlgorithmicDollar.sol"; import "./interfaces/ICurveFactory.sol"; import "./interfaces/IMetaPool.sol"; import "./TWAPOracle.sol"; /// @title A central config for the uAD system. Also acts as a central /// access control manager. /// @notice For storing constants. For storing variables and allowing them to /// be changed by the admin (governance) /// @dev This should be used as a central access control manager which other /// contracts use to check permissions contract UbiquityAlgorithmicDollarManager is AccessControl { using SafeERC20 for IERC20; bytes32 public constant UBQ_MINTER_ROLE = keccak256("UBQ_MINTER_ROLE"); bytes32 public constant UBQ_BURNER_ROLE = keccak256("UBQ_BURNER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant COUPON_MANAGER_ROLE = keccak256("COUPON_MANAGER"); bytes32 public constant BONDING_MANAGER_ROLE = keccak256("BONDING_MANAGER"); bytes32 public constant INCENTIVE_MANAGER_ROLE = keccak256("INCENTIVE_MANAGER"); bytes32 public constant UBQ_TOKEN_MANAGER_ROLE = keccak256("UBQ_TOKEN_MANAGER_ROLE"); address public twapOracleAddress; address public debtCouponAddress; address public dollarTokenAddress; // uAD address public couponCalculatorAddress; address public dollarMintingCalculatorAddress; address public bondingShareAddress; address public bondingContractAddress; address public stableSwapMetaPoolAddress; address public curve3PoolTokenAddress; // 3CRV address public treasuryAddress; address public governanceTokenAddress; // uGOV address public sushiSwapPoolAddress; // sushi pool uAD-uGOV address public masterChefAddress; address public formulasAddress; address public autoRedeemTokenAddress; // uAR address public uarCalculatorAddress; // uAR calculator //key = address of couponmanager, value = excessdollardistributor mapping(address => address) private _excessDollarDistributors; modifier onlyAdmin() { require( hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "uADMGR: Caller is not admin" ); _; } constructor(address _admin) { _setupRole(DEFAULT_ADMIN_ROLE, _admin); _setupRole(UBQ_MINTER_ROLE, _admin); _setupRole(PAUSER_ROLE, _admin); _setupRole(COUPON_MANAGER_ROLE, _admin); _setupRole(BONDING_MANAGER_ROLE, _admin); _setupRole(INCENTIVE_MANAGER_ROLE, _admin); _setupRole(UBQ_TOKEN_MANAGER_ROLE, address(this)); } // TODO Add a generic setter for extra addresses that needs to be linked function setTwapOracleAddress(address _twapOracleAddress) external onlyAdmin { twapOracleAddress = _twapOracleAddress; // to be removed TWAPOracle oracle = TWAPOracle(twapOracleAddress); oracle.update(); } function setuARTokenAddress(address _uarTokenAddress) external onlyAdmin { autoRedeemTokenAddress = _uarTokenAddress; } function setDebtCouponAddress(address _debtCouponAddress) external onlyAdmin { debtCouponAddress = _debtCouponAddress; } function setIncentiveToUAD(address _account, address _incentiveAddress) external onlyAdmin { IUbiquityAlgorithmicDollar(dollarTokenAddress).setIncentiveContract( _account, _incentiveAddress ); } function setDollarTokenAddress(address _dollarTokenAddress) external onlyAdmin { dollarTokenAddress = _dollarTokenAddress; } function setGovernanceTokenAddress(address _governanceTokenAddress) external onlyAdmin { governanceTokenAddress = _governanceTokenAddress; } function setSushiSwapPoolAddress(address _sushiSwapPoolAddress) external onlyAdmin { sushiSwapPoolAddress = _sushiSwapPoolAddress; } function setUARCalculatorAddress(address _uarCalculatorAddress) external onlyAdmin { uarCalculatorAddress = _uarCalculatorAddress; } function setCouponCalculatorAddress(address _couponCalculatorAddress) external onlyAdmin { couponCalculatorAddress = _couponCalculatorAddress; } function setDollarMintingCalculatorAddress( address _dollarMintingCalculatorAddress ) external onlyAdmin { dollarMintingCalculatorAddress = _dollarMintingCalculatorAddress; } function setExcessDollarsDistributor( address debtCouponManagerAddress, address excessCouponDistributor ) external onlyAdmin { _excessDollarDistributors[ debtCouponManagerAddress ] = excessCouponDistributor; } function setMasterChefAddress(address _masterChefAddress) external onlyAdmin { masterChefAddress = _masterChefAddress; } function setFormulasAddress(address _formulasAddress) external onlyAdmin { formulasAddress = _formulasAddress; } function setBondingShareAddress(address _bondingShareAddress) external onlyAdmin { bondingShareAddress = _bondingShareAddress; } function setStableSwapMetaPoolAddress(address _stableSwapMetaPoolAddress) external onlyAdmin { stableSwapMetaPoolAddress = _stableSwapMetaPoolAddress; } /** @notice set the bonding bontract smart contract address @dev bonding contract participants deposit curve LP token for a certain duration to earn uGOV and more curve LP token @param _bondingContractAddress bonding contract address */ function setBondingContractAddress(address _bondingContractAddress) external onlyAdmin { bondingContractAddress = _bondingContractAddress; } /** @notice set the treasury address @dev the treasury fund is used to maintain the protocol @param _treasuryAddress treasury fund address */ function setTreasuryAddress(address _treasuryAddress) external onlyAdmin { treasuryAddress = _treasuryAddress; } /** @notice deploy a new Curve metapools for uAD Token uAD/3Pool @dev From the curve documentation for uncollateralized algorithmic stablecoins amplification should be 5-10 @param _curveFactory MetaPool factory address @param _crvBasePool Address of the base pool to use within the new metapool. @param _crv3PoolTokenAddress curve 3Pool token Address @param _amplificationCoefficient amplification coefficient. The smaller it is the closer to a constant product we are. @param _fee Trade fee, given as an integer with 1e10 precision. */ function deployStableSwapPool( address _curveFactory, address _crvBasePool, address _crv3PoolTokenAddress, uint256 _amplificationCoefficient, uint256 _fee ) external onlyAdmin { // Create new StableSwap meta pool (uAD <-> 3Crv) address metaPool = ICurveFactory(_curveFactory).deploy_metapool( _crvBasePool, ERC20(dollarTokenAddress).name(), ERC20(dollarTokenAddress).symbol(), dollarTokenAddress, _amplificationCoefficient, _fee ); stableSwapMetaPoolAddress = metaPool; // Approve the newly-deployed meta pool to transfer this contract's funds uint256 crv3PoolTokenAmount = IERC20(_crv3PoolTokenAddress).balanceOf(address(this)); uint256 uADTokenAmount = IERC20(dollarTokenAddress).balanceOf(address(this)); // safe approve revert if approve from non-zero to non-zero allowance IERC20(_crv3PoolTokenAddress).safeApprove(metaPool, 0); IERC20(_crv3PoolTokenAddress).safeApprove( metaPool, crv3PoolTokenAmount ); IERC20(dollarTokenAddress).safeApprove(metaPool, 0); IERC20(dollarTokenAddress).safeApprove(metaPool, uADTokenAmount); // coin at index 0 is uAD and index 1 is 3CRV require( IMetaPool(metaPool).coins(0) == dollarTokenAddress && IMetaPool(metaPool).coins(1) == _crv3PoolTokenAddress, "uADMGR: COIN_ORDER_MISMATCH" ); // Add the initial liquidity to the StableSwap meta pool uint256[2] memory amounts = [ IERC20(dollarTokenAddress).balanceOf(address(this)), IERC20(_crv3PoolTokenAddress).balanceOf(address(this)) ]; // set curve 3Pool address curve3PoolTokenAddress = _crv3PoolTokenAddress; IMetaPool(metaPool).add_liquidity(amounts, 0, msg.sender); } function getExcessDollarsDistributor(address _debtCouponManagerAddress) external view returns (address) { return _excessDollarDistributors[_debtCouponManagerAddress]; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.3; import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol"; /// @title A mechanism for calculating dollars to be minted interface IDollarMintingCalculator { function getDollarsToMint() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.3; import "./interfaces/IMetaPool.sol"; contract TWAPOracle { address public immutable pool; address public immutable token0; address public immutable token1; uint256 public price0Average; uint256 public price1Average; uint256 public pricesBlockTimestampLast; uint256[2] public priceCumulativeLast; constructor( address _pool, address _uADtoken0, address _curve3CRVtoken1 ) { pool = _pool; // coin at index 0 is uAD and index 1 is 3CRV require( IMetaPool(_pool).coins(0) == _uADtoken0 && IMetaPool(_pool).coins(1) == _curve3CRVtoken1, "TWAPOracle: COIN_ORDER_MISMATCH" ); token0 = _uADtoken0; token1 = _curve3CRVtoken1; uint256 _reserve0 = uint112(IMetaPool(_pool).balances(0)); uint256 _reserve1 = uint112(IMetaPool(_pool).balances(1)); // ensure that there's liquidity in the pair require(_reserve0 != 0 && _reserve1 != 0, "TWAPOracle: NO_RESERVES"); // ensure that pair balance is perfect require(_reserve0 == _reserve1, "TWAPOracle: PAIR_UNBALANCED"); priceCumulativeLast = IMetaPool(_pool).get_price_cumulative_last(); pricesBlockTimestampLast = IMetaPool(_pool).block_timestamp_last(); price0Average = 1 ether; price1Average = 1 ether; } // calculate average price function update() external { (uint256[2] memory priceCumulative, uint256 blockTimestamp) = _currentCumulativePrices(); if (blockTimestamp - pricesBlockTimestampLast > 0) { // get the balances between now and the last price cumulative snapshot uint256[2] memory twapBalances = IMetaPool(pool).get_twap_balances( priceCumulativeLast, priceCumulative, blockTimestamp - pricesBlockTimestampLast ); // price to exchange amounIn uAD to 3CRV based on TWAP price0Average = IMetaPool(pool).get_dy(0, 1, 1 ether, twapBalances); // price to exchange amounIn 3CRV to uAD based on TWAP price1Average = IMetaPool(pool).get_dy(1, 0, 1 ether, twapBalances); // we update the priceCumulative priceCumulativeLast = priceCumulative; pricesBlockTimestampLast = blockTimestamp; } } // note this will always return 0 before update has been called successfully // for the first time. function consult(address token) external view returns (uint256 amountOut) { if (token == token0) { // price to exchange 1 uAD to 3CRV based on TWAP amountOut = price0Average; } else { require(token == token1, "TWAPOracle: INVALID_TOKEN"); // price to exchange 1 3CRV to uAD based on TWAP amountOut = price1Average; } } function _currentCumulativePrices() internal view returns (uint256[2] memory priceCumulative, uint256 blockTimestamp) { priceCumulative = IMetaPool(pool).get_price_cumulative_last(); blockTimestamp = IMetaPool(pool).block_timestamp_last(); } } // SPDX-License-Identifier: BSD-4-Clause /* * ABDK Math Quad Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.8.0; /** * Smart contract library of mathematical functions operating with IEEE 754 * quadruple-precision binary floating-point numbers (quadruple precision * numbers). As long as quadruple precision numbers are 16-bytes long, they are * represented by bytes16 type. */ library ABDKMathQuad { /* * 0. */ bytes16 private constant _POSITIVE_ZERO = 0x00000000000000000000000000000000; /* * -0. */ bytes16 private constant _NEGATIVE_ZERO = 0x80000000000000000000000000000000; /* * +Infinity. */ bytes16 private constant _POSITIVE_INFINITY = 0x7FFF0000000000000000000000000000; /* * -Infinity. */ bytes16 private constant _NEGATIVE_INFINITY = 0xFFFF0000000000000000000000000000; /* * Canonical NaN value. */ bytes16 private constant NaN = 0x7FFF8000000000000000000000000000; /** * Convert signed 256-bit integer number into quadruple precision number. * * @param x signed 256-bit integer number * @return quadruple precision number */ function fromInt(int256 x) internal pure returns (bytes16) { unchecked { if (x == 0) return bytes16(0); else { // We rely on overflow behavior here uint256 result = uint256(x > 0 ? x : -x); uint256 msb = mostSignificantBit(result); if (msb < 112) result <<= 112 - msb; else if (msb > 112) result >>= msb - 112; result = (result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | ((16383 + msb) << 112); if (x < 0) result |= 0x80000000000000000000000000000000; return bytes16(uint128(result)); } } } /** * Convert quadruple precision number into signed 256-bit integer number * rounding towards zero. Revert on overflow. * * @param x quadruple precision number * @return signed 256-bit integer number */ function toInt(bytes16 x) internal pure returns (int256) { unchecked { uint256 exponent = (uint128(x) >> 112) & 0x7FFF; require(exponent <= 16638); // Overflow if (exponent < 16383) return 0; // Underflow uint256 result = (uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | 0x10000000000000000000000000000; if (exponent < 16495) result >>= 16495 - exponent; else if (exponent > 16495) result <<= exponent - 16495; if (uint128(x) >= 0x80000000000000000000000000000000) { // Negative require( result <= 0x8000000000000000000000000000000000000000000000000000000000000000 ); return -int256(result); // We rely on overflow behavior here } else { require( result <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF ); return int256(result); } } } /** * Convert unsigned 256-bit integer number into quadruple precision number. * * @param x unsigned 256-bit integer number * @return quadruple precision number */ function fromUInt(uint256 x) internal pure returns (bytes16) { unchecked { if (x == 0) return bytes16(0); else { uint256 result = x; uint256 msb = mostSignificantBit(result); if (msb < 112) result <<= 112 - msb; else if (msb > 112) result >>= msb - 112; result = (result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | ((16383 + msb) << 112); return bytes16(uint128(result)); } } } /** * Convert quadruple precision number into unsigned 256-bit integer number * rounding towards zero. Revert on underflow. Note, that negative floating * point numbers in range (-1.0 .. 0.0) may be converted to unsigned integer * without error, because they are rounded to zero. * * @param x quadruple precision number * @return unsigned 256-bit integer number */ function toUInt(bytes16 x) internal pure returns (uint256) { unchecked { uint256 exponent = (uint128(x) >> 112) & 0x7FFF; if (exponent < 16383) return 0; // Underflow require(uint128(x) < 0x80000000000000000000000000000000); // Negative require(exponent <= 16638); // Overflow uint256 result = (uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | 0x10000000000000000000000000000; if (exponent < 16495) result >>= 16495 - exponent; else if (exponent > 16495) result <<= exponent - 16495; return result; } } /** * Convert signed 128.128 bit fixed point number into quadruple precision * number. * * @param x signed 128.128 bit fixed point number * @return quadruple precision number */ function from128x128(int256 x) internal pure returns (bytes16) { unchecked { if (x == 0) return bytes16(0); else { // We rely on overflow behavior here uint256 result = uint256(x > 0 ? x : -x); uint256 msb = mostSignificantBit(result); if (msb < 112) result <<= 112 - msb; else if (msb > 112) result >>= msb - 112; result = (result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | ((16255 + msb) << 112); if (x < 0) result |= 0x80000000000000000000000000000000; return bytes16(uint128(result)); } } } /** * Convert quadruple precision number into signed 128.128 bit fixed point * number. Revert on overflow. * * @param x quadruple precision number * @return signed 128.128 bit fixed point number */ function to128x128(bytes16 x) internal pure returns (int256) { unchecked { uint256 exponent = (uint128(x) >> 112) & 0x7FFF; require(exponent <= 16510); // Overflow if (exponent < 16255) return 0; // Underflow uint256 result = (uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | 0x10000000000000000000000000000; if (exponent < 16367) result >>= 16367 - exponent; else if (exponent > 16367) result <<= exponent - 16367; if (uint128(x) >= 0x80000000000000000000000000000000) { // Negative require( result <= 0x8000000000000000000000000000000000000000000000000000000000000000 ); return -int256(result); // We rely on overflow behavior here } else { require( result <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF ); return int256(result); } } } /** * Convert signed 64.64 bit fixed point number into quadruple precision * number. * * @param x signed 64.64 bit fixed point number * @return quadruple precision number */ function from64x64(int128 x) internal pure returns (bytes16) { unchecked { if (x == 0) return bytes16(0); else { // We rely on overflow behavior here uint256 result = uint128(x > 0 ? x : -x); uint256 msb = mostSignificantBit(result); if (msb < 112) result <<= 112 - msb; else if (msb > 112) result >>= msb - 112; result = (result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | ((16319 + msb) << 112); if (x < 0) result |= 0x80000000000000000000000000000000; return bytes16(uint128(result)); } } } /** * Convert quadruple precision number into signed 64.64 bit fixed point * number. Revert on overflow. * * @param x quadruple precision number * @return signed 64.64 bit fixed point number */ function to64x64(bytes16 x) internal pure returns (int128) { unchecked { uint256 exponent = (uint128(x) >> 112) & 0x7FFF; require(exponent <= 16446); // Overflow if (exponent < 16319) return 0; // Underflow uint256 result = (uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | 0x10000000000000000000000000000; if (exponent < 16431) result >>= 16431 - exponent; else if (exponent > 16431) result <<= exponent - 16431; if (uint128(x) >= 0x80000000000000000000000000000000) { // Negative require(result <= 0x80000000000000000000000000000000); return -int128(int256(result)); // We rely on overflow behavior here } else { require(result <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128(int256(result)); } } } /** * Convert octuple precision number into quadruple precision number. * * @param x octuple precision number * @return quadruple precision number */ function fromOctuple(bytes32 x) internal pure returns (bytes16) { unchecked { bool negative = x & 0x8000000000000000000000000000000000000000000000000000000000000000 > 0; uint256 exponent = (uint256(x) >> 236) & 0x7FFFF; uint256 significand = uint256(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; if (exponent == 0x7FFFF) { if (significand > 0) return NaN; else return negative ? _NEGATIVE_INFINITY : _POSITIVE_INFINITY; } if (exponent > 278526) return negative ? _NEGATIVE_INFINITY : _POSITIVE_INFINITY; else if (exponent < 245649) return negative ? _NEGATIVE_ZERO : _POSITIVE_ZERO; else if (exponent < 245761) { significand = (significand | 0x100000000000000000000000000000000000000000000000000000000000) >> (245885 - exponent); exponent = 0; } else { significand >>= 124; exponent -= 245760; } uint128 result = uint128(significand | (exponent << 112)); if (negative) result |= 0x80000000000000000000000000000000; return bytes16(result); } } /** * Convert quadruple precision number into octuple precision number. * * @param x quadruple precision number * @return octuple precision number */ function toOctuple(bytes16 x) internal pure returns (bytes32) { unchecked { uint256 exponent = (uint128(x) >> 112) & 0x7FFF; uint256 result = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; if (exponent == 0x7FFF) exponent = 0x7FFFF; // Infinity or NaN else if (exponent == 0) { if (result > 0) { uint256 msb = mostSignificantBit(result); result = (result << (236 - msb)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; exponent = 245649 + msb; } } else { result <<= 124; exponent += 245760; } result |= exponent << 236; if (uint128(x) >= 0x80000000000000000000000000000000) result |= 0x8000000000000000000000000000000000000000000000000000000000000000; return bytes32(result); } } /** * Convert double precision number into quadruple precision number. * * @param x double precision number * @return quadruple precision number */ function fromDouble(bytes8 x) internal pure returns (bytes16) { unchecked { uint256 exponent = (uint64(x) >> 52) & 0x7FF; uint256 result = uint64(x) & 0xFFFFFFFFFFFFF; if (exponent == 0x7FF) exponent = 0x7FFF; // Infinity or NaN else if (exponent == 0) { if (result > 0) { uint256 msb = mostSignificantBit(result); result = (result << (112 - msb)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; exponent = 15309 + msb; } } else { result <<= 60; exponent += 15360; } result |= exponent << 112; if (x & 0x8000000000000000 > 0) result |= 0x80000000000000000000000000000000; return bytes16(uint128(result)); } } /** * Convert quadruple precision number into double precision number. * * @param x quadruple precision number * @return double precision number */ function toDouble(bytes16 x) internal pure returns (bytes8) { unchecked { bool negative = uint128(x) >= 0x80000000000000000000000000000000; uint256 exponent = (uint128(x) >> 112) & 0x7FFF; uint256 significand = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; if (exponent == 0x7FFF) { if (significand > 0) return 0x7FF8000000000000; // NaN else return negative ? bytes8(0xFFF0000000000000) // -Infinity : bytes8(0x7FF0000000000000); // Infinity } if (exponent > 17406) return negative ? bytes8(0xFFF0000000000000) // -Infinity : bytes8(0x7FF0000000000000); // Infinity else if (exponent < 15309) return negative ? bytes8(0x8000000000000000) // -0 : bytes8(0x0000000000000000); // 0 else if (exponent < 15361) { significand = (significand | 0x10000000000000000000000000000) >> (15421 - exponent); exponent = 0; } else { significand >>= 60; exponent -= 15360; } uint64 result = uint64(significand | (exponent << 52)); if (negative) result |= 0x8000000000000000; return bytes8(result); } } /** * Test whether given quadruple precision number is NaN. * * @param x quadruple precision number * @return true if x is NaN, false otherwise */ function isNaN(bytes16 x) internal pure returns (bool) { unchecked { return uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF > 0x7FFF0000000000000000000000000000; } } /** * Test whether given quadruple precision number is positive or negative * infinity. * * @param x quadruple precision number * @return true if x is positive or negative infinity, false otherwise */ function isInfinity(bytes16 x) internal pure returns (bool) { unchecked { return uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0x7FFF0000000000000000000000000000; } } /** * Calculate sign of x, i.e. -1 if x is negative, 0 if x if zero, and 1 if x * is positive. Note that sign (-0) is zero. Revert if x is NaN. * * @param x quadruple precision number * @return sign of x */ function sign(bytes16 x) internal pure returns (int8) { unchecked { uint128 absoluteX = uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; require(absoluteX <= 0x7FFF0000000000000000000000000000); // Not NaN if (absoluteX == 0) return 0; else if (uint128(x) >= 0x80000000000000000000000000000000) return -1; else return 1; } } /** * Calculate sign (x - y). Revert if either argument is NaN, or both * arguments are infinities of the same sign. * * @param x quadruple precision number * @param y quadruple precision number * @return sign (x - y) */ function cmp(bytes16 x, bytes16 y) internal pure returns (int8) { unchecked { uint128 absoluteX = uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; require(absoluteX <= 0x7FFF0000000000000000000000000000); // Not NaN uint128 absoluteY = uint128(y) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; require(absoluteY <= 0x7FFF0000000000000000000000000000); // Not NaN // Not infinities of the same sign require(x != y || absoluteX < 0x7FFF0000000000000000000000000000); if (x == y) return 0; else { bool negativeX = uint128(x) >= 0x80000000000000000000000000000000; bool negativeY = uint128(y) >= 0x80000000000000000000000000000000; if (negativeX) { if (negativeY) return absoluteX > absoluteY ? -1 : int8(1); else return -1; } else { if (negativeY) return 1; else return absoluteX > absoluteY ? int8(1) : -1; } } } } /** * Test whether x equals y. NaN, infinity, and -infinity are not equal to * anything. * * @param x quadruple precision number * @param y quadruple precision number * @return true if x equals to y, false otherwise */ function eq(bytes16 x, bytes16 y) internal pure returns (bool) { unchecked { if (x == y) { return uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF < 0x7FFF0000000000000000000000000000; } else return false; } } /** * Calculate x + y. Special values behave in the following way: * * NaN + x = NaN for any x. * Infinity + x = Infinity for any finite x. * -Infinity + x = -Infinity for any finite x. * Infinity + Infinity = Infinity. * -Infinity + -Infinity = -Infinity. * Infinity + -Infinity = -Infinity + Infinity = NaN. * * @param x quadruple precision number * @param y quadruple precision number * @return quadruple precision number */ function add(bytes16 x, bytes16 y) internal pure returns (bytes16) { unchecked { uint256 xExponent = (uint128(x) >> 112) & 0x7FFF; uint256 yExponent = (uint128(y) >> 112) & 0x7FFF; if (xExponent == 0x7FFF) { if (yExponent == 0x7FFF) { if (x == y) return x; else return NaN; } else return x; } else if (yExponent == 0x7FFF) return y; else { bool xSign = uint128(x) >= 0x80000000000000000000000000000000; uint256 xSignifier = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; if (xExponent == 0) xExponent = 1; else xSignifier |= 0x10000000000000000000000000000; bool ySign = uint128(y) >= 0x80000000000000000000000000000000; uint256 ySignifier = uint128(y) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; if (yExponent == 0) yExponent = 1; else ySignifier |= 0x10000000000000000000000000000; if (xSignifier == 0) return y == _NEGATIVE_ZERO ? _POSITIVE_ZERO : y; else if (ySignifier == 0) return x == _NEGATIVE_ZERO ? _POSITIVE_ZERO : x; else { int256 delta = int256(xExponent) - int256(yExponent); if (xSign == ySign) { if (delta > 112) return x; else if (delta > 0) ySignifier >>= uint256(delta); else if (delta < -112) return y; else if (delta < 0) { xSignifier >>= uint256(-delta); xExponent = yExponent; } xSignifier += ySignifier; if (xSignifier >= 0x20000000000000000000000000000) { xSignifier >>= 1; xExponent += 1; } if (xExponent == 0x7FFF) return xSign ? _NEGATIVE_INFINITY : _POSITIVE_INFINITY; else { if (xSignifier < 0x10000000000000000000000000000) xExponent = 0; else xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; return bytes16( uint128( ( xSign ? 0x80000000000000000000000000000000 : 0 ) | (xExponent << 112) | xSignifier ) ); } } else { if (delta > 0) { xSignifier <<= 1; xExponent -= 1; } else if (delta < 0) { ySignifier <<= 1; xExponent = yExponent - 1; } if (delta > 112) ySignifier = 1; else if (delta > 1) ySignifier = ((ySignifier - 1) >> uint256(delta - 1)) + 1; else if (delta < -112) xSignifier = 1; else if (delta < -1) xSignifier = ((xSignifier - 1) >> uint256(-delta - 1)) + 1; if (xSignifier >= ySignifier) xSignifier -= ySignifier; else { xSignifier = ySignifier - xSignifier; xSign = ySign; } if (xSignifier == 0) return _POSITIVE_ZERO; uint256 msb = mostSignificantBit(xSignifier); if (msb == 113) { xSignifier = (xSignifier >> 1) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; xExponent += 1; } else if (msb < 112) { uint256 shift = 112 - msb; if (xExponent > shift) { xSignifier = (xSignifier << shift) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; xExponent -= shift; } else { xSignifier <<= xExponent - 1; xExponent = 0; } } else xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; if (xExponent == 0x7FFF) return xSign ? _NEGATIVE_INFINITY : _POSITIVE_INFINITY; else return bytes16( uint128( ( xSign ? 0x80000000000000000000000000000000 : 0 ) | (xExponent << 112) | xSignifier ) ); } } } } } /** * Calculate x - y. Special values behave in the following way: * * NaN - x = NaN for any x. * Infinity - x = Infinity for any finite x. * -Infinity - x = -Infinity for any finite x. * Infinity - -Infinity = Infinity. * -Infinity - Infinity = -Infinity. * Infinity - Infinity = -Infinity - -Infinity = NaN. * * @param x quadruple precision number * @param y quadruple precision number * @return quadruple precision number */ function sub(bytes16 x, bytes16 y) internal pure returns (bytes16) { unchecked {return add(x, y ^ 0x80000000000000000000000000000000);} } /** * Calculate x * y. Special values behave in the following way: * * NaN * x = NaN for any x. * Infinity * x = Infinity for any finite positive x. * Infinity * x = -Infinity for any finite negative x. * -Infinity * x = -Infinity for any finite positive x. * -Infinity * x = Infinity for any finite negative x. * Infinity * 0 = NaN. * -Infinity * 0 = NaN. * Infinity * Infinity = Infinity. * Infinity * -Infinity = -Infinity. * -Infinity * Infinity = -Infinity. * -Infinity * -Infinity = Infinity. * * @param x quadruple precision number * @param y quadruple precision number * @return quadruple precision number */ function mul(bytes16 x, bytes16 y) internal pure returns (bytes16) { unchecked { uint256 xExponent = (uint128(x) >> 112) & 0x7FFF; uint256 yExponent = (uint128(y) >> 112) & 0x7FFF; if (xExponent == 0x7FFF) { if (yExponent == 0x7FFF) { if (x == y) return x ^ (y & 0x80000000000000000000000000000000); else if (x ^ y == 0x80000000000000000000000000000000) return x | y; else return NaN; } else { if (y & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) return NaN; else return x ^ (y & 0x80000000000000000000000000000000); } } else if (yExponent == 0x7FFF) { if (x & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) return NaN; else return y ^ (x & 0x80000000000000000000000000000000); } else { uint256 xSignifier = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; if (xExponent == 0) xExponent = 1; else xSignifier |= 0x10000000000000000000000000000; uint256 ySignifier = uint128(y) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; if (yExponent == 0) yExponent = 1; else ySignifier |= 0x10000000000000000000000000000; xSignifier *= ySignifier; if (xSignifier == 0) return (x ^ y) & 0x80000000000000000000000000000000 > 0 ? _NEGATIVE_ZERO : _POSITIVE_ZERO; xExponent += yExponent; uint256 msb = xSignifier >= 0x200000000000000000000000000000000000000000000000000000000 ? 225 : xSignifier >= 0x100000000000000000000000000000000000000000000000000000000 ? 224 : mostSignificantBit(xSignifier); if (xExponent + msb < 16496) { // Underflow xExponent = 0; xSignifier = 0; } else if (xExponent + msb < 16608) { // Subnormal if (xExponent < 16496) xSignifier >>= 16496 - xExponent; else if (xExponent > 16496) xSignifier <<= xExponent - 16496; xExponent = 0; } else if (xExponent + msb > 49373) { xExponent = 0x7FFF; xSignifier = 0; } else { if (msb > 112) xSignifier >>= msb - 112; else if (msb < 112) xSignifier <<= 112 - msb; xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; xExponent = xExponent + msb - 16607; } return bytes16( uint128( uint128( (x ^ y) & 0x80000000000000000000000000000000 ) | (xExponent << 112) | xSignifier ) ); } } } /** * Calculate x / y. Special values behave in the following way: * * NaN / x = NaN for any x. * x / NaN = NaN for any x. * Infinity / x = Infinity for any finite non-negative x. * Infinity / x = -Infinity for any finite negative x including -0. * -Infinity / x = -Infinity for any finite non-negative x. * -Infinity / x = Infinity for any finite negative x including -0. * x / Infinity = 0 for any finite non-negative x. * x / -Infinity = -0 for any finite non-negative x. * x / Infinity = -0 for any finite non-negative x including -0. * x / -Infinity = 0 for any finite non-negative x including -0. * * Infinity / Infinity = NaN. * Infinity / -Infinity = -NaN. * -Infinity / Infinity = -NaN. * -Infinity / -Infinity = NaN. * * Division by zero behaves in the following way: * * x / 0 = Infinity for any finite positive x. * x / -0 = -Infinity for any finite positive x. * x / 0 = -Infinity for any finite negative x. * x / -0 = Infinity for any finite negative x. * 0 / 0 = NaN. * 0 / -0 = NaN. * -0 / 0 = NaN. * -0 / -0 = NaN. * * @param x quadruple precision number * @param y quadruple precision number * @return quadruple precision number */ function div(bytes16 x, bytes16 y) internal pure returns (bytes16) { unchecked { uint256 xExponent = (uint128(x) >> 112) & 0x7FFF; uint256 yExponent = (uint128(y) >> 112) & 0x7FFF; if (xExponent == 0x7FFF) { if (yExponent == 0x7FFF) return NaN; else return x ^ (y & 0x80000000000000000000000000000000); } else if (yExponent == 0x7FFF) { if (y & 0x0000FFFFFFFFFFFFFFFFFFFFFFFFFFFF != 0) return NaN; else return _POSITIVE_ZERO | ((x ^ y) & 0x80000000000000000000000000000000); } else if (y & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) { if (x & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) return NaN; else return _POSITIVE_INFINITY | ((x ^ y) & 0x80000000000000000000000000000000); } else { uint256 ySignifier = uint128(y) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; if (yExponent == 0) yExponent = 1; else ySignifier |= 0x10000000000000000000000000000; uint256 xSignifier = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; if (xExponent == 0) { if (xSignifier != 0) { uint256 shift = 226 - mostSignificantBit(xSignifier); xSignifier <<= shift; xExponent = 1; yExponent += shift - 114; } } else { xSignifier = (xSignifier | 0x10000000000000000000000000000) << 114; } xSignifier = xSignifier / ySignifier; if (xSignifier == 0) return (x ^ y) & 0x80000000000000000000000000000000 > 0 ? _NEGATIVE_ZERO : _POSITIVE_ZERO; assert(xSignifier >= 0x1000000000000000000000000000); uint256 msb = xSignifier >= 0x80000000000000000000000000000 ? mostSignificantBit(xSignifier) : xSignifier >= 0x40000000000000000000000000000 ? 114 : xSignifier >= 0x20000000000000000000000000000 ? 113 : 112; if (xExponent + msb > yExponent + 16497) { // Overflow xExponent = 0x7FFF; xSignifier = 0; } else if (xExponent + msb + 16380 < yExponent) { // Underflow xExponent = 0; xSignifier = 0; } else if (xExponent + msb + 16268 < yExponent) { // Subnormal if (xExponent + 16380 > yExponent) xSignifier <<= xExponent + 16380 - yExponent; else if (xExponent + 16380 < yExponent) xSignifier >>= yExponent - xExponent - 16380; xExponent = 0; } else { // Normal if (msb > 112) xSignifier >>= msb - 112; xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; xExponent = xExponent + msb + 16269 - yExponent; } return bytes16( uint128( uint128( (x ^ y) & 0x80000000000000000000000000000000 ) | (xExponent << 112) | xSignifier ) ); } } } /** * Calculate -x. * * @param x quadruple precision number * @return quadruple precision number */ function neg(bytes16 x) internal pure returns (bytes16) { unchecked {return x ^ 0x80000000000000000000000000000000;} } /** * Calculate |x|. * * @param x quadruple precision number * @return quadruple precision number */ function abs(bytes16 x) internal pure returns (bytes16) { unchecked {return x & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;} } /** * Calculate square root of x. Return NaN on negative x excluding -0. * * @param x quadruple precision number * @return quadruple precision number */ function sqrt(bytes16 x) internal pure returns (bytes16) { unchecked { if (uint128(x) > 0x80000000000000000000000000000000) return NaN; else { uint256 xExponent = (uint128(x) >> 112) & 0x7FFF; if (xExponent == 0x7FFF) return x; else { uint256 xSignifier = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; if (xExponent == 0) xExponent = 1; else xSignifier |= 0x10000000000000000000000000000; if (xSignifier == 0) return _POSITIVE_ZERO; bool oddExponent = xExponent & 0x1 == 0; xExponent = (xExponent + 16383) >> 1; if (oddExponent) { if (xSignifier >= 0x10000000000000000000000000000) xSignifier <<= 113; else { uint256 msb = mostSignificantBit(xSignifier); uint256 shift = (226 - msb) & 0xFE; xSignifier <<= shift; xExponent -= (shift - 112) >> 1; } } else { if (xSignifier >= 0x10000000000000000000000000000) xSignifier <<= 112; else { uint256 msb = mostSignificantBit(xSignifier); uint256 shift = (225 - msb) & 0xFE; xSignifier <<= shift; xExponent -= (shift - 112) >> 1; } } uint256 r = 0x10000000000000000000000000000; r = (r + xSignifier / r) >> 1; r = (r + xSignifier / r) >> 1; r = (r + xSignifier / r) >> 1; r = (r + xSignifier / r) >> 1; r = (r + xSignifier / r) >> 1; r = (r + xSignifier / r) >> 1; r = (r + xSignifier / r) >> 1; // Seven iterations should be enough uint256 r1 = xSignifier / r; if (r1 < r) r = r1; return bytes16( uint128( (xExponent << 112) | (r & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) ) ); } } } } /** * Calculate binary logarithm of x. Return NaN on negative x excluding -0. * * @param x quadruple precision number * @return quadruple precision number */ function log_2(bytes16 x) internal pure returns (bytes16) { unchecked { if (uint128(x) > 0x80000000000000000000000000000000) return NaN; else if (x == 0x3FFF0000000000000000000000000000) return _POSITIVE_ZERO; else { uint256 xExponent = (uint128(x) >> 112) & 0x7FFF; if (xExponent == 0x7FFF) return x; else { uint256 xSignifier = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; if (xExponent == 0) xExponent = 1; else xSignifier |= 0x10000000000000000000000000000; if (xSignifier == 0) return _NEGATIVE_INFINITY; bool resultNegative; uint256 resultExponent = 16495; uint256 resultSignifier; if (xExponent >= 0x3FFF) { resultNegative = false; resultSignifier = xExponent - 0x3FFF; xSignifier <<= 15; } else { resultNegative = true; if (xSignifier >= 0x10000000000000000000000000000) { resultSignifier = 0x3FFE - xExponent; xSignifier <<= 15; } else { uint256 msb = mostSignificantBit(xSignifier); resultSignifier = 16493 - msb; xSignifier <<= 127 - msb; } } if (xSignifier == 0x80000000000000000000000000000000) { if (resultNegative) resultSignifier += 1; uint256 shift = 112 - mostSignificantBit(resultSignifier); resultSignifier <<= shift; resultExponent -= shift; } else { uint256 bb = resultNegative ? 1 : 0; while ( resultSignifier < 0x10000000000000000000000000000 ) { resultSignifier <<= 1; resultExponent -= 1; xSignifier *= xSignifier; uint256 b = xSignifier >> 255; resultSignifier += b ^ bb; xSignifier >>= 127 + b; } } return bytes16( uint128( ( resultNegative ? 0x80000000000000000000000000000000 : 0 ) | (resultExponent << 112) | (resultSignifier & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) ) ); } } } } /** * Calculate natural logarithm of x. Return NaN on negative x excluding -0. * * @param x quadruple precision number * @return quadruple precision number */ function ln(bytes16 x) internal pure returns (bytes16) { unchecked {return mul(log_2(x), 0x3FFE62E42FEFA39EF35793C7673007E5);} } /** * Calculate 2^x. * * @param x quadruple precision number * @return quadruple precision number */ function pow_2(bytes16 x) internal pure returns (bytes16) { unchecked { bool xNegative = uint128(x) > 0x80000000000000000000000000000000; uint256 xExponent = (uint128(x) >> 112) & 0x7FFF; uint256 xSignifier = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; if (xExponent == 0x7FFF && xSignifier != 0) return NaN; else if (xExponent > 16397) return xNegative ? _POSITIVE_ZERO : _POSITIVE_INFINITY; else if (xExponent < 16255) return 0x3FFF0000000000000000000000000000; else { if (xExponent == 0) xExponent = 1; else xSignifier |= 0x10000000000000000000000000000; if (xExponent > 16367) xSignifier <<= xExponent - 16367; else if (xExponent < 16367) xSignifier >>= 16367 - xExponent; if ( xNegative && xSignifier > 0x406E00000000000000000000000000000000 ) return _POSITIVE_ZERO; if ( !xNegative && xSignifier > 0x3FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF ) return _POSITIVE_INFINITY; uint256 resultExponent = xSignifier >> 128; xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; if (xNegative && xSignifier != 0) { xSignifier = ~xSignifier; resultExponent += 1; } uint256 resultSignifier = 0x80000000000000000000000000000000; if (xSignifier & 0x80000000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x16A09E667F3BCC908B2FB1366EA957D3E) >> 128; if (xSignifier & 0x40000000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x1306FE0A31B7152DE8D5A46305C85EDEC) >> 128; if (xSignifier & 0x20000000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x1172B83C7D517ADCDF7C8C50EB14A791F) >> 128; if (xSignifier & 0x10000000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x10B5586CF9890F6298B92B71842A98363) >> 128; if (xSignifier & 0x8000000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x1059B0D31585743AE7C548EB68CA417FD) >> 128; if (xSignifier & 0x4000000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x102C9A3E778060EE6F7CACA4F7A29BDE8) >> 128; if (xSignifier & 0x2000000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x10163DA9FB33356D84A66AE336DCDFA3F) >> 128; if (xSignifier & 0x1000000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x100B1AFA5ABCBED6129AB13EC11DC9543) >> 128; if (xSignifier & 0x800000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x10058C86DA1C09EA1FF19D294CF2F679B) >> 128; if (xSignifier & 0x400000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x1002C605E2E8CEC506D21BFC89A23A00F) >> 128; if (xSignifier & 0x200000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x100162F3904051FA128BCA9C55C31E5DF) >> 128; if (xSignifier & 0x100000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x1000B175EFFDC76BA38E31671CA939725) >> 128; if (xSignifier & 0x80000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x100058BA01FB9F96D6CACD4B180917C3D) >> 128; if (xSignifier & 0x40000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x10002C5CC37DA9491D0985C348C68E7B3) >> 128; if (xSignifier & 0x20000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x1000162E525EE054754457D5995292026) >> 128; if (xSignifier & 0x10000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x10000B17255775C040618BF4A4ADE83FC) >> 128; if (xSignifier & 0x8000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB) >> 128; if (xSignifier & 0x4000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9) >> 128; if (xSignifier & 0x2000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x10000162E43F4F831060E02D839A9D16D) >> 128; if (xSignifier & 0x1000000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x100000B1721BCFC99D9F890EA06911763) >> 128; if (xSignifier & 0x800000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x10000058B90CF1E6D97F9CA14DBCC1628) >> 128; if (xSignifier & 0x400000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x1000002C5C863B73F016468F6BAC5CA2B) >> 128; if (xSignifier & 0x200000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x100000162E430E5A18F6119E3C02282A5) >> 128; if (xSignifier & 0x100000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x1000000B1721835514B86E6D96EFD1BFE) >> 128; if (xSignifier & 0x80000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x100000058B90C0B48C6BE5DF846C5B2EF) >> 128; if (xSignifier & 0x40000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x10000002C5C8601CC6B9E94213C72737A) >> 128; if (xSignifier & 0x20000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x1000000162E42FFF037DF38AA2B219F06) >> 128; if (xSignifier & 0x10000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x10000000B17217FBA9C739AA5819F44F9) >> 128; if (xSignifier & 0x8000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x1000000058B90BFCDEE5ACD3C1CEDC823) >> 128; if (xSignifier & 0x4000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x100000002C5C85FE31F35A6A30DA1BE50) >> 128; if (xSignifier & 0x2000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x10000000162E42FF0999CE3541B9FFFCF) >> 128; if (xSignifier & 0x1000000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x100000000B17217F80F4EF5AADDA45554) >> 128; if (xSignifier & 0x800000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x10000000058B90BFBF8479BD5A81B51AD) >> 128; if (xSignifier & 0x400000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x1000000002C5C85FDF84BD62AE30A74CC) >> 128; if (xSignifier & 0x200000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x100000000162E42FEFB2FED257559BDAA) >> 128; if (xSignifier & 0x100000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x1000000000B17217F7D5A7716BBA4A9AE) >> 128; if (xSignifier & 0x80000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x100000000058B90BFBE9DDBAC5E109CCE) >> 128; if (xSignifier & 0x40000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x10000000002C5C85FDF4B15DE6F17EB0D) >> 128; if (xSignifier & 0x20000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x1000000000162E42FEFA494F1478FDE05) >> 128; if (xSignifier & 0x10000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x10000000000B17217F7D20CF927C8E94C) >> 128; if (xSignifier & 0x8000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x1000000000058B90BFBE8F71CB4E4B33D) >> 128; if (xSignifier & 0x4000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x100000000002C5C85FDF477B662B26945) >> 128; if (xSignifier & 0x2000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x10000000000162E42FEFA3AE53369388C) >> 128; if (xSignifier & 0x1000000000000000000000 > 0) resultSignifier = (resultSignifier * 0x100000000000B17217F7D1D351A389D40) >> 128; if (xSignifier & 0x800000000000000000000 > 0) resultSignifier = (resultSignifier * 0x10000000000058B90BFBE8E8B2D3D4EDE) >> 128; if (xSignifier & 0x400000000000000000000 > 0) resultSignifier = (resultSignifier * 0x1000000000002C5C85FDF4741BEA6E77E) >> 128; if (xSignifier & 0x200000000000000000000 > 0) resultSignifier = (resultSignifier * 0x100000000000162E42FEFA39FE95583C2) >> 128; if (xSignifier & 0x100000000000000000000 > 0) resultSignifier = (resultSignifier * 0x1000000000000B17217F7D1CFB72B45E1) >> 128; if (xSignifier & 0x80000000000000000000 > 0) resultSignifier = (resultSignifier * 0x100000000000058B90BFBE8E7CC35C3F0) >> 128; if (xSignifier & 0x40000000000000000000 > 0) resultSignifier = (resultSignifier * 0x10000000000002C5C85FDF473E242EA38) >> 128; if (xSignifier & 0x20000000000000000000 > 0) resultSignifier = (resultSignifier * 0x1000000000000162E42FEFA39F02B772C) >> 128; if (xSignifier & 0x10000000000000000000 > 0) resultSignifier = (resultSignifier * 0x10000000000000B17217F7D1CF7D83C1A) >> 128; if (xSignifier & 0x8000000000000000000 > 0) resultSignifier = (resultSignifier * 0x1000000000000058B90BFBE8E7BDCBE2E) >> 128; if (xSignifier & 0x4000000000000000000 > 0) resultSignifier = (resultSignifier * 0x100000000000002C5C85FDF473DEA871F) >> 128; if (xSignifier & 0x2000000000000000000 > 0) resultSignifier = (resultSignifier * 0x10000000000000162E42FEFA39EF44D91) >> 128; if (xSignifier & 0x1000000000000000000 > 0) resultSignifier = (resultSignifier * 0x100000000000000B17217F7D1CF79E949) >> 128; if (xSignifier & 0x800000000000000000 > 0) resultSignifier = (resultSignifier * 0x10000000000000058B90BFBE8E7BCE544) >> 128; if (xSignifier & 0x400000000000000000 > 0) resultSignifier = (resultSignifier * 0x1000000000000002C5C85FDF473DE6ECA) >> 128; if (xSignifier & 0x200000000000000000 > 0) resultSignifier = (resultSignifier * 0x100000000000000162E42FEFA39EF366F) >> 128; if (xSignifier & 0x100000000000000000 > 0) resultSignifier = (resultSignifier * 0x1000000000000000B17217F7D1CF79AFA) >> 128; if (xSignifier & 0x80000000000000000 > 0) resultSignifier = (resultSignifier * 0x100000000000000058B90BFBE8E7BCD6D) >> 128; if (xSignifier & 0x40000000000000000 > 0) resultSignifier = (resultSignifier * 0x10000000000000002C5C85FDF473DE6B2) >> 128; if (xSignifier & 0x20000000000000000 > 0) resultSignifier = (resultSignifier * 0x1000000000000000162E42FEFA39EF358) >> 128; if (xSignifier & 0x10000000000000000 > 0) resultSignifier = (resultSignifier * 0x10000000000000000B17217F7D1CF79AB) >> 128; if (xSignifier & 0x8000000000000000 > 0) resultSignifier = (resultSignifier * 0x1000000000000000058B90BFBE8E7BCD5) >> 128; if (xSignifier & 0x4000000000000000 > 0) resultSignifier = (resultSignifier * 0x100000000000000002C5C85FDF473DE6A) >> 128; if (xSignifier & 0x2000000000000000 > 0) resultSignifier = (resultSignifier * 0x10000000000000000162E42FEFA39EF34) >> 128; if (xSignifier & 0x1000000000000000 > 0) resultSignifier = (resultSignifier * 0x100000000000000000B17217F7D1CF799) >> 128; if (xSignifier & 0x800000000000000 > 0) resultSignifier = (resultSignifier * 0x10000000000000000058B90BFBE8E7BCC) >> 128; if (xSignifier & 0x400000000000000 > 0) resultSignifier = (resultSignifier * 0x1000000000000000002C5C85FDF473DE5) >> 128; if (xSignifier & 0x200000000000000 > 0) resultSignifier = (resultSignifier * 0x100000000000000000162E42FEFA39EF2) >> 128; if (xSignifier & 0x100000000000000 > 0) resultSignifier = (resultSignifier * 0x1000000000000000000B17217F7D1CF78) >> 128; if (xSignifier & 0x80000000000000 > 0) resultSignifier = (resultSignifier * 0x100000000000000000058B90BFBE8E7BB) >> 128; if (xSignifier & 0x40000000000000 > 0) resultSignifier = (resultSignifier * 0x10000000000000000002C5C85FDF473DD) >> 128; if (xSignifier & 0x20000000000000 > 0) resultSignifier = (resultSignifier * 0x1000000000000000000162E42FEFA39EE) >> 128; if (xSignifier & 0x10000000000000 > 0) resultSignifier = (resultSignifier * 0x10000000000000000000B17217F7D1CF6) >> 128; if (xSignifier & 0x8000000000000 > 0) resultSignifier = (resultSignifier * 0x1000000000000000000058B90BFBE8E7A) >> 128; if (xSignifier & 0x4000000000000 > 0) resultSignifier = (resultSignifier * 0x100000000000000000002C5C85FDF473C) >> 128; if (xSignifier & 0x2000000000000 > 0) resultSignifier = (resultSignifier * 0x10000000000000000000162E42FEFA39D) >> 128; if (xSignifier & 0x1000000000000 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000B17217F7D1CE) >> 128; if (xSignifier & 0x800000000000 > 0) resultSignifier = (resultSignifier * 0x10000000000000000000058B90BFBE8E6) >> 128; if (xSignifier & 0x400000000000 > 0) resultSignifier = (resultSignifier * 0x1000000000000000000002C5C85FDF472) >> 128; if (xSignifier & 0x200000000000 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000162E42FEFA38) >> 128; if (xSignifier & 0x100000000000 > 0) resultSignifier = (resultSignifier * 0x1000000000000000000000B17217F7D1B) >> 128; if (xSignifier & 0x80000000000 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000058B90BFBE8D) >> 128; if (xSignifier & 0x40000000000 > 0) resultSignifier = (resultSignifier * 0x10000000000000000000002C5C85FDF46) >> 128; if (xSignifier & 0x20000000000 > 0) resultSignifier = (resultSignifier * 0x1000000000000000000000162E42FEFA2) >> 128; if (xSignifier & 0x10000000000 > 0) resultSignifier = (resultSignifier * 0x10000000000000000000000B17217F7D0) >> 128; if (xSignifier & 0x8000000000 > 0) resultSignifier = (resultSignifier * 0x1000000000000000000000058B90BFBE7) >> 128; if (xSignifier & 0x4000000000 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000002C5C85FDF3) >> 128; if (xSignifier & 0x2000000000 > 0) resultSignifier = (resultSignifier * 0x10000000000000000000000162E42FEF9) >> 128; if (xSignifier & 0x1000000000 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000000B17217F7C) >> 128; if (xSignifier & 0x800000000 > 0) resultSignifier = (resultSignifier * 0x10000000000000000000000058B90BFBD) >> 128; if (xSignifier & 0x400000000 > 0) resultSignifier = (resultSignifier * 0x1000000000000000000000002C5C85FDE) >> 128; if (xSignifier & 0x200000000 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000000162E42FEE) >> 128; if (xSignifier & 0x100000000 > 0) resultSignifier = (resultSignifier * 0x1000000000000000000000000B17217F6) >> 128; if (xSignifier & 0x80000000 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000000058B90BFA) >> 128; if (xSignifier & 0x40000000 > 0) resultSignifier = (resultSignifier * 0x10000000000000000000000002C5C85FC) >> 128; if (xSignifier & 0x20000000 > 0) resultSignifier = (resultSignifier * 0x1000000000000000000000000162E42FD) >> 128; if (xSignifier & 0x10000000 > 0) resultSignifier = (resultSignifier * 0x10000000000000000000000000B17217E) >> 128; if (xSignifier & 0x8000000 > 0) resultSignifier = (resultSignifier * 0x1000000000000000000000000058B90BE) >> 128; if (xSignifier & 0x4000000 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000000002C5C85E) >> 128; if (xSignifier & 0x2000000 > 0) resultSignifier = (resultSignifier * 0x10000000000000000000000000162E42E) >> 128; if (xSignifier & 0x1000000 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000000000B17216) >> 128; if (xSignifier & 0x800000 > 0) resultSignifier = (resultSignifier * 0x10000000000000000000000000058B90A) >> 128; if (xSignifier & 0x400000 > 0) resultSignifier = (resultSignifier * 0x1000000000000000000000000002C5C84) >> 128; if (xSignifier & 0x200000 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000000000162E41) >> 128; if (xSignifier & 0x100000 > 0) resultSignifier = (resultSignifier * 0x1000000000000000000000000000B1720) >> 128; if (xSignifier & 0x80000 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000000000058B8F) >> 128; if (xSignifier & 0x40000 > 0) resultSignifier = (resultSignifier * 0x10000000000000000000000000002C5C7) >> 128; if (xSignifier & 0x20000 > 0) resultSignifier = (resultSignifier * 0x1000000000000000000000000000162E3) >> 128; if (xSignifier & 0x10000 > 0) resultSignifier = (resultSignifier * 0x10000000000000000000000000000B171) >> 128; if (xSignifier & 0x8000 > 0) resultSignifier = (resultSignifier * 0x1000000000000000000000000000058B8) >> 128; if (xSignifier & 0x4000 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000000000002C5B) >> 128; if (xSignifier & 0x2000 > 0) resultSignifier = (resultSignifier * 0x10000000000000000000000000000162D) >> 128; if (xSignifier & 0x1000 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000000000000B16) >> 128; if (xSignifier & 0x800 > 0) resultSignifier = (resultSignifier * 0x10000000000000000000000000000058A) >> 128; if (xSignifier & 0x400 > 0) resultSignifier = (resultSignifier * 0x1000000000000000000000000000002C4) >> 128; if (xSignifier & 0x200 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000000000000161) >> 128; if (xSignifier & 0x100 > 0) resultSignifier = (resultSignifier * 0x1000000000000000000000000000000B0) >> 128; if (xSignifier & 0x80 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000000000000057) >> 128; if (xSignifier & 0x40 > 0) resultSignifier = (resultSignifier * 0x10000000000000000000000000000002B) >> 128; if (xSignifier & 0x20 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000000000000015) >> 128; if (xSignifier & 0x10 > 0) resultSignifier = (resultSignifier * 0x10000000000000000000000000000000A) >> 128; if (xSignifier & 0x8 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000000000000004) >> 128; if (xSignifier & 0x4 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000000000000001) >> 128; if (!xNegative) { resultSignifier = (resultSignifier >> 15) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; resultExponent += 0x3FFF; } else if (resultExponent <= 0x3FFE) { resultSignifier = (resultSignifier >> 15) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; resultExponent = 0x3FFF - resultExponent; } else { resultSignifier = resultSignifier >> (resultExponent - 16367); resultExponent = 0; } return bytes16(uint128((resultExponent << 112) | resultSignifier)); } } } /** * Calculate e^x. * * @param x quadruple precision number * @return quadruple precision number */ function exp(bytes16 x) internal pure returns (bytes16) { unchecked {return pow_2(mul(x, 0x3FFF71547652B82FE1777D0FFDA0D23A));} } /** * Get index of the most significant non-zero bit in binary representation of * x. Reverts if x is zero. * * @return index of the most significant non-zero bit in binary representation * of x */ function mostSignificantBit(uint256 x) private pure returns (uint256) { unchecked { require(x > 0); uint256 result = 0; if (x >= 0x100000000000000000000000000000000) { x >>= 128; result += 128; } if (x >= 0x10000000000000000) { x >>= 64; result += 64; } if (x >= 0x100000000) { x >>= 32; result += 32; } if (x >= 0x10000) { x >>= 16; result += 16; } if (x >= 0x100) { x >>= 8; result += 8; } if (x >= 0x10) { x >>= 4; result += 4; } if (x >= 0x4) { x >>= 2; result += 2; } if (x >= 0x2) result += 1; // No need to shift x anymore return result; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @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 AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping (address => bool) 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 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]{20}) is missing role (0x[0-9a-f]{32})$/ * * _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(IAccessControl).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]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if(!hasRole(role, account)) { revert(string(abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.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 { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = 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()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _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"); _approve(_msgSender(), spender, currentAllowance - 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 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"); _balances[sender] = senderBalance - amount; _balances[recipient] += 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 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); } /** * @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"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(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 to 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 { } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; 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) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _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"); } } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.3; import "./IERC20Ubiquity.sol"; /// @title UAD stablecoin interface /// @author Ubiquity Algorithmic Dollar interface IUbiquityAlgorithmicDollar is IERC20Ubiquity { event IncentiveContractUpdate( address indexed _incentivized, address indexed _incentiveContract ); function setIncentiveContract(address account, address incentive) external; function incentiveContract(address account) external view returns (address); } // SPDX-License-Identifier: MIT // !! THIS FILE WAS AUTOGENERATED BY abi-to-sol. SEE BELOW FOR SOURCE. !! pragma solidity ^0.8.3; interface ICurveFactory { event BasePoolAdded(address base_pool, address implementat); event MetaPoolDeployed( address coin, address base_pool, uint256 A, uint256 fee, address deployer ); function find_pool_for_coins(address _from, address _to) external view returns (address); function find_pool_for_coins( address _from, address _to, uint256 i ) external view returns (address); function get_n_coins(address _pool) external view returns (uint256, uint256); function get_coins(address _pool) external view returns (address[2] memory); function get_underlying_coins(address _pool) external view returns (address[8] memory); function get_decimals(address _pool) external view returns (uint256[2] memory); function get_underlying_decimals(address _pool) external view returns (uint256[8] memory); function get_rates(address _pool) external view returns (uint256[2] memory); function get_balances(address _pool) external view returns (uint256[2] memory); function get_underlying_balances(address _pool) external view returns (uint256[8] memory); function get_A(address _pool) external view returns (uint256); function get_fees(address _pool) external view returns (uint256, uint256); function get_admin_balances(address _pool) external view returns (uint256[2] memory); function get_coin_indices( address _pool, address _from, address _to ) external view returns ( int128, int128, bool ); function add_base_pool( address _base_pool, address _metapool_implementation, address _fee_receiver ) external; function deploy_metapool( address _base_pool, string memory _name, string memory _symbol, address _coin, uint256 _A, uint256 _fee ) external returns (address); function commit_transfer_ownership(address addr) external; function accept_transfer_ownership() external; function set_fee_receiver(address _base_pool, address _fee_receiver) external; function convert_fees() external returns (bool); function admin() external view returns (address); function future_admin() external view returns (address); function pool_list(uint256 arg0) external view returns (address); function pool_count() external view returns (uint256); function base_pool_list(uint256 arg0) external view returns (address); function base_pool_count() external view returns (uint256); function fee_receiver(address arg0) external view returns (address); } // SPDX-License-Identifier: UNLICENSED // !! THIS FILE WAS AUTOGENERATED BY abi-to-sol. SEE BELOW FOR SOURCE. !! pragma solidity ^0.8.3; interface IMetaPool { event Transfer( address indexed sender, address indexed receiver, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); event TokenExchange( address indexed buyer, int128 sold_id, uint256 tokens_sold, int128 bought_id, uint256 tokens_bought ); event TokenExchangeUnderlying( address indexed buyer, int128 sold_id, uint256 tokens_sold, int128 bought_id, uint256 tokens_bought ); event AddLiquidity( address indexed provider, uint256[2] token_amounts, uint256[2] fees, uint256 invariant, uint256 token_supply ); event RemoveLiquidity( address indexed provider, uint256[2] token_amounts, uint256[2] fees, uint256 token_supply ); event RemoveLiquidityOne( address indexed provider, uint256 token_amount, uint256 coin_amount, uint256 token_supply ); event RemoveLiquidityImbalance( address indexed provider, uint256[2] token_amounts, uint256[2] fees, uint256 invariant, uint256 token_supply ); event CommitNewAdmin(uint256 indexed deadline, address indexed admin); event NewAdmin(address indexed admin); event CommitNewFee( uint256 indexed deadline, uint256 fee, uint256 admin_fee ); event NewFee(uint256 fee, uint256 admin_fee); event RampA( uint256 old_A, uint256 new_A, uint256 initial_time, uint256 future_time ); event StopRampA(uint256 A, uint256 t); function initialize( string memory _name, string memory _symbol, address _coin, uint256 _decimals, uint256 _A, uint256 _fee, address _admin ) external; function decimals() external view returns (uint256); function transfer(address _to, uint256 _value) external returns (bool); function transferFrom( address _from, address _to, uint256 _value ) external returns (bool); function approve(address _spender, uint256 _value) external returns (bool); function get_previous_balances() external view returns (uint256[2] memory); function get_balances() external view returns (uint256[2] memory); function get_twap_balances( uint256[2] memory _first_balances, uint256[2] memory _last_balances, uint256 _time_elapsed ) external view returns (uint256[2] memory); function get_price_cumulative_last() external view returns (uint256[2] memory); function admin_fee() external view returns (uint256); function A() external view returns (uint256); function A_precise() external view returns (uint256); function get_virtual_price() external view returns (uint256); function calc_token_amount(uint256[2] memory _amounts, bool _is_deposit) external view returns (uint256); function calc_token_amount( uint256[2] memory _amounts, bool _is_deposit, bool _previous ) external view returns (uint256); function add_liquidity(uint256[2] memory _amounts, uint256 _min_mint_amount) external returns (uint256); function add_liquidity( uint256[2] memory _amounts, uint256 _min_mint_amount, address _receiver ) external returns (uint256); function get_dy( int128 i, int128 j, uint256 dx ) external view returns (uint256); function get_dy( int128 i, int128 j, uint256 dx, uint256[2] memory _balances ) external view returns (uint256); function get_dy_underlying( int128 i, int128 j, uint256 dx ) external view returns (uint256); function get_dy_underlying( int128 i, int128 j, uint256 dx, uint256[2] memory _balances ) external view returns (uint256); function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy ) external returns (uint256); function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy, address _receiver ) external returns (uint256); function exchange_underlying( int128 i, int128 j, uint256 dx, uint256 min_dy ) external returns (uint256); function exchange_underlying( int128 i, int128 j, uint256 dx, uint256 min_dy, address _receiver ) external returns (uint256); function remove_liquidity( uint256 _burn_amount, uint256[2] memory _min_amounts ) external returns (uint256[2] memory); function remove_liquidity( uint256 _burn_amount, uint256[2] memory _min_amounts, address _receiver ) external returns (uint256[2] memory); function remove_liquidity_imbalance( uint256[2] memory _amounts, uint256 _max_burn_amount ) external returns (uint256); function remove_liquidity_imbalance( uint256[2] memory _amounts, uint256 _max_burn_amount, address _receiver ) external returns (uint256); function calc_withdraw_one_coin(uint256 _burn_amount, int128 i) external view returns (uint256); function calc_withdraw_one_coin( uint256 _burn_amount, int128 i, bool _previous ) external view returns (uint256); function remove_liquidity_one_coin( uint256 _burn_amount, int128 i, uint256 _min_received ) external returns (uint256); function remove_liquidity_one_coin( uint256 _burn_amount, int128 i, uint256 _min_received, address _receiver ) external returns (uint256); function ramp_A(uint256 _future_A, uint256 _future_time) external; function stop_ramp_A() external; function admin_balances(uint256 i) external view returns (uint256); function withdraw_admin_fees() external; function admin() external view returns (address); function coins(uint256 arg0) external view returns (address); function balances(uint256 arg0) external view returns (uint256); function fee() external view returns (uint256); function block_timestamp_last() external view returns (uint256); function initial_A() external view returns (uint256); function future_A() external view returns (uint256); function initial_A_time() external view returns (uint256); function future_A_time() external view returns (uint256); function name() external view returns (string memory); function symbol() external view returns (string memory); function balanceOf(address arg0) external view returns (uint256); function allowance(address arg0, address arg1) external view returns (uint256); function totalSupply() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "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] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @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 ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT 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; // 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); } } } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title ERC20 Ubiquiti preset interface /// @author Ubiquity Algorithmic Dollar interface IERC20Ubiquity is IERC20 { // ----------- Events ----------- event Minting( address indexed _to, address indexed _minter, uint256 _amount ); event Burning(address indexed _burned, uint256 _amount); // ----------- State changing api ----------- function burn(uint256 amount) external; function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; // ----------- Burner only state changing api ----------- function burnFrom(address account, uint256 amount) external; // ----------- Minter only state changing api ----------- function mint(address account, uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @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)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @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)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); }
Calculate x y. Special values behave in the following way: NaN x = NaN for any x. Infinity x = Infinity for any finite positive x. Infinity x = -Infinity for any finite negative x. -Infinity x = -Infinity for any finite positive x. -Infinity x = Infinity for any finite negative x. Infinity 0 = NaN. -Infinity 0 = NaN. Infinity Infinity = Infinity. Infinity -Infinity = -Infinity. -Infinity Infinity = -Infinity. -Infinity -Infinity = Infinity. x quadruple precision number y quadruple precision number return quadruple precision number/ Underflow Subnormal
function mul(bytes16 x, bytes16 y) internal pure returns (bytes16) { unchecked { uint256 xExponent = (uint128(x) >> 112) & 0x7FFF; uint256 yExponent = (uint128(y) >> 112) & 0x7FFF; if (xExponent == 0x7FFF) { if (yExponent == 0x7FFF) { if (x == y) return x ^ (y & 0x80000000000000000000000000000000); else if (x ^ y == 0x80000000000000000000000000000000) return x | y; else return NaN; if (y & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) return NaN; else return x ^ (y & 0x80000000000000000000000000000000); } if (x & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) return NaN; else return y ^ (x & 0x80000000000000000000000000000000); uint256 xSignifier = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; if (xExponent == 0) xExponent = 1; else xSignifier |= 0x10000000000000000000000000000; uint256 ySignifier = uint128(y) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; if (yExponent == 0) yExponent = 1; else ySignifier |= 0x10000000000000000000000000000; xSignifier *= ySignifier; if (xSignifier == 0) return (x ^ y) & 0x80000000000000000000000000000000 > 0 ? _NEGATIVE_ZERO : _POSITIVE_ZERO; xExponent += yExponent; uint256 msb = xSignifier >= 0x200000000000000000000000000000000000000000000000000000000 ? 225 : xSignifier >= 0x100000000000000000000000000000000000000000000000000000000 ? 224 : mostSignificantBit(xSignifier); if (xExponent + msb < 16496) { xExponent = 0; xSignifier = 0; if (xExponent < 16496) xSignifier >>= 16496 - xExponent; else if (xExponent > 16496) xSignifier <<= xExponent - 16496; xExponent = 0; xExponent = 0x7FFF; xSignifier = 0; if (msb > 112) xSignifier >>= msb - 112; else if (msb < 112) xSignifier <<= 112 - msb; xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF; xExponent = xExponent + msb - 16607; } return bytes16( uint128( uint128( (x ^ y) & 0x80000000000000000000000000000000 ) | (xExponent << 112) | xSignifier ) ); } } }
96,132
./full_match/4/0x9981663cFABc42FfE36DE046913540b753836C89/sources/contracts/NToken.sol
Mint amount The amount of NToken to add account The account of NToken to add
function mint(uint256 amount, address account) override public { require(address(msg.sender) == INestPool(C_NestPool).addrOfNestMining(), "Nest:NTK:!Auth"); _balances[account] = _balances[account].add(amount); _totalSupply = _totalSupply.add(amount); _recentlyUsedBlock = block.number; }
13,298,932
// SPDX-License-Identifier: MIT // // ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ // ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ // ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // // pragma solidity ^0.8.9; import "./RandomBeacon.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /// @title Keep Random Beacon Governance /// @notice Owns the `RandomBeacon` contract and is responsible for updating its /// governable parameters in respect to governance delay individual /// for each parameter. contract RandomBeaconGovernance is Ownable { uint256 public newRelayRequestFee; uint256 public relayRequestFeeChangeInitiated; uint256 public newRelayEntrySubmissionEligibilityDelay; uint256 public relayEntrySubmissionEligibilityDelayChangeInitiated; uint256 public newRelayEntryHardTimeout; uint256 public relayEntryHardTimeoutChangeInitiated; uint256 public newCallbackGasLimit; uint256 public callbackGasLimitChangeInitiated; uint256 public newGroupCreationFrequency; uint256 public groupCreationFrequencyChangeInitiated; uint256 public newGroupLifetime; uint256 public groupLifetimeChangeInitiated; uint256 public newDkgResultChallengePeriodLength; uint256 public dkgResultChallengePeriodLengthChangeInitiated; uint256 public newDkgResultSubmissionEligibilityDelay; uint256 public dkgResultSubmissionEligibilityDelayChangeInitiated; uint256 public newDkgResultSubmissionReward; uint256 public dkgResultSubmissionRewardChangeInitiated; uint256 public newSortitionPoolUnlockingReward; uint256 public sortitionPoolUnlockingRewardChangeInitiated; uint256 public newIneligibleOperatorNotifierReward; uint256 public ineligibleOperatorNotifierRewardChangeInitiated; uint256 public newRelayEntrySubmissionFailureSlashingAmount; uint256 public relayEntrySubmissionFailureSlashingAmountChangeInitiated; uint256 public newMaliciousDkgResultSlashingAmount; uint256 public maliciousDkgResultSlashingAmountChangeInitiated; uint256 public newUnauthorizedSigningSlashingAmount; uint256 public unauthorizedSigningSlashingAmountChangeInitiated; uint256 public newSortitionPoolRewardsBanDuration; uint256 public sortitionPoolRewardsBanDurationChangeInitiated; uint256 public newRelayEntryTimeoutNotificationRewardMultiplier; uint256 public relayEntryTimeoutNotificationRewardMultiplierChangeInitiated; uint256 public newUnauthorizedSigningNotificationRewardMultiplier; uint256 public unauthorizedSigningNotificationRewardMultiplierChangeInitiated; uint96 public newMinimumAuthorization; uint256 public minimumAuthorizationChangeInitiated; uint64 public newAuthorizationDecreaseDelay; uint256 public authorizationDecreaseDelayChangeInitiated; uint256 public newDkgMaliciousResultNotificationRewardMultiplier; uint256 public dkgMaliciousResultNotificationRewardMultiplierChangeInitiated; RandomBeacon public randomBeacon; // Long governance delay used for critical parameters giving a chance for // stakers to opt out before the change is finalized in case they do not // agree with that change. The maximum group lifetime must not be longer // than this delay. // // The full list of parameters protected by this delay: // - relay entry hard timeout // - callback gas limit // - group lifetime // - relay entry submission failure slashing amount // - minimum authorization // - authorization decrease delay uint256 internal constant CRITICAL_PARAMETER_GOVERNANCE_DELAY = 2 weeks; // Short governance delay for non-critical parameters. Honest stakers should // not be severely affected by any change of these parameters. // // The full list of parameters protected by this delay: // - relay request fee // - group creation frequency // - relay entry submission eligibility delay // - DKG result challenge period length // - DKG result submission eligibility delay // - DKG result submission reward // - sortition pool rewards ban duration // - malicious DKG result slashing amount // - sortition pool unlocking reward // - ineligible operator notifier reward // - relay entry timeout notification reward multiplier // - DKG malicious result notification reward multiplier uint256 internal constant STANDARD_PARAMETER_GOVERNANCE_DELAY = 12 hours; event RelayRequestFeeUpdateStarted( uint256 relayRequestFee, uint256 timestamp ); event RelayRequestFeeUpdated(uint256 relayRequestFee); event RelayEntrySubmissionEligibilityDelayUpdateStarted( uint256 relayEntrySubmissionEligibilityDelay, uint256 timestamp ); event RelayEntrySubmissionEligibilityDelayUpdated( uint256 relayEntrySubmissionEligibilityDelay ); event RelayEntryHardTimeoutUpdateStarted( uint256 relayEntryHardTimeout, uint256 timestamp ); event RelayEntryHardTimeoutUpdated(uint256 relayEntryHardTimeout); event CallbackGasLimitUpdateStarted( uint256 callbackGasLimit, uint256 timestamp ); event CallbackGasLimitUpdated(uint256 callbackGasLimit); event GroupCreationFrequencyUpdateStarted( uint256 groupCreationFrequency, uint256 timestamp ); event GroupCreationFrequencyUpdated(uint256 groupCreationFrequency); event GroupLifetimeUpdateStarted(uint256 groupLifetime, uint256 timestamp); event GroupLifetimeUpdated(uint256 groupLifetime); event DkgResultChallengePeriodLengthUpdateStarted( uint256 dkgResultChallengePeriodLength, uint256 timestamp ); event DkgResultChallengePeriodLengthUpdated( uint256 dkgResultChallengePeriodLength ); event DkgResultSubmissionEligibilityDelayUpdateStarted( uint256 dkgResultSubmissionEligibilityDelay, uint256 timestamp ); event DkgResultSubmissionEligibilityDelayUpdated( uint256 dkgResultSubmissionEligibilityDelay ); event DkgResultSubmissionRewardUpdateStarted( uint256 dkgResultSubmissionReward, uint256 timestamp ); event DkgResultSubmissionRewardUpdated(uint256 dkgResultSubmissionReward); event SortitionPoolUnlockingRewardUpdateStarted( uint256 sortitionPoolUnlockingReward, uint256 timestamp ); event SortitionPoolUnlockingRewardUpdated( uint256 sortitionPoolUnlockingReward ); event IneligibleOperatorNotifierRewardUpdateStarted( uint256 ineligibleOperatorNotifierReward, uint256 timestamp ); event IneligibleOperatorNotifierRewardUpdated( uint256 ineligibleOperatorNotifierReward ); event RelayEntrySubmissionFailureSlashingAmountUpdateStarted( uint256 relayEntrySubmissionFailureSlashingAmount, uint256 timestamp ); event RelayEntrySubmissionFailureSlashingAmountUpdated( uint256 relayEntrySubmissionFailureSlashingAmount ); event MaliciousDkgResultSlashingAmountUpdateStarted( uint256 maliciousDkgResultSlashingAmount, uint256 timestamp ); event MaliciousDkgResultSlashingAmountUpdated( uint256 maliciousDkgResultSlashingAmount ); event UnauthorizedSigningSlashingAmountUpdateStarted( uint256 unauthorizedSigningSlashingAmount, uint256 timestamp ); event UnauthorizedSigningSlashingAmountUpdated( uint256 unauthorizedSigningSlashingAmount ); event SortitionPoolRewardsBanDurationUpdateStarted( uint256 sortitionPoolRewardsBanDuration, uint256 timestamp ); event SortitionPoolRewardsBanDurationUpdated( uint256 sortitionPoolRewardsBanDuration ); event RelayEntryTimeoutNotificationRewardMultiplierUpdateStarted( uint256 relayEntryTimeoutNotificationRewardMultiplier, uint256 timestamp ); event RelayEntryTimeoutNotificationRewardMultiplierUpdated( uint256 relayEntryTimeoutNotificationRewardMultiplier ); event UnauthorizedSigningNotificationRewardMultiplierUpdateStarted( uint256 unauthorizedSigningTimeoutNotificationRewardMultiplier, uint256 timestamp ); event UnauthorizedSigningNotificationRewardMultiplierUpdated( uint256 unauthorizedSigningTimeoutNotificationRewardMultiplier ); event MinimumAuthorizationUpdateStarted( uint96 minimumAuthorization, uint256 timestamp ); event MinimumAuthorizationUpdated(uint96 minimumAuthorization); event AuthorizationDecreaseDelayUpdateStarted( uint64 authorizationDecreaseDelay, uint256 timestamp ); event AuthorizationDecreaseDelayUpdated(uint64 authorizationDecreaseDelay); event DkgMaliciousResultNotificationRewardMultiplierUpdateStarted( uint256 dkgMaliciousResultNotificationRewardMultiplier, uint256 timestamp ); event DkgMaliciousResultNotificationRewardMultiplierUpdated( uint256 dkgMaliciousResultNotificationRewardMultiplier ); /// @notice Reverts if called before the governance delay elapses. /// @param changeInitiatedTimestamp Timestamp indicating the beginning /// of the change. modifier onlyAfterGovernanceDelay( uint256 changeInitiatedTimestamp, uint256 delay ) { /* solhint-disable not-rely-on-time */ require(changeInitiatedTimestamp > 0, "Change not initiated"); require( block.timestamp - changeInitiatedTimestamp >= delay, "Governance delay has not elapsed" ); _; /* solhint-enable not-rely-on-time */ } constructor(RandomBeacon _randomBeacon) { randomBeacon = _randomBeacon; } /// @notice Begins the relay request fee update process. /// @dev Can be called only by the contract owner. /// @param _newRelayRequestFee New relay request fee function beginRelayRequestFeeUpdate(uint256 _newRelayRequestFee) external onlyOwner { /* solhint-disable not-rely-on-time */ newRelayRequestFee = _newRelayRequestFee; relayRequestFeeChangeInitiated = block.timestamp; emit RelayRequestFeeUpdateStarted(_newRelayRequestFee, block.timestamp); /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the relay request fee update process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeRelayRequestFeeUpdate() external onlyOwner onlyAfterGovernanceDelay( relayRequestFeeChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ) { emit RelayRequestFeeUpdated(newRelayRequestFee); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateRelayEntryParameters( newRelayRequestFee, randomBeacon.relayEntrySubmissionEligibilityDelay(), randomBeacon.relayEntryHardTimeout(), randomBeacon.callbackGasLimit() ); relayRequestFeeChangeInitiated = 0; newRelayRequestFee = 0; } /// @notice Begins the relay entry submission eligibility delay update /// process. /// @dev Can be called only by the contract owner. /// @param _newRelayEntrySubmissionEligibilityDelay New relay entry /// submission eligibility delay in blocks function beginRelayEntrySubmissionEligibilityDelayUpdate( uint256 _newRelayEntrySubmissionEligibilityDelay ) external onlyOwner { /* solhint-disable not-rely-on-time */ require( _newRelayEntrySubmissionEligibilityDelay > 0, "Relay entry submission eligibility delay must be > 0" ); newRelayEntrySubmissionEligibilityDelay = _newRelayEntrySubmissionEligibilityDelay; relayEntrySubmissionEligibilityDelayChangeInitiated = block.timestamp; emit RelayEntrySubmissionEligibilityDelayUpdateStarted( _newRelayEntrySubmissionEligibilityDelay, block.timestamp ); /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the relay entry submission eligibility delay update //// process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeRelayEntrySubmissionEligibilityDelayUpdate() external onlyOwner onlyAfterGovernanceDelay( relayEntrySubmissionEligibilityDelayChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ) { emit RelayEntrySubmissionEligibilityDelayUpdated( newRelayEntrySubmissionEligibilityDelay ); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateRelayEntryParameters( randomBeacon.relayRequestFee(), newRelayEntrySubmissionEligibilityDelay, randomBeacon.relayEntryHardTimeout(), randomBeacon.callbackGasLimit() ); relayEntrySubmissionEligibilityDelayChangeInitiated = 0; newRelayEntrySubmissionEligibilityDelay = 0; } /// @notice Begins the relay entry hard timeout update process. /// @dev Can be called only by the contract owner. /// @param _newRelayEntryHardTimeout New relay entry hard timeout in blocks function beginRelayEntryHardTimeoutUpdate(uint256 _newRelayEntryHardTimeout) external onlyOwner { /* solhint-disable not-rely-on-time */ newRelayEntryHardTimeout = _newRelayEntryHardTimeout; relayEntryHardTimeoutChangeInitiated = block.timestamp; emit RelayEntryHardTimeoutUpdateStarted( _newRelayEntryHardTimeout, block.timestamp ); /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the relay entry hard timeout update process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeRelayEntryHardTimeoutUpdate() external onlyOwner onlyAfterGovernanceDelay( relayEntryHardTimeoutChangeInitiated, CRITICAL_PARAMETER_GOVERNANCE_DELAY ) { emit RelayEntryHardTimeoutUpdated(newRelayEntryHardTimeout); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateRelayEntryParameters( randomBeacon.relayRequestFee(), randomBeacon.relayEntrySubmissionEligibilityDelay(), newRelayEntryHardTimeout, randomBeacon.callbackGasLimit() ); relayEntryHardTimeoutChangeInitiated = 0; newRelayEntryHardTimeout = 0; } /// @notice Begins the callback gas limit update process. /// @dev Can be called only by the contract owner. /// @param _newCallbackGasLimit New callback gas limit function beginCallbackGasLimitUpdate(uint256 _newCallbackGasLimit) external onlyOwner { /* solhint-disable not-rely-on-time */ // slither-disable-next-line too-many-digits require( _newCallbackGasLimit > 0 && _newCallbackGasLimit <= 1e6, "Callback gas limit must be > 0 and <= 1000000" ); newCallbackGasLimit = _newCallbackGasLimit; callbackGasLimitChangeInitiated = block.timestamp; emit CallbackGasLimitUpdateStarted( _newCallbackGasLimit, block.timestamp ); /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the callback gas limit update process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeCallbackGasLimitUpdate() external onlyOwner onlyAfterGovernanceDelay( callbackGasLimitChangeInitiated, CRITICAL_PARAMETER_GOVERNANCE_DELAY ) { emit CallbackGasLimitUpdated(newCallbackGasLimit); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateRelayEntryParameters( randomBeacon.relayRequestFee(), randomBeacon.relayEntrySubmissionEligibilityDelay(), randomBeacon.relayEntryHardTimeout(), newCallbackGasLimit ); callbackGasLimitChangeInitiated = 0; newCallbackGasLimit = 0; } /// @notice Begins the group creation frequency update process. /// @dev Can be called only by the contract owner. /// @param _newGroupCreationFrequency New group creation frequency function beginGroupCreationFrequencyUpdate( uint256 _newGroupCreationFrequency ) external onlyOwner { /* solhint-disable not-rely-on-time */ require( _newGroupCreationFrequency > 0, "Group creation frequency must be > 0" ); newGroupCreationFrequency = _newGroupCreationFrequency; groupCreationFrequencyChangeInitiated = block.timestamp; emit GroupCreationFrequencyUpdateStarted( _newGroupCreationFrequency, block.timestamp ); /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the group creation frequency update process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeGroupCreationFrequencyUpdate() external onlyOwner onlyAfterGovernanceDelay( groupCreationFrequencyChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ) { emit GroupCreationFrequencyUpdated(newGroupCreationFrequency); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateGroupCreationParameters( newGroupCreationFrequency, randomBeacon.groupLifetime() ); groupCreationFrequencyChangeInitiated = 0; newGroupCreationFrequency = 0; } /// @notice Begins the group lifetime update process. /// @dev Can be called only by the contract owner. /// @param _newGroupLifetime New group lifetime in blocks function beginGroupLifetimeUpdate(uint256 _newGroupLifetime) external onlyOwner { /* solhint-disable not-rely-on-time */ require( _newGroupLifetime >= 1 days && _newGroupLifetime <= 2 weeks, "Group lifetime must be >= 1 day and <= 2 weeks" ); newGroupLifetime = _newGroupLifetime; groupLifetimeChangeInitiated = block.timestamp; emit GroupLifetimeUpdateStarted(_newGroupLifetime, block.timestamp); /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the group creation frequency update process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeGroupLifetimeUpdate() external onlyOwner onlyAfterGovernanceDelay( groupLifetimeChangeInitiated, CRITICAL_PARAMETER_GOVERNANCE_DELAY ) { emit GroupLifetimeUpdated(newGroupLifetime); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateGroupCreationParameters( randomBeacon.groupCreationFrequency(), newGroupLifetime ); groupLifetimeChangeInitiated = 0; newGroupLifetime = 0; } /// @notice Begins the DKG result challenge period length update process. /// @dev Can be called only by the contract owner. /// @param _newDkgResultChallengePeriodLength New DKG result challenge /// period length in blocks function beginDkgResultChallengePeriodLengthUpdate( uint256 _newDkgResultChallengePeriodLength ) external onlyOwner { /* solhint-disable not-rely-on-time */ require( _newDkgResultChallengePeriodLength >= 10, "DKG result challenge period length must be >= 10" ); newDkgResultChallengePeriodLength = _newDkgResultChallengePeriodLength; dkgResultChallengePeriodLengthChangeInitiated = block.timestamp; emit DkgResultChallengePeriodLengthUpdateStarted( _newDkgResultChallengePeriodLength, block.timestamp ); /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the DKG result challenge period length update process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeDkgResultChallengePeriodLengthUpdate() external onlyOwner onlyAfterGovernanceDelay( dkgResultChallengePeriodLengthChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ) { emit DkgResultChallengePeriodLengthUpdated( newDkgResultChallengePeriodLength ); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateDkgParameters( newDkgResultChallengePeriodLength, randomBeacon.dkgResultSubmissionEligibilityDelay() ); dkgResultChallengePeriodLengthChangeInitiated = 0; newDkgResultChallengePeriodLength = 0; } /// @notice Begins the DKG result submission eligibility delay update /// process. /// @dev Can be called only by the contract owner. /// @param _newDkgResultSubmissionEligibilityDelay New DKG result submission /// eligibility delay in blocks function beginDkgResultSubmissionEligibilityDelayUpdate( uint256 _newDkgResultSubmissionEligibilityDelay ) external onlyOwner { /* solhint-disable not-rely-on-time */ require( _newDkgResultSubmissionEligibilityDelay > 0, "DKG result submission eligibility delay must be > 0" ); newDkgResultSubmissionEligibilityDelay = _newDkgResultSubmissionEligibilityDelay; dkgResultSubmissionEligibilityDelayChangeInitiated = block.timestamp; emit DkgResultSubmissionEligibilityDelayUpdateStarted( _newDkgResultSubmissionEligibilityDelay, block.timestamp ); /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the DKG result submission eligibility delay update /// process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeDkgResultSubmissionEligibilityDelayUpdate() external onlyOwner onlyAfterGovernanceDelay( dkgResultSubmissionEligibilityDelayChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ) { emit DkgResultSubmissionEligibilityDelayUpdated( newDkgResultSubmissionEligibilityDelay ); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateDkgParameters( randomBeacon.dkgResultChallengePeriodLength(), newDkgResultSubmissionEligibilityDelay ); dkgResultSubmissionEligibilityDelayChangeInitiated = 0; newDkgResultSubmissionEligibilityDelay = 0; } /// @notice Begins the DKG result submission reward update process. /// @dev Can be called only by the contract owner. /// @param _newDkgResultSubmissionReward New DKG result submission reward function beginDkgResultSubmissionRewardUpdate( uint256 _newDkgResultSubmissionReward ) external onlyOwner { /* solhint-disable not-rely-on-time */ newDkgResultSubmissionReward = _newDkgResultSubmissionReward; dkgResultSubmissionRewardChangeInitiated = block.timestamp; emit DkgResultSubmissionRewardUpdateStarted( _newDkgResultSubmissionReward, block.timestamp ); /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the DKG result submission reward update process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeDkgResultSubmissionRewardUpdate() external onlyOwner onlyAfterGovernanceDelay( dkgResultSubmissionRewardChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ) { emit DkgResultSubmissionRewardUpdated(newDkgResultSubmissionReward); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateRewardParameters( newDkgResultSubmissionReward, randomBeacon.sortitionPoolUnlockingReward(), randomBeacon.ineligibleOperatorNotifierReward(), randomBeacon.sortitionPoolRewardsBanDuration(), randomBeacon.relayEntryTimeoutNotificationRewardMultiplier(), randomBeacon.unauthorizedSigningNotificationRewardMultiplier(), randomBeacon.dkgMaliciousResultNotificationRewardMultiplier() ); dkgResultSubmissionRewardChangeInitiated = 0; newDkgResultSubmissionReward = 0; } /// @notice Begins the sortition pool unlocking reward update process. /// @dev Can be called only by the contract owner. /// @param _newSortitionPoolUnlockingReward New sortition pool unlocking reward function beginSortitionPoolUnlockingRewardUpdate( uint256 _newSortitionPoolUnlockingReward ) external onlyOwner { /* solhint-disable not-rely-on-time */ newSortitionPoolUnlockingReward = _newSortitionPoolUnlockingReward; sortitionPoolUnlockingRewardChangeInitiated = block.timestamp; emit SortitionPoolUnlockingRewardUpdateStarted( _newSortitionPoolUnlockingReward, block.timestamp ); /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the sortition pool unlocking reward update process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeSortitionPoolUnlockingRewardUpdate() external onlyOwner onlyAfterGovernanceDelay( sortitionPoolUnlockingRewardChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ) { emit SortitionPoolUnlockingRewardUpdated( newSortitionPoolUnlockingReward ); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateRewardParameters( randomBeacon.dkgResultSubmissionReward(), newSortitionPoolUnlockingReward, randomBeacon.ineligibleOperatorNotifierReward(), randomBeacon.sortitionPoolRewardsBanDuration(), randomBeacon.relayEntryTimeoutNotificationRewardMultiplier(), randomBeacon.unauthorizedSigningNotificationRewardMultiplier(), randomBeacon.dkgMaliciousResultNotificationRewardMultiplier() ); sortitionPoolUnlockingRewardChangeInitiated = 0; newSortitionPoolUnlockingReward = 0; } /// @notice Begins the ineligible operator notifier reward update process. /// @dev Can be called only by the contract owner. /// @param _newIneligibleOperatorNotifierReward New ineligible operator /// notifier reward. function beginIneligibleOperatorNotifierRewardUpdate( uint256 _newIneligibleOperatorNotifierReward ) external onlyOwner { /* solhint-disable not-rely-on-time */ newIneligibleOperatorNotifierReward = _newIneligibleOperatorNotifierReward; ineligibleOperatorNotifierRewardChangeInitiated = block.timestamp; emit IneligibleOperatorNotifierRewardUpdateStarted( _newIneligibleOperatorNotifierReward, block.timestamp ); /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the ineligible operator notifier reward update process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeIneligibleOperatorNotifierRewardUpdate() external onlyOwner onlyAfterGovernanceDelay( ineligibleOperatorNotifierRewardChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ) { emit IneligibleOperatorNotifierRewardUpdated( newIneligibleOperatorNotifierReward ); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateRewardParameters( randomBeacon.dkgResultSubmissionReward(), randomBeacon.sortitionPoolUnlockingReward(), newIneligibleOperatorNotifierReward, randomBeacon.sortitionPoolRewardsBanDuration(), randomBeacon.relayEntryTimeoutNotificationRewardMultiplier(), randomBeacon.unauthorizedSigningNotificationRewardMultiplier(), randomBeacon.dkgMaliciousResultNotificationRewardMultiplier() ); ineligibleOperatorNotifierRewardChangeInitiated = 0; newIneligibleOperatorNotifierReward = 0; } /// @notice Begins the sortition pool rewards ban duration update process. /// @dev Can be called only by the contract owner. /// @param _newSortitionPoolRewardsBanDuration New sortition pool rewards /// ban duration. function beginSortitionPoolRewardsBanDurationUpdate( uint256 _newSortitionPoolRewardsBanDuration ) external onlyOwner { /* solhint-disable not-rely-on-time */ newSortitionPoolRewardsBanDuration = _newSortitionPoolRewardsBanDuration; sortitionPoolRewardsBanDurationChangeInitiated = block.timestamp; emit SortitionPoolRewardsBanDurationUpdateStarted( _newSortitionPoolRewardsBanDuration, block.timestamp ); /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the sortition pool rewards ban duration update process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeSortitionPoolRewardsBanDurationUpdate() external onlyOwner onlyAfterGovernanceDelay( sortitionPoolRewardsBanDurationChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ) { emit SortitionPoolRewardsBanDurationUpdated( newSortitionPoolRewardsBanDuration ); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateRewardParameters( randomBeacon.dkgResultSubmissionReward(), randomBeacon.sortitionPoolUnlockingReward(), randomBeacon.ineligibleOperatorNotifierReward(), newSortitionPoolRewardsBanDuration, randomBeacon.relayEntryTimeoutNotificationRewardMultiplier(), randomBeacon.unauthorizedSigningNotificationRewardMultiplier(), randomBeacon.dkgMaliciousResultNotificationRewardMultiplier() ); sortitionPoolRewardsBanDurationChangeInitiated = 0; newSortitionPoolRewardsBanDuration = 0; } /// @notice Begins the relay entry timeout notification reward multiplier /// update process. /// @dev Can be called only by the contract owner. /// @param _newRelayEntryTimeoutNotificationRewardMultiplier New relay /// entry timeout notification reward multiplier. function beginRelayEntryTimeoutNotificationRewardMultiplierUpdate( uint256 _newRelayEntryTimeoutNotificationRewardMultiplier ) external onlyOwner { /* solhint-disable not-rely-on-time */ require( _newRelayEntryTimeoutNotificationRewardMultiplier <= 100, "Maximum value is 100" ); newRelayEntryTimeoutNotificationRewardMultiplier = _newRelayEntryTimeoutNotificationRewardMultiplier; relayEntryTimeoutNotificationRewardMultiplierChangeInitiated = block .timestamp; emit RelayEntryTimeoutNotificationRewardMultiplierUpdateStarted( _newRelayEntryTimeoutNotificationRewardMultiplier, block.timestamp ); /* solhint-enable not-rely-on-time */ } /// @notice Begins the unauthorized signing notification reward multiplier /// update process. /// @dev Can be called only by the contract owner. /// @param _newUnauthorizedSigningNotificationRewardMultiplier New unauthorized /// signing notification reward multiplier. function beginUnauthorizedSigningNotificationRewardMultiplierUpdate( uint256 _newUnauthorizedSigningNotificationRewardMultiplier ) external onlyOwner { /* solhint-disable not-rely-on-time */ require( _newUnauthorizedSigningNotificationRewardMultiplier <= 100, "Maximum value is 100" ); newUnauthorizedSigningNotificationRewardMultiplier = _newUnauthorizedSigningNotificationRewardMultiplier; unauthorizedSigningNotificationRewardMultiplierChangeInitiated = block .timestamp; emit UnauthorizedSigningNotificationRewardMultiplierUpdateStarted( _newUnauthorizedSigningNotificationRewardMultiplier, block.timestamp ); /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the unauthorized signing notification reward /// multiplier update process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeUnauthorizedSigningNotificationRewardMultiplierUpdate() external onlyOwner onlyAfterGovernanceDelay( unauthorizedSigningNotificationRewardMultiplierChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ) { emit UnauthorizedSigningNotificationRewardMultiplierUpdated( newUnauthorizedSigningNotificationRewardMultiplier ); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateRewardParameters( randomBeacon.dkgResultSubmissionReward(), randomBeacon.sortitionPoolUnlockingReward(), randomBeacon.ineligibleOperatorNotifierReward(), randomBeacon.sortitionPoolRewardsBanDuration(), randomBeacon.relayEntryTimeoutNotificationRewardMultiplier(), newUnauthorizedSigningNotificationRewardMultiplier, randomBeacon.dkgMaliciousResultNotificationRewardMultiplier() ); unauthorizedSigningNotificationRewardMultiplierChangeInitiated = 0; newUnauthorizedSigningNotificationRewardMultiplier = 0; } /// @notice Finalizes the relay entry timeout notification reward /// multiplier update process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeRelayEntryTimeoutNotificationRewardMultiplierUpdate() external onlyOwner onlyAfterGovernanceDelay( relayEntryTimeoutNotificationRewardMultiplierChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ) { emit RelayEntryTimeoutNotificationRewardMultiplierUpdated( newRelayEntryTimeoutNotificationRewardMultiplier ); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateRewardParameters( randomBeacon.dkgResultSubmissionReward(), randomBeacon.sortitionPoolUnlockingReward(), randomBeacon.ineligibleOperatorNotifierReward(), randomBeacon.sortitionPoolRewardsBanDuration(), newRelayEntryTimeoutNotificationRewardMultiplier, randomBeacon.unauthorizedSigningNotificationRewardMultiplier(), randomBeacon.dkgMaliciousResultNotificationRewardMultiplier() ); relayEntryTimeoutNotificationRewardMultiplierChangeInitiated = 0; newRelayEntryTimeoutNotificationRewardMultiplier = 0; } /// @notice Begins the DKG malicious result notification reward multiplier /// update process. /// @dev Can be called only by the contract owner. /// @param _newDkgMaliciousResultNotificationRewardMultiplier New DKG /// malicious result notification reward multiplier. function beginDkgMaliciousResultNotificationRewardMultiplierUpdate( uint256 _newDkgMaliciousResultNotificationRewardMultiplier ) external onlyOwner { /* solhint-disable not-rely-on-time */ require( _newDkgMaliciousResultNotificationRewardMultiplier <= 100, "Maximum value is 100" ); newDkgMaliciousResultNotificationRewardMultiplier = _newDkgMaliciousResultNotificationRewardMultiplier; dkgMaliciousResultNotificationRewardMultiplierChangeInitiated = block .timestamp; emit DkgMaliciousResultNotificationRewardMultiplierUpdateStarted( _newDkgMaliciousResultNotificationRewardMultiplier, block.timestamp ); /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the DKG malicious result notification reward /// multiplier update process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeDkgMaliciousResultNotificationRewardMultiplierUpdate() external onlyOwner onlyAfterGovernanceDelay( dkgMaliciousResultNotificationRewardMultiplierChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ) { emit DkgMaliciousResultNotificationRewardMultiplierUpdated( newDkgMaliciousResultNotificationRewardMultiplier ); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateRewardParameters( randomBeacon.dkgResultSubmissionReward(), randomBeacon.sortitionPoolUnlockingReward(), randomBeacon.ineligibleOperatorNotifierReward(), randomBeacon.sortitionPoolRewardsBanDuration(), randomBeacon.relayEntryTimeoutNotificationRewardMultiplier(), randomBeacon.unauthorizedSigningNotificationRewardMultiplier(), newDkgMaliciousResultNotificationRewardMultiplier ); dkgMaliciousResultNotificationRewardMultiplierChangeInitiated = 0; newDkgMaliciousResultNotificationRewardMultiplier = 0; } /// @notice Begins the relay entry submission failure slashing amount update /// process. /// @dev Can be called only by the contract owner. /// @param _newRelayEntrySubmissionFailureSlashingAmount New relay entry /// submission failure slashing amount function beginRelayEntrySubmissionFailureSlashingAmountUpdate( uint256 _newRelayEntrySubmissionFailureSlashingAmount ) external onlyOwner { /* solhint-disable not-rely-on-time */ newRelayEntrySubmissionFailureSlashingAmount = _newRelayEntrySubmissionFailureSlashingAmount; relayEntrySubmissionFailureSlashingAmountChangeInitiated = block .timestamp; emit RelayEntrySubmissionFailureSlashingAmountUpdateStarted( _newRelayEntrySubmissionFailureSlashingAmount, block.timestamp ); /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the relay entry submission failure slashing amount /// update process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeRelayEntrySubmissionFailureSlashingAmountUpdate() external onlyOwner onlyAfterGovernanceDelay( relayEntrySubmissionFailureSlashingAmountChangeInitiated, CRITICAL_PARAMETER_GOVERNANCE_DELAY ) { emit RelayEntrySubmissionFailureSlashingAmountUpdated( newRelayEntrySubmissionFailureSlashingAmount ); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateSlashingParameters( newRelayEntrySubmissionFailureSlashingAmount, randomBeacon.maliciousDkgResultSlashingAmount(), randomBeacon.unauthorizedSigningSlashingAmount() ); relayEntrySubmissionFailureSlashingAmountChangeInitiated = 0; newRelayEntrySubmissionFailureSlashingAmount = 0; } /// @notice Begins the malicious DKG result slashing amount update process. /// @dev Can be called only by the contract owner. /// @param _newMaliciousDkgResultSlashingAmount New malicious DKG result /// slashing amount function beginMaliciousDkgResultSlashingAmountUpdate( uint256 _newMaliciousDkgResultSlashingAmount ) external onlyOwner { /* solhint-disable not-rely-on-time */ newMaliciousDkgResultSlashingAmount = _newMaliciousDkgResultSlashingAmount; maliciousDkgResultSlashingAmountChangeInitiated = block.timestamp; emit MaliciousDkgResultSlashingAmountUpdateStarted( _newMaliciousDkgResultSlashingAmount, block.timestamp ); /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the malicious DKG result slashing amount update /// process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeMaliciousDkgResultSlashingAmountUpdate() external onlyOwner onlyAfterGovernanceDelay( maliciousDkgResultSlashingAmountChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ) { emit MaliciousDkgResultSlashingAmountUpdated( newMaliciousDkgResultSlashingAmount ); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateSlashingParameters( randomBeacon.relayEntrySubmissionFailureSlashingAmount(), newMaliciousDkgResultSlashingAmount, randomBeacon.unauthorizedSigningSlashingAmount() ); maliciousDkgResultSlashingAmountChangeInitiated = 0; newMaliciousDkgResultSlashingAmount = 0; } /// @notice Begins the unauthorized signing slashing amount update process. /// @dev Can be called only by the contract owner. /// @param _newUnauthorizedSigningSlashingAmount New unauthorized signing /// slashing amount function beginUnauthorizedSigningSlashingAmountUpdate( uint256 _newUnauthorizedSigningSlashingAmount ) external onlyOwner { /* solhint-disable not-rely-on-time */ newUnauthorizedSigningSlashingAmount = _newUnauthorizedSigningSlashingAmount; unauthorizedSigningSlashingAmountChangeInitiated = block.timestamp; emit UnauthorizedSigningSlashingAmountUpdateStarted( _newUnauthorizedSigningSlashingAmount, block.timestamp ); /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the unauthorized signing slashing amount update /// process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeUnauthorizedSigningSlashingAmountUpdate() external onlyOwner onlyAfterGovernanceDelay( unauthorizedSigningSlashingAmountChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ) { emit UnauthorizedSigningSlashingAmountUpdated( newUnauthorizedSigningSlashingAmount ); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateSlashingParameters( randomBeacon.relayEntrySubmissionFailureSlashingAmount(), randomBeacon.maliciousDkgResultSlashingAmount(), newUnauthorizedSigningSlashingAmount ); unauthorizedSigningSlashingAmountChangeInitiated = 0; newUnauthorizedSigningSlashingAmount = 0; } /// @notice Begins the minimum authorization amount update process. /// @dev Can be called only by the contract owner. /// @param _newMinimumAuthorization New minimum authorization amount. function beginMinimumAuthorizationUpdate(uint96 _newMinimumAuthorization) external onlyOwner { /* solhint-disable not-rely-on-time */ newMinimumAuthorization = _newMinimumAuthorization; minimumAuthorizationChangeInitiated = block.timestamp; emit MinimumAuthorizationUpdateStarted( _newMinimumAuthorization, block.timestamp ); /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the minimum authorization amount update process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeMinimumAuthorizationUpdate() external onlyOwner onlyAfterGovernanceDelay( minimumAuthorizationChangeInitiated, CRITICAL_PARAMETER_GOVERNANCE_DELAY ) { emit MinimumAuthorizationUpdated(newMinimumAuthorization); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateAuthorizationParameters( newMinimumAuthorization, randomBeacon.authorizationDecreaseDelay() ); minimumAuthorizationChangeInitiated = 0; newMinimumAuthorization = 0; } /// @notice Begins the authorization decrease delay update process. /// @dev Can be called only by the contract owner. /// @param _newAuthorizationDecreaseDelay New authorization decrease delay function beginAuthorizationDecreaseDelayUpdate( uint64 _newAuthorizationDecreaseDelay ) external onlyOwner { /* solhint-disable not-rely-on-time */ newAuthorizationDecreaseDelay = _newAuthorizationDecreaseDelay; authorizationDecreaseDelayChangeInitiated = block.timestamp; emit AuthorizationDecreaseDelayUpdateStarted( _newAuthorizationDecreaseDelay, block.timestamp ); /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the authorization decrease delay update process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeAuthorizationDecreaseDelayUpdate() external onlyOwner onlyAfterGovernanceDelay( authorizationDecreaseDelayChangeInitiated, CRITICAL_PARAMETER_GOVERNANCE_DELAY ) { emit AuthorizationDecreaseDelayUpdated(newAuthorizationDecreaseDelay); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateAuthorizationParameters( randomBeacon.minimumAuthorization(), newAuthorizationDecreaseDelay ); authorizationDecreaseDelayChangeInitiated = 0; newAuthorizationDecreaseDelay = 0; } /// @notice Withdraws rewards belonging to operators marked as ineligible /// for sortition pool rewards. /// @dev Can be called only by the contract owner. /// @param recipient Recipient of withdrawn rewards. function withdrawIneligibleRewards(address recipient) external onlyOwner { randomBeacon.withdrawIneligibleRewards(recipient); } /// @notice Get the time remaining until the relay request fee can be /// updated. /// @return Remaining time in seconds. function getRemainingRelayRequestFeeUpdateTime() external view returns (uint256) { return getRemainingChangeTime( relayRequestFeeChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the relay entry submission /// eligibility delay can be updated. /// @return Remaining time in seconds. function getRemainingRelayEntrySubmissionEligibilityDelayUpdateTime() external view returns (uint256) { return getRemainingChangeTime( relayEntrySubmissionEligibilityDelayChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the relay entry hard timeout can be /// updated. /// @return Remaining time in seconds. function getRemainingRelayEntryHardTimeoutUpdateTime() external view returns (uint256) { return getRemainingChangeTime( relayEntryHardTimeoutChangeInitiated, CRITICAL_PARAMETER_GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the callback gas limit can be /// updated. /// @return Remaining time in seconds. function getRemainingCallbackGasLimitUpdateTime() external view returns (uint256) { return getRemainingChangeTime( callbackGasLimitChangeInitiated, CRITICAL_PARAMETER_GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the group creation frequency can be /// updated. /// @return Remaining time in seconds. function getRemainingGroupCreationFrequencyUpdateTime() external view returns (uint256) { return getRemainingChangeTime( groupCreationFrequencyChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the group lifetime can be updated. /// @return Remaining time in seconds. function getRemainingGroupLifetimeUpdateTime() external view returns (uint256) { return getRemainingChangeTime( groupLifetimeChangeInitiated, CRITICAL_PARAMETER_GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the DKG result challenge period /// length can be updated. /// @return Remaining time in seconds. function getRemainingDkgResultChallengePeriodLengthUpdateTime() external view returns (uint256) { return getRemainingChangeTime( dkgResultChallengePeriodLengthChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the DKG result submission /// eligibility delay can be updated. /// @return Remaining time in seconds. function getRemainingDkgResultSubmissionEligibilityDelayUpdateTime() external view returns (uint256) { return getRemainingChangeTime( dkgResultSubmissionEligibilityDelayChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the DKG result submission reward /// can be updated. /// @return Remaining time in seconds. function getRemainingDkgResultSubmissionRewardUpdateTime() external view returns (uint256) { return getRemainingChangeTime( dkgResultSubmissionRewardChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the sortition pool unlocking reward /// can be updated. /// @return Remaining time in seconds. function getRemainingSortitionPoolUnlockingRewardUpdateTime() external view returns (uint256) { return getRemainingChangeTime( sortitionPoolUnlockingRewardChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the ineligible operator notifier /// reward can be updated. /// @return Remaining time in seconds. function getRemainingIneligibleOperatorNotifierRewardUpdateTime() external view returns (uint256) { return getRemainingChangeTime( ineligibleOperatorNotifierRewardChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the relay entry submission failure /// slashing amount can be updated. /// @return Remaining time in seconds. function getRemainingRelayEntrySubmissionFailureSlashingAmountUpdateTime() external view returns (uint256) { return getRemainingChangeTime( relayEntrySubmissionFailureSlashingAmountChangeInitiated, CRITICAL_PARAMETER_GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the malicious DKG result /// slashing amount can be updated. /// @return Remaining time in seconds. function getRemainingMaliciousDkgResultSlashingAmountUpdateTime() external view returns (uint256) { return getRemainingChangeTime( maliciousDkgResultSlashingAmountChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the unauthorized signing /// slashing amount can be updated. /// @return Remaining time in seconds. function getRemainingUnauthorizedSigningSlashingAmountUpdateTime() external view returns (uint256) { return getRemainingChangeTime( unauthorizedSigningSlashingAmountChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the minimum authorization amount /// can be updated. /// @return Remaining time in seconds. function getRemainingMimimumAuthorizationUpdateTime() external view returns (uint256) { return getRemainingChangeTime( minimumAuthorizationChangeInitiated, CRITICAL_PARAMETER_GOVERNANCE_DELAY ); } function getRemainingAuthorizationDecreaseDelayUpdateTime() external view returns (uint256) { return getRemainingChangeTime( authorizationDecreaseDelayChangeInitiated, CRITICAL_PARAMETER_GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the sortition pool rewards ban /// duration can be updated. /// @return Remaining time in seconds. function getRemainingSortitionPoolRewardsBanDurationUpdateTime() external view returns (uint256) { return getRemainingChangeTime( sortitionPoolRewardsBanDurationChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the relay entry timeout /// notification reward multiplier duration can be updated. /// @return Remaining time in seconds. function getRemainingRelayEntryTimeoutNotificationRewardMultiplierUpdateTime() external view returns (uint256) { return getRemainingChangeTime( relayEntryTimeoutNotificationRewardMultiplierChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the unauthorized signing /// notification reward multiplier duration can be updated. /// @return Remaining time in seconds. function getRemainingUnauthorizedSigningNotificationRewardMultiplierUpdateTime() external view returns (uint256) { return getRemainingChangeTime( unauthorizedSigningNotificationRewardMultiplierChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the DKG malicious result /// notification reward multiplier duration can be updated. /// @return Remaining time in seconds. function getRemainingDkgMaliciousResultNotificationRewardMultiplierUpdateTime() external view returns (uint256) { return getRemainingChangeTime( dkgMaliciousResultNotificationRewardMultiplierChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ); } /// @notice Gets the time remaining until the governable parameter update /// can be committed. /// @param changeTimestamp Timestamp indicating the beginning of the change. /// @param delay Governance delay. /// @return Remaining time in seconds. function getRemainingChangeTime(uint256 changeTimestamp, uint256 delay) internal view returns (uint256) { require(changeTimestamp > 0, "Change not initiated"); /* solhint-disable-next-line not-rely-on-time */ uint256 elapsed = block.timestamp - changeTimestamp; if (elapsed >= delay) { return 0; } else { return delay - elapsed; } } }
Get the time remaining until the unauthorized signing notification reward multiplier duration can be updated. return Remaining time in seconds.
function getRemainingUnauthorizedSigningNotificationRewardMultiplierUpdateTime() external view returns (uint256) { return getRemainingChangeTime( unauthorizedSigningNotificationRewardMultiplierChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ); }
12,899,177
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./ERC1155eenft.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155Holder.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /// @title Smart contract of eenft /// @author eenft Team /// @dev It's entry function of eenft service contract eenftContract is ERC1155eenft, ERC1155Holder, Ownable, ReentrancyGuard{ using SafeMath for uint256; /// @dev When creating collectible event EventCreatingCollectible(uint256 id, uint256 nftPriceUnit); /// @dev when customer bought a NFT event EventBuyingCollectible(address buyer, uint256 id,uint256 amountNFT); /// @dev when the customer resells a NFT event EventResellCollectible(address seller, uint256 id,uint256 amountNFT); /// @dev When owner activate the resell event EventActivatedResellID(uint256 id,bool activate); /// @dev When customer withdraw after resell event Eventwithdrawal(address addressWithdraw,uint256 amount); /// @dev When transfert from contract to adress event EventTransferTo(address addressToTransfert, uint256 amountToWithdraw); /// @dev Mapping from NFTid to NFTPrice in ETH mapping(uint256=>uint256) public nftPriceUnitById; /// @dev Collection activating for resell mapping(uint256=>bool) public idResellActivate; /// @dev Withdraw address=>ammount in eth mapping(address=>uint256) public withdrawByAddress; /// @dev must indicate setOwnerNFT constructor() public ERC1155eenft("https://eenft.com/nft/{id}.json") { setOwnerNFT(address(this)); } /// @dev Create NFT collection. /// @param id id of collection, allows to personalise the uri to the json. /// @param amount number of NFT in collectible. /// @param nftPriceUnit price of one NFT in ETH function createCollectible(uint256 id, uint256 amount, uint256 nftPriceUnit) public onlyOwner{ nftPriceUnitById[id]=nftPriceUnit; _mint(address(this), id, amount, ""); emit EventCreatingCollectible(id,nftPriceUnit); } /// @dev Buy NFT of collection, FIXME if the customer wants to buy several NFT so you have to implement buy with safeBatchTransfer /// @param id number of NFT in collectible. /// @param amountNFT price of one NFT in ETH function buy(uint256 id, uint256 amountNFT) public payable allowTransfer{ require(nftPriceUnitById[id]!=0,"NFTIMABLE:Price doesn't exist"); uint256 price = nftPriceUnitById[id].mul(amountNFT); require(msg.value==price,"NFTIMABLE:the amount sent is not correct"); safeTransferFrom(address(this), msg.sender, id, amountNFT, ""); emit EventBuyingCollectible(msg.sender, id, amountNFT); } /// @dev activate collection for resell. NFTs can only be resold when the entire collection is sold. /// @param id id of collection. /// @param activate if activate, customer can resell NFT of collection. function activateResellID(uint256 id, bool activate) public onlyOwner{ idResellActivate[id]=activate; emit EventActivatedResellID(id,activate); } /// @dev is activate collectible for resell, NFTs can only be resold when the entire collection is sold. /// @param id id of collection. /// @return true if collection activate for resell function isIdActivateForResell(uint256 id) public view returns (bool){ return idResellActivate[id]; } /// @dev activate a collection for resell, withdraw is manage by back when the NFT is actually resold /// @param id id of collection. /// @param amountNFT number NFT of collection to resell function reSell(uint256 id, uint256 amountNFT) public allowTransfer{ require(isIdActivateForResell(id),"NFTIMABLE:Resell not activated wet"); safeTransferFrom(msg.sender, address(this), id, amountNFT, ""); uint256 price = nftPriceUnitById[id].mul(amountNFT); withdrawByAddress[msg.sender]=withdrawByAddress[msg.sender].add(price); emit EventResellCollectible(msg.sender, id,amountNFT); } /// @dev withdraw ETH after resold. function withdraw() public nonReentrant{ require(withdrawByAddress[msg.sender]>=0,"NFTIMABLE:Nothing to refund"); require(address(this).balance>withdrawByAddress[msg.sender],"NFTIMABLE:Not enought amount to withdraw"); uint256 amountToWithdraw=withdrawByAddress[msg.sender]; msg.sender.transfer(amountToWithdraw); withdrawByAddress[msg.sender]=0; emit Eventwithdrawal(msg.sender,amountToWithdraw); } /// @dev transfer eth from contract to address /// @param addressToTransfer address that receives the funds /// @param amountToWithdraw amount in ETH function transferTo(address payable addressToTransfer, uint256 amountToWithdraw) public onlyOwner nonReentrant (){ require(address(this).balance>amountToWithdraw,"NFTIMABLE:Not enought amount to transfertTo"); addressToTransfer.transfer(amountToWithdraw); emit EventTransferTo(addressToTransfer, amountToWithdraw); } //payable obligation receive() external payable { } }
Buy NFT of collection, FIXME if the customer wants to buy several NFT so you have to implement buy with safeBatchTransfer id number of NFT in collectible. amountNFT price of one NFT in ETH
function buy(uint256 id, uint256 amountNFT) public payable allowTransfer{ require(nftPriceUnitById[id]!=0,"NFTIMABLE:Price doesn't exist"); uint256 price = nftPriceUnitById[id].mul(amountNFT); require(msg.value==price,"NFTIMABLE:the amount sent is not correct"); safeTransferFrom(address(this), msg.sender, id, amountNFT, ""); emit EventBuyingCollectible(msg.sender, id, amountNFT); }
12,850,264
pragma solidity ^0.4.24; /** * @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; /** * @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 transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = true; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused returns (bool) { paused = true; emit Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused returns (bool) { paused = false; emit Unpause(); return true; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { 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; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant 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); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @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) { 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 constant returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) 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 amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { uint256 _allowance = allowed[_from][msg.sender]; balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @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) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); 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 specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) constant public returns (uint256 remaining) { return allowed[_owner][_spender]; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * 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); _; } /** * @dev Function to mint tokens * @param _to The address that will recieve 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 onlyOwner canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(0X0, _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } contract BlockableToken is Ownable{ event Blocked(address blockedAddress); event UnBlocked(address unBlockedAddress); //keep mapping of blocked addresses mapping (address => bool) public blockedAddresses; modifier whenNotBlocked(){ require(!blockedAddresses[msg.sender]); _; } function blockAddress(address toBeBlocked) onlyOwner public { blockedAddresses[toBeBlocked] = true; emit Blocked(toBeBlocked); } function unBlockAddress(address toBeUnblocked) onlyOwner public { blockedAddresses[toBeUnblocked] = false; emit UnBlocked(toBeUnblocked); } } contract StrikeToken is MintableToken, Pausable, BlockableToken{ string public name = "Dimensions Strike Token"; string public symbol = "DST"; uint256 public decimals = 18; event Ev(string message, address whom, uint256 val); struct XRec { bool inList; address next; address prev; uint256 val; } struct QueueRecord { address whom; uint256 val; } address first = 0x0; address last = 0x0; mapping (address => XRec) public theList; QueueRecord[] theQueue; // add a record to the END of the list function add(address whom, uint256 value) internal { theList[whom] = XRec(true,0x0,last,value); if (last != 0x0) { theList[last].next = whom; } else { first = whom; } last = whom; emit Ev("add",whom,value); } function remove(address whom) internal { if (first == whom) { first = theList[whom].next; theList[whom] = XRec(false,0x0,0x0,0); return; } address next = theList[whom].next; address prev = theList[whom].prev; if (prev != 0x0) { theList[prev].next = next; } if (next != 0x0) { theList[next].prev = prev; } theList[whom] =XRec(false,0x0,0x0,0); emit Ev("remove",whom,0); } function update(address whom, uint256 value) internal { if (value != 0) { if (!theList[whom].inList) { add(whom,value); } else { theList[whom].val = value; emit Ev("update",whom,value); } return; } if (theList[whom].inList) { remove(whom); } } /** * @dev Allows anyone to transfer the Strike tokens once trading has started * @param _to the recipient address of the tokens. * @param _value number of tokens to be transfered. */ function transfer(address _to, uint _value) public whenNotPaused whenNotBlocked returns (bool) { bool result = super.transfer(_to, _value); update(msg.sender,balances[msg.sender]); update(_to,balances[_to]); return result; } /** * @dev Allows anyone to transfer the Strike tokens once trading has started * @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 uint the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint _value) public whenNotPaused whenNotBlocked returns (bool) { bool result = super.transferFrom(_from, _to, _value); update(_from,balances[_from]); update(_to,balances[_to]); return result; } /** * @dev Function to mint tokens * @param _to The address that will recieve 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 onlyOwner canMint returns (bool) { bool result = super.mint(_to,_amount); update(_to,balances[_to]); return result; } constructor() public{ owner = msg.sender; } function changeOwner(address newOwner) public onlyOwner { owner = newOwner; } } contract StrikeTokenCrowdsale is Ownable, Pausable { using SafeMath for uint256; StrikeToken public token = new StrikeToken(); // start and end times uint256 public startTimestamp = 1575158400; uint256 public endTimestamp = 1577750400; uint256 etherToWei = 10**18; // address where funds are collected and tokens distributed address public hardwareWallet = 0xDe3A91E42E9F6955ce1a9eDb23Be4aBf8d2eb08B; address public restrictedWallet = 0xDe3A91E42E9F6955ce1a9eDb23Be4aBf8d2eb08B; address public additionalTokensFromCommonPoolWallet = 0xDe3A91E42E9F6955ce1a9eDb23Be4aBf8d2eb08B; mapping (address => uint256) public deposits; uint256 public numberOfPurchasers; // Percentage bonus tokens given in Token Sale, on a daily basis uint256[] public bonus = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]; uint256 public rate = 4800; // 4800 DST is one Ether // amount of raised money in wei uint256 public weiRaised = 0; uint256 public tokensSold = 0; uint256 public advisorTokensGranted = 0; uint256 public commonPoolTokensGranted = 0; uint256 public minContribution = 100 * 1 finney; uint256 public hardCapEther = 30000; uint256 hardcap = hardCapEther * etherToWei; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); event MainSaleClosed(); uint256 public weiRaisedInPresale = 0 ether; bool private frozen = false; function freeze() public onlyOwner{ frozen = true; } function unfreeze() public onlyOwner{ frozen = false; } modifier whenNotFrozen() { require(!frozen); _; } modifier whenFrozen() { require(frozen); _; } function setHardwareWallet(address _wallet) public onlyOwner { require(_wallet != 0x0); hardwareWallet = _wallet; } function setRestrictedWallet(address _restrictedWallet) public onlyOwner { require(_restrictedWallet != 0x0); restrictedWallet = _restrictedWallet; } function setAdditionalTokensFromCommonPoolWallet(address _wallet) public onlyOwner { require(_wallet != 0x0); additionalTokensFromCommonPoolWallet = _wallet; } function setHardCapEther(uint256 newEtherAmt) public onlyOwner{ require(newEtherAmt > 0); hardCapEther = newEtherAmt; hardcap = hardCapEther * etherToWei; } constructor() public { require(startTimestamp >= now); require(endTimestamp >= startTimestamp); } // check if valid purchase modifier validPurchase { require(now >= startTimestamp); require(now < endTimestamp); require(msg.value >= minContribution); require(frozen == false); _; } // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { if (now > endTimestamp) return true; return false; } // low level token purchase function function buyTokens(address beneficiary) public payable validPurchase { require(beneficiary != 0x0); uint256 weiAmount = msg.value; // Check if the hardcap has been exceeded uint256 weiRaisedSoFar = weiRaised.add(weiAmount); require(weiRaisedSoFar + weiRaisedInPresale <= hardcap); if (deposits[msg.sender] == 0) { numberOfPurchasers++; } deposits[msg.sender] = weiAmount.add(deposits[msg.sender]); uint256 daysInSale = (now - startTimestamp) / (1 days); uint256 thisBonus = 0; if(daysInSale < 29 ){ thisBonus = bonus[daysInSale]; } // Calculate token amount to be created uint256 tokens = weiAmount.mul(rate); uint256 extraBonus = tokens.mul(thisBonus); extraBonus = extraBonus.div(100); tokens = tokens.add(extraBonus); // Update the global token sale variables uint256 finalTokenCount; finalTokenCount = tokens.add(tokensSold); weiRaised = weiRaisedSoFar; tokensSold = finalTokenCount; token.mint(beneficiary, tokens); hardwareWallet.transfer(msg.value); emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); } function grantTokensAdvisors(address beneficiary,uint256 dstTokenCount) public onlyOwner{ dstTokenCount = dstTokenCount * etherToWei; advisorTokensGranted = advisorTokensGranted.add(dstTokenCount); token.mint(beneficiary,dstTokenCount); } function grantTokensCommonPool(address beneficiary,uint256 dstTokenCount) public onlyOwner{ dstTokenCount = dstTokenCount * etherToWei; commonPoolTokensGranted = commonPoolTokensGranted.add(dstTokenCount); token.mint(beneficiary,dstTokenCount); } // finish mining coins and transfer ownership of Change coin to owner function finishMinting() public onlyOwner returns(bool){ require(hasEnded()); uint issuedTokenSupply = token.totalSupply(); uint publicTokens = issuedTokenSupply-advisorTokensGranted; if(publicTokens>60*advisorTokensGranted/40 ){ uint restrictedTokens=(publicTokens)*40/60-advisorTokensGranted; token.mint(restrictedWallet, restrictedTokens); advisorTokensGranted=advisorTokensGranted+restrictedTokens; } else if(publicTokens<60*advisorTokensGranted/40){ uint256 deltaCommonPool=advisorTokensGranted*60/40-publicTokens; token.mint(additionalTokensFromCommonPoolWallet,deltaCommonPool); } token.finishMinting(); token.transferOwnership(owner); emit MainSaleClosed(); return true; } // fallback function can be used to buy tokens function () payable public { buyTokens(msg.sender); } function setRate(uint256 amount) onlyOwner public { require(amount>=0); rate = amount; } function setBonus(uint256 [] amounts) onlyOwner public { require( amounts.length > 30 ); bonus = amounts; } function setWeiRaisedInPresale(uint256 amount) onlyOwner public { require(amount>=0); weiRaisedInPresale = amount; } function setEndTimeStamp(uint256 end) onlyOwner public { require(end>now); endTimestamp = end; } function setStartTimeStamp(uint256 start) onlyOwner public { startTimestamp = start; } function pauseTrading() onlyOwner public{ token.pause(); } function startTrading() onlyOwner public{ token.unpause(); } function smartBlockAddress(address toBeBlocked) onlyOwner public{ token.blockAddress(toBeBlocked); } function smartUnBlockAddress(address toBeUnblocked) onlyOwner public{ token.unBlockAddress(toBeUnblocked); } function changeTokenOwner(address newOwner) public onlyOwner { require(hasEnded()); token.changeOwner(newOwner); } function bulkGrantTokenAdvisors(address [] beneficiaries,uint256 [] granttokencounts) public onlyOwner{ require( beneficiaries.length == granttokencounts.length); for (uint256 i=0; i<beneficiaries.length; i++) { grantTokensAdvisors(beneficiaries[i],granttokencounts[i]); } } function bulkGrantTokenCommonPool(address [] beneficiaries,uint256 [] granttokencounts) public onlyOwner{ require( beneficiaries.length == granttokencounts.length); for (uint256 i=0; i<beneficiaries.length; i++) { grantTokensCommonPool(beneficiaries[i],granttokencounts[i]); } } }
add a record to the END of the list
function add(address whom, uint256 value) internal { theList[whom] = XRec(true,0x0,last,value); if (last != 0x0) { theList[last].next = whom; first = whom; } last = whom; emit Ev("add",whom,value); }
1,769,246
/** *Submitted for verification at Etherscan.io on 2019-07-04 */ pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account&#39;s access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract PauserRole { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; constructor () internal { _addPauser(msg.sender); } modifier onlyPauser() { require(isPauser(msg.sender)); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(msg.sender); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring &#39;a&#39; not being zero, but the // benefit is lost if &#39;b&#39; is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * Originally based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn&#39;t required by the specification, and other * compliant implementations may not do it. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query 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]; } /** * @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 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) { _transfer(msg.sender, 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&#39;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) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @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) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); return true; } /** * @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 * Emits an Approval event. * @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) public returns (bool) { require(spender != address(0)); _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 * Emits an Approval event. * @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) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender&#39;s allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is PauserRole { event Paused(address account); event Unpaused(address account); bool private _paused; constructor () internal { _paused = false; } /** * @return true if the contract is paused, false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } } /** * @title Pausable token * @dev ERC20 modified with pausable transfers. **/ contract ERC20Pausable is ERC20, Pausable { function transfer(address to, uint256 value) public whenNotPaused returns (bool) { return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public whenNotPaused returns (bool) { return super.approve(spender, value); } function increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseAllowance(spender, subtractedValue); } } /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ 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; } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } } /** * @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 private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return 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 OwnershipTransferred(_owner, address(0)); _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; } } contract BNDESRegistry is Ownable() { /** The account of clients and suppliers are assigned to states. Reserved accounts (e.g. from BNDES and ANCINE) do not have state. AVAILABLE - The account is not yet assigned any role (any of them - client, supplier or any reserved addresses). WAITING_VALIDATION - The account was linked to a legal entity but it still needs to be validated VALIDATED - The account was validated INVALIDATED_BY_VALIDATOR - The account was invalidated INVALIDATED_BY_CHANGE - The client or supplier changed the ethereum account so the original one must be invalidated. */ enum BlockchainAccountState {AVAILABLE,WAITING_VALIDATION,VALIDATED,INVALIDATED_BY_VALIDATOR,INVALIDATED_BY_CHANGE} BlockchainAccountState blockchainState; //Not used. Defined to create the enum type. address responsibleForSettlement; address responsibleForRegistryValidation; address responsibleForDisbursement; address redemptionAddress; address tokenAddress; /** Describes the Legal Entity - clients or suppliers */ struct LegalEntityInfo { uint64 cnpj; //Brazilian identification of legal entity uint64 idFinancialSupportAgreement; //SCC contract uint32 salic; //ANCINE identifier string idProofHash; //hash of declaration BlockchainAccountState state; } /** Links Ethereum addresses to LegalEntityInfo */ mapping(address => LegalEntityInfo) public legalEntitiesInfo; /** Links Legal Entity to Ethereum address. cnpj => (idFinancialSupportAgreement => address) */ mapping(uint64 => mapping(uint64 => address)) cnpjFSAddr; /** Links Ethereum addresses to the possibility to change the account Since the Ethereum account can be changed once, it is not necessary to put the bool to false. TODO: Discuss later what is the best data structure */ mapping(address => bool) public legalEntitiesChangeAccount; event AccountRegistration(address addr, uint64 cnpj, uint64 idFinancialSupportAgreement, uint32 salic, string idProofHash); event AccountChange(address oldAddr, address newAddr, uint64 cnpj, uint64 idFinancialSupportAgreement, uint32 salic, string idProofHash); event AccountValidation(address addr, uint64 cnpj, uint64 idFinancialSupportAgreement, uint32 salic); event AccountInvalidation(address addr, uint64 cnpj, uint64 idFinancialSupportAgreement, uint32 salic); /** * @dev Throws if called by any account other than the token address. */ modifier onlyTokenAddress() { require(isTokenAddress()); _; } constructor () public { responsibleForSettlement = msg.sender; responsibleForRegistryValidation = msg.sender; responsibleForDisbursement = msg.sender; redemptionAddress = msg.sender; } /** * Link blockchain address with CNPJ - It can be a cliente or a supplier * The link still needs to be validated by BNDES * This method can only be called by BNDESToken contract because BNDESToken can pause. * @param cnpj Brazilian identifier to legal entities * @param idFinancialSupportAgreement contract number of financial contract with BNDES. It assumes 0 if it is a supplier. * @param salic contract number of financial contract with ANCINE. It assumes 0 if it is a supplier. * @param addr the address to be associated with the legal entity. * @param idProofHash The legal entities have to send BNDES a PDF where it assumes as responsible for an Ethereum account. * This PDF is signed with eCNPJ and send to BNDES. */ function registryLegalEntity(uint64 cnpj, uint64 idFinancialSupportAgreement, uint32 salic, address addr, string memory idProofHash) onlyTokenAddress public { // Endere&#231;o n&#227;o pode ter sido cadastrado anteriormente require (isAvailableAccount(addr), "Endere&#231;o n&#227;o pode ter sido cadastrado anteriormente"); require (isValidHash(idProofHash), "O hash da declara&#231;&#227;o &#233; inv&#225;lido"); legalEntitiesInfo[addr] = LegalEntityInfo(cnpj, idFinancialSupportAgreement, salic, idProofHash, BlockchainAccountState.WAITING_VALIDATION); // N&#227;o pode haver outro endere&#231;o cadastrado para esse mesmo subcr&#233;dito if (idFinancialSupportAgreement > 0) { address account = getBlockchainAccount(cnpj,idFinancialSupportAgreement); require (isAvailableAccount(account), "Cliente j&#225; est&#225; associado a outro endere&#231;o. Use a fun&#231;&#227;o Troca."); } else { address account = getBlockchainAccount(cnpj,0); require (isAvailableAccount(account), "Fornecedor j&#225; est&#225; associado a outro endere&#231;o. Use a fun&#231;&#227;o Troca."); } cnpjFSAddr[cnpj][idFinancialSupportAgreement] = addr; emit AccountRegistration(addr, cnpj, idFinancialSupportAgreement, salic, idProofHash); } /** * Changes the original link between CNPJ and Ethereum account. * The new link still needs to be validated by BNDES. * This method can only be called by BNDESToken contract because BNDESToken can pause and because there are * additional instructions there. * @param cnpj Brazilian identifier to legal entities * @param idFinancialSupportAgreement contract number of financial contract with BNDES. It assumes 0 if it is a supplier. * @param salic contract number of financial contract with ANCINE. It assumes 0 if it is a supplier. * @param newAddr the new address to be associated with the legal entity * @param idProofHash The legal entities have to send BNDES a PDF where it assumes as responsible for an Ethereum account. * This PDF is signed with eCNPJ and send to BNDES. */ function changeAccountLegalEntity(uint64 cnpj, uint64 idFinancialSupportAgreement, uint32 salic, address newAddr, string memory idProofHash) onlyTokenAddress public { address oldAddr = getBlockchainAccount(cnpj, idFinancialSupportAgreement); // Tem que haver um endere&#231;o associado a esse cnpj/subcr&#233;dito require(!isReservedAccount(oldAddr), "N&#227;o pode trocar endere&#231;o de conta reservada"); require(!isAvailableAccount(oldAddr), "Tem que haver um endere&#231;o associado a esse cnpj/subcr&#233;dito"); require(isAvailableAccount(newAddr), "Novo endere&#231;o n&#227;o est&#225; dispon&#237;vel"); require (isChangeAccountEnabled(oldAddr), "A conta atual n&#227;o est&#225; habilitada para troca"); require (isValidHash(idProofHash), "O hash da declara&#231;&#227;o &#233; inv&#225;lido"); require(legalEntitiesInfo[oldAddr].cnpj==cnpj && legalEntitiesInfo[oldAddr].idFinancialSupportAgreement ==idFinancialSupportAgreement, "Dados inconsistentes de cnpj ou subcr&#233;dito"); // Aponta o novo endere&#231;o para o novo LegalEntityInfo legalEntitiesInfo[newAddr] = LegalEntityInfo(cnpj, idFinancialSupportAgreement, salic, idProofHash, BlockchainAccountState.WAITING_VALIDATION); // Apaga o mapping do endere&#231;o antigo legalEntitiesInfo[oldAddr].state = BlockchainAccountState.INVALIDATED_BY_CHANGE; // Aponta mapping CNPJ e Subcredito para newAddr cnpjFSAddr[cnpj][idFinancialSupportAgreement] = newAddr; emit AccountChange(oldAddr, newAddr, cnpj, idFinancialSupportAgreement, salic, idProofHash); } /** * Validates the initial registry of a legal entity or the change of its registry * @param addr Ethereum address that needs to be validated * @param idProofHash The legal entities have to send BNDES a PDF where it assumes as responsible for an Ethereum account. * This PDF is signed with eCNPJ and send to BNDES. */ function validateRegistryLegalEntity(address addr, string memory idProofHash) public { require(isResponsibleForRegistryValidation(msg.sender), "Somente o respons&#225;vel pela valida&#231;&#227;o pode validar contas"); require(legalEntitiesInfo[addr].state == BlockchainAccountState.WAITING_VALIDATION, "A conta precisa estar no estado Aguardando Valida&#231;&#227;o"); require(keccak256(abi.encodePacked(legalEntitiesInfo[addr].idProofHash)) == keccak256(abi.encodePacked(idProofHash)), "O hash recebido &#233; diferente do esperado"); legalEntitiesInfo[addr].state = BlockchainAccountState.VALIDATED; emit AccountValidation(addr, legalEntitiesInfo[addr].cnpj, legalEntitiesInfo[addr].idFinancialSupportAgreement, legalEntitiesInfo[addr].salic); } /** * Invalidates the initial registry of a legal entity or the change of its registry * The invalidation can be called at any time in the lifecycle of the address (not only when it is WAITING_VALIDATION) * @param addr Ethereum address that needs to be validated */ function invalidateRegistryLegalEntity(address addr) public { require(isResponsibleForRegistryValidation(msg.sender), "Somente o respons&#225;vel pela valida&#231;&#227;o pode invalidar contas"); require(!isReservedAccount(addr), "N&#227;o &#233; poss&#237;vel invalidar conta reservada"); legalEntitiesInfo[addr].state = BlockchainAccountState.INVALIDATED_BY_VALIDATOR; emit AccountInvalidation(addr, legalEntitiesInfo[addr].cnpj, legalEntitiesInfo[addr].idFinancialSupportAgreement, legalEntitiesInfo[addr].salic); } /** * By default, the owner is also the Responsible for Settlement. * The owner can assign other address to be the Responsible for Settlement. * @param rs Ethereum address to be assigned as Responsible for Settlement. */ function setResponsibleForSettlement(address rs) onlyOwner public { responsibleForSettlement = rs; } /** * By default, the owner is also the Responsible for Validation. * The owner can assign other address to be the Responsible for Validation. * @param rs Ethereum address to be assigned as Responsible for Validation. */ function setResponsibleForRegistryValidation(address rs) onlyOwner public { responsibleForRegistryValidation = rs; } /** * By default, the owner is also the Responsible for Disbursment. * The owner can assign other address to be the Responsible for Disbursment. * @param rs Ethereum address to be assigned as Responsible for Disbursment. */ function setResponsibleForDisbursement(address rs) onlyOwner public { responsibleForDisbursement = rs; } /** * The supplier reedems the BNDESToken by transfering the tokens to a specific address, * called Redemption address. * By default, the redemption address is the address of the owner. * The owner can change the redemption address using this function. * @param rs new Redemption address */ function setRedemptionAddress(address rs) onlyOwner public { redemptionAddress = rs; } /** * @param rs Ethereum address to be assigned to the token address. */ function setTokenAddress(address rs) onlyOwner public { tokenAddress = rs; } /** * Enable the legal entity to change the account * @param rs account that can be changed. */ function enableChangeAccount (address rs) public { require(isResponsibleForRegistryValidation(msg.sender), "Somente o respons&#225;vel pela valida&#231;&#227;o pode habilitar a troca de conta"); legalEntitiesChangeAccount[rs] = true; } function isChangeAccountEnabled (address rs) view public returns (bool) { return legalEntitiesChangeAccount[rs] == true; } function isTokenAddress() public view returns (bool) { return tokenAddress == msg.sender; } function isResponsibleForSettlement(address addr) view public returns (bool) { return (addr == responsibleForSettlement); } function isResponsibleForRegistryValidation(address addr) view public returns (bool) { return (addr == responsibleForRegistryValidation); } function isResponsibleForDisbursement(address addr) view public returns (bool) { return (addr == responsibleForDisbursement); } function isRedemptionAddress(address addr) view public returns (bool) { return (addr == redemptionAddress); } function isReservedAccount(address addr) view public returns (bool) { if (isOwner(addr) || isResponsibleForSettlement(addr) || isResponsibleForRegistryValidation(addr) || isResponsibleForDisbursement(addr) || isRedemptionAddress(addr) ) { return true; } return false; } function isOwner(address addr) view public returns (bool) { return owner()==addr; } function isSupplier(address addr) view public returns (bool) { if (isReservedAccount(addr)) return false; if (isAvailableAccount(addr)) return false; return legalEntitiesInfo[addr].idFinancialSupportAgreement == 0; } function isValidatedSupplier (address addr) view public returns (bool) { return isSupplier(addr) && (legalEntitiesInfo[addr].state == BlockchainAccountState.VALIDATED); } function isClient (address addr) view public returns (bool) { if (isReservedAccount(addr)) { return false; } return legalEntitiesInfo[addr].idFinancialSupportAgreement != 0; } function isValidatedClient (address addr) view public returns (bool) { return isClient(addr) && (legalEntitiesInfo[addr].state == BlockchainAccountState.VALIDATED); } function isAvailableAccount(address addr) view public returns (bool) { if ( isReservedAccount(addr) ) { return false; } return legalEntitiesInfo[addr].state == BlockchainAccountState.AVAILABLE; } function isWaitingValidationAccount(address addr) view public returns (bool) { return legalEntitiesInfo[addr].state == BlockchainAccountState.WAITING_VALIDATION; } function isValidatedAccount(address addr) view public returns (bool) { return legalEntitiesInfo[addr].state == BlockchainAccountState.VALIDATED; } function isInvalidatedByValidatorAccount(address addr) view public returns (bool) { return legalEntitiesInfo[addr].state == BlockchainAccountState.INVALIDATED_BY_VALIDATOR; } function isInvalidatedByChangeAccount(address addr) view public returns (bool) { return legalEntitiesInfo[addr].state == BlockchainAccountState.INVALIDATED_BY_CHANGE; } function getResponsibleForSettlement() view public returns (address) { return responsibleForSettlement; } function getResponsibleForRegistryValidation() view public returns (address) { return responsibleForRegistryValidation; } function getResponsibleForDisbursement() view public returns (address) { return responsibleForDisbursement; } function getRedemptionAddress() view public returns (address) { return redemptionAddress; } function getCNPJ(address addr) view public returns (uint64) { return legalEntitiesInfo[addr].cnpj; } function getIdLegalFinancialAgreement(address addr) view public returns (uint64) { return legalEntitiesInfo[addr].idFinancialSupportAgreement; } function getLegalEntityInfo (address addr) view public returns (uint64, uint64, uint32, string memory, uint, address) { return (legalEntitiesInfo[addr].cnpj, legalEntitiesInfo[addr].idFinancialSupportAgreement, legalEntitiesInfo[addr].salic, legalEntitiesInfo[addr].idProofHash, (uint) (legalEntitiesInfo[addr].state), addr); } function getBlockchainAccount(uint64 cnpj, uint64 idFinancialSupportAgreement) view public returns (address) { return cnpjFSAddr[cnpj][idFinancialSupportAgreement]; } function getLegalEntityInfoByCNPJ (uint64 cnpj, uint64 idFinancialSupportAgreement) view public returns (uint64, uint64, uint32, string memory, uint, address) { address addr = getBlockchainAccount(cnpj,idFinancialSupportAgreement); return getLegalEntityInfo (addr); } function getAccountState(address addr) view public returns (int) { if ( isReservedAccount(addr) ) { return 100; } else { return ((int) (legalEntitiesInfo[addr].state)); } } function isValidHash(string memory str) pure public returns (bool) { bytes memory b = bytes(str); if(b.length != 64) return false; for (uint i=0; i<64; i++) { if (b[i] < "0") return false; if (b[i] > "9" && b[i] <"a") return false; if (b[i] > "f") return false; } return true; } } contract BNDESToken is ERC20Pausable, ERC20Detailed("BNDESToken", "BND", 2) { uint private version = 20190517; BNDESRegistry registry; event BNDESTokenDisbursement(uint64 cnpj, uint64 idFinancialSupportAgreement, uint256 value); event BNDESTokenTransfer(uint64 fromCnpj, uint64 fromIdFinancialSupportAgreement, uint64 toCnpj, uint256 value); event BNDESTokenRedemption(uint64 cnpj, uint256 value); event BNDESTokenRedemptionSettlement(string redemptionTransactionHash, string receiptHash); event BNDESManualIntervention(string description); /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } constructor (address newRegistryAddr) public { registry = BNDESRegistry(newRegistryAddr); } function getVersion() view public returns (uint) { return version; } /** * The transfer funcion follows ERC20 token signature. * Using them, it is possible to disburse money to the client, transfer from client to supplier and redeem. * @param to the Ethereum address to where the money should be sent * @param value how much BNDESToken the supplier wants to redeem */ function transfer (address to, uint256 value) public whenNotPaused returns (bool) { address from = msg.sender; require(from != to, "N&#227;o pode transferir token para si mesmo"); if (registry.isResponsibleForDisbursement(from)) { require(registry.isValidatedClient(to), "O endere&#231;o n&#227;o pertence a um cliente ou n&#227;o est&#225; validada"); _mint(to, value); emit BNDESTokenDisbursement(registry.getCNPJ(to), registry.getIdLegalFinancialAgreement(to), value); } else { if (registry.isRedemptionAddress(to)) { require(registry.isValidatedSupplier(from), "A conta do endere&#231;o n&#227;o pertence a um fornecedor ou n&#227;o est&#225; validada"); _burn(from, value); emit BNDESTokenRedemption(registry.getCNPJ(from), value); } else { // Se nem from nem to s&#227;o o Banco, eh transferencia normal require(registry.isValidatedClient(from), "O endere&#231;o n&#227;o pertence a um cliente ou n&#227;o est&#225; validada"); require(registry.isValidatedSupplier(to), "A conta do endere&#231;o n&#227;o pertence a um fornecedor ou n&#227;o est&#225; validada"); _transfer(msg.sender, to, value); emit BNDESTokenTransfer(registry.getCNPJ(from), registry.getIdLegalFinancialAgreement(from), registry.getCNPJ(to), value); } } return true; } /** * When redeeming, the supplier indicated to the Resposible for Settlement that he wants to receive * the FIAT money. * @param value - how much BNDESToken the supplier wants to redeem */ function redeem (uint256 value) public whenNotPaused returns (bool) { return transfer(registry.getRedemptionAddress(), value); } /** * Using this function, the Responsible for Settlement indicates that he has made the FIAT money transfer. * @param redemptionTransactionHash hash of the redeem transaction in which the FIAT money settlement occurred. * @param receiptHash hash that proof the FIAT money transfer */ function notifyRedemptionSettlement(string memory redemptionTransactionHash, string memory receiptHash) public whenNotPaused { require (registry.isResponsibleForSettlement(msg.sender), "A liquida&#231;&#227;o s&#243; n&#227;o pode ser realizada pelo endere&#231;o que submeteu a transa&#231;&#227;o"); require (registry.isValidHash(receiptHash), "O hash do recibo &#233; inv&#225;lido"); emit BNDESTokenRedemptionSettlement(redemptionTransactionHash, receiptHash); } function registryLegalEntity(uint64 cnpj, uint64 idFinancialSupportAgreement, uint32 salic, string memory idProofHash) public whenNotPaused { registry.registryLegalEntity(cnpj, idFinancialSupportAgreement, salic, msg.sender, idProofHash); } /** * Changes the original link between CNPJ and Ethereum account. * The new link still needs to be validated by BNDES. * IMPORTANT: The BNDESTOKENs are transfered from the original to the new Ethereum address * @param cnpj Brazilian identifier to legal entities * @param idFinancialSupportAgreement contract number of financial contract with BNDES. It assumes 0 if it is a supplier. * @param salic contract number of financial contract with ANCINE. It assumes 0 if it is a supplier. * @param idProofHash The legal entities have to send BNDES a PDF where it assumes as responsible for an Ethereum account. * This PDF is signed with eCNPJ and send to BNDES. */ function changeAccountLegalEntity(uint64 cnpj, uint64 idFinancialSupportAgreement, uint32 salic, string memory idProofHash) public whenNotPaused { address oldAddr = registry.getBlockchainAccount(cnpj, idFinancialSupportAgreement); address newAddr = msg.sender; registry.changeAccountLegalEntity(cnpj, idFinancialSupportAgreement, salic, msg.sender, idProofHash); // Se h&#225; saldo no enderecoAntigo, precisa transferir if (balanceOf(oldAddr) > 0) { _transfer(oldAddr, newAddr, balanceOf(oldAddr)); } } //These methods may be necessary to solve incidents. function burn(address from, uint256 value, string memory description) public onlyOwner { _burn(from, value); emit BNDESManualIntervention(description); } //These methods may be necessary to solve incidents. function mint(address to, uint256 value, string memory description) public onlyOwner { _mint(to, value); emit BNDESManualIntervention(description); } function isOwner() public view returns (bool) { return registry.owner() == msg.sender; } //Unsupported methods - created to avoid call the lib functions by overriding them function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) { require(false, "Unsupported method - transferFrom"); } //Unsupported methods - created to avoid call the lib functions by overriding them function approve(address spender, uint256 value) public whenNotPaused returns (bool) { require(false, "Unsupported method - approve"); } //Unsupported methods - created to avoid call the lib functions by overriding them function increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) { require(false, "Unsupported method - increaseAllowance"); } //Unsupported methods - created to avoid call the lib functions by overriding them function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) { require(false, "Unsupported method - decreaseAllowance"); } }
Enable the legal entity to change the account rs account that can be changed./
function enableChangeAccount (address rs) public { require(isResponsibleForRegistryValidation(msg.sender), "Somente o respons&#225;vel pela valida&#231;&#227;o pode habilitar a troca de conta"); legalEntitiesChangeAccount[rs] = true; }
7,801,592