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/5/0x2E3dD5F1E9E3180a64E367B2aCD56B4004039590/sources/ParagonsDAOPlayerID.sol
|
Returns the Player data by id.
|
function getPlayerData(uint256 _tokenId) public view returns (PlayerData memory) {
if (!_exists(_tokenId)) revert NoPDP();
return _playerData[_tokenId];
}
| 1,876,920
|
./full_match/5/0xB23F0796e592A91467E5D42F3368Cd722E7f0251/sources/contracts/medrecords.sol
|
Retrieve patient count
|
function getPatientCount() public view returns(uint256) {
return patientCount;
}
| 11,630,163
|
// SPDX-License-Identifier: Apache-2.0
/*
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.6;
pragma experimental ABIEncoderV2;
import "@0x/contracts-erc20/contracts/src/v06/IEtherTokenV06.sol";
import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol";
import "../../fixins/FixinERC1155Spender.sol";
import "../../migrations/LibMigrate.sol";
import "../../storage/LibERC1155OrdersStorage.sol";
import "../interfaces/IFeature.sol";
import "../interfaces/IERC1155OrdersFeature.sol";
import "../libs/LibNFTOrder.sol";
import "../libs/LibSignature.sol";
import "./NFTOrders.sol";
/// @dev Feature for interacting with ERC1155 orders.
contract ERC1155OrdersFeature is
IFeature,
IERC1155OrdersFeature,
FixinERC1155Spender,
NFTOrders
{
using LibSafeMathV06 for uint256;
using LibSafeMathV06 for uint128;
using LibNFTOrder for LibNFTOrder.ERC1155Order;
using LibNFTOrder for LibNFTOrder.NFTOrder;
/// @dev Name of this feature.
string public constant override FEATURE_NAME = "ERC1155Orders";
/// @dev Version of this feature.
uint256 public immutable override FEATURE_VERSION = _encodeVersion(1, 0, 0);
/// @dev The magic return value indicating the success of a `onERC1155Received`.
bytes4 private constant ERC1155_RECEIVED_MAGIC_BYTES = this.onERC1155Received.selector;
constructor(address zeroExAddress, IEtherTokenV06 weth)
public
NFTOrders(zeroExAddress, weth)
{}
/// @dev Initialize and register this feature.
/// Should be delegatecalled by `Migrate.migrate()`.
/// @return success `LibMigrate.SUCCESS` on success.
function migrate()
external
returns (bytes4 success)
{
_registerFeatureFunction(this.sellERC1155.selector);
_registerFeatureFunction(this.buyERC1155.selector);
_registerFeatureFunction(this.cancelERC1155Order.selector);
_registerFeatureFunction(this.batchBuyERC1155s.selector);
_registerFeatureFunction(this.onERC1155Received.selector);
_registerFeatureFunction(this.preSignERC1155Order.selector);
_registerFeatureFunction(this.validateERC1155OrderSignature.selector);
_registerFeatureFunction(this.validateERC1155OrderProperties.selector);
_registerFeatureFunction(this.getERC1155OrderInfo.selector);
_registerFeatureFunction(this.getERC1155OrderHash.selector);
return LibMigrate.MIGRATE_SUCCESS;
}
/// @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 sellERC1155(
LibNFTOrder.ERC1155Order 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 buyERC1155(
LibNFTOrder.ERC1155Order memory sellOrder,
LibSignature.Signature memory signature,
uint128 erc1155BuyAmount,
bytes memory callbackData
)
public
override
payable
{
uint256 ethBalanceBefore = address(this).balance
.safeSub(msg.value);
_buyERC1155(
sellOrder,
signature,
BuyParams(
erc1155BuyAmount,
msg.value,
callbackData
)
);
uint256 ethBalanceAfter = address(this).balance;
// Cannot use pre-existing ETH balance
if (ethBalanceAfter < ethBalanceBefore) {
LibNFTOrdersRichErrors.OverspentEthError(
ethBalanceBefore - ethBalanceAfter + msg.value,
msg.value
).rrevert();
}
// Refund
_transferEth(msg.sender, ethBalanceAfter - ethBalanceBefore);
}
/// @dev Cancel a single ERC1155 order by its nonce. The caller
/// should be the maker of the order. Silently succeeds if
/// an order with the same nonce has already been filled or
/// cancelled.
/// @param orderNonce The order nonce.
function cancelERC1155Order(uint256 orderNonce)
public
override
{
// The bitvector is indexed by the lower 8 bits of the nonce.
uint256 flag = 1 << (orderNonce & 255);
// Update order cancellation bit vector to indicate that the order
// has been cancelled/filled by setting the designated bit to 1.
LibERC1155OrdersStorage.getStorage().orderCancellationByMaker
[msg.sender][uint248(orderNonce >> 8)] |= flag;
emit ERC1155OrderCancelled(msg.sender, orderNonce);
}
/// @dev Cancel multiple ERC1155 orders by their nonces. The caller
/// should be the maker of the orders. Silently succeeds if
/// an order with the same nonce has already been filled or
/// cancelled.
/// @param orderNonces The order nonces.
function batchCancelERC1155Orders(uint256[] calldata orderNonces)
external
override
{
for (uint256 i = 0; i < orderNonces.length; i++) {
cancelERC1155Order(orderNonces[i]);
}
}
/// @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 batchBuyERC1155s(
LibNFTOrder.ERC1155Order[] memory sellOrders,
LibSignature.Signature[] memory signatures,
uint128[] calldata erc1155FillAmounts,
bytes[] memory callbackData,
bool revertIfIncomplete
)
public
override
payable
returns (bool[] memory successes)
{
require(
sellOrders.length == signatures.length &&
sellOrders.length == erc1155FillAmounts.length &&
sellOrders.length == callbackData.length,
"ERC1155OrdersFeature::batchBuyERC1155s/ARRAY_LENGTH_MISMATCH"
);
successes = new bool[](sellOrders.length);
uint256 ethBalanceBefore = address(this).balance
.safeSub(msg.value);
if (revertIfIncomplete) {
for (uint256 i = 0; i < sellOrders.length; i++) {
// Will revert if _buyERC1155 reverts.
_buyERC1155(
sellOrders[i],
signatures[i],
BuyParams(
erc1155FillAmounts[i],
address(this).balance.safeSub(ethBalanceBefore), // Remaining ETH available
callbackData[i]
)
);
successes[i] = true;
}
} else {
for (uint256 i = 0; i < sellOrders.length; i++) {
// Delegatecall `_buyERC1155` to catch swallow reverts while
// preserving execution context.
// Note that `_buyERC1155` is a public function but should _not_
// be registered in the Exchange Proxy.
(successes[i], ) = _implementation.delegatecall(
abi.encodeWithSelector(
this._buyERC1155.selector,
sellOrders[i],
signatures[i],
BuyParams(
erc1155FillAmounts[i],
address(this).balance.safeSub(ethBalanceBefore), // Remaining ETH available
callbackData[i]
)
)
);
}
}
// Cannot use pre-existing ETH balance
uint256 ethBalanceAfter = address(this).balance;
if (ethBalanceAfter < ethBalanceBefore) {
LibNFTOrdersRichErrors.OverspentEthError(
msg.value + (ethBalanceBefore - ethBalanceAfter),
msg.value
).rrevert();
}
// Refund
_transferEth(msg.sender, ethBalanceAfter - ethBalanceBefore);
}
/// @dev Callback for the ERC1155 `safeTransferFrom` function.
/// This callback can be used to sell an ERC1155 asset if
/// a valid ERC1155 order, signature and `unwrapNativeToken`
/// are encoded in `data`. This allows takers to sell their
/// ERC1155 asset without first calling `setApprovalForAll`.
/// @param operator The address which called `safeTransferFrom`.
/// @param tokenId The ID of the asset being transferred.
/// @param value The amount being transferred.
/// @param data Additional data with no specified format. If a
/// valid ERC1155 order, signature and `unwrapNativeToken`
/// are encoded in `data`, this function will try to fill
/// the order using the received asset.
/// @return success The selector of this function (0xf23a6e61),
/// indicating that the callback succeeded.
function onERC1155Received(
address operator,
address /* from */,
uint256 tokenId,
uint256 value,
bytes calldata data
)
external
override
returns (bytes4 success)
{
// Decode the order, signature, and `unwrapNativeToken` from
// `data`. If `data` does not encode such parameters, this
// will throw.
(
LibNFTOrder.ERC1155Order memory buyOrder,
LibSignature.Signature memory signature,
bool unwrapNativeToken
) = abi.decode(
data,
(LibNFTOrder.ERC1155Order, LibSignature.Signature, bool)
);
// `onERC1155Received` is called by the ERC1155 token contract.
// Check that it matches the ERC1155 token in the order.
if (msg.sender != address(buyOrder.erc1155Token)) {
LibNFTOrdersRichErrors.ERC1155TokenMismatchError(
msg.sender,
address(buyOrder.erc1155Token)
).rrevert();
}
_sellERC1155(
buyOrder,
signature,
SellParams(
value.safeDowncastToUint128(),
tokenId,
unwrapNativeToken,
operator, // taker
address(this), // owner (we hold the NFT currently)
new bytes(0) // No taker callback
)
);
return ERC1155_RECEIVED_MAGIC_BYTES;
}
/// @dev Approves an ERC1155 order on-chain. After pre-signing
/// the order, the `PRESIGNED` signature type will become
/// valid for that order and signer.
/// @param order An ERC1155 order.
function preSignERC1155Order(LibNFTOrder.ERC1155Order memory order)
public
override
{
require(
order.maker == msg.sender,
"ERC1155OrdersFeature::preSignERC1155Order/MAKER_MISMATCH"
);
bytes32 orderHash = getERC1155OrderHash(order);
LibERC1155OrdersStorage.Storage storage stor =
LibERC1155OrdersStorage.getStorage();
// Set `preSigned` to true on the order state variable
// to indicate that the order has been pre-signed.
stor.orderState[orderHash].preSigned = true;
emit ERC1155OrderPreSigned(
order.direction,
order.maker,
order.taker,
order.expiry,
order.nonce,
order.erc20Token,
order.erc20TokenAmount,
order.fees,
order.erc1155Token,
order.erc1155TokenId,
order.erc1155TokenProperties,
order.erc1155TokenAmount
);
}
// Core settlement logic for selling an ERC1155 asset.
// Used by `sellERC1155` and `onERC1155Received`.
function _sellERC1155(
LibNFTOrder.ERC1155Order memory buyOrder,
LibSignature.Signature memory signature,
SellParams memory params
)
private
{
uint256 erc20FillAmount = _sellNFT(
buyOrder.asNFTOrder(),
signature,
params
);
emit ERC1155OrderFilled(
buyOrder.direction,
buyOrder.maker,
params.taker,
buyOrder.nonce,
buyOrder.erc20Token,
erc20FillAmount,
buyOrder.erc1155Token,
params.tokenId,
params.sellAmount,
address(0)
);
}
// Core settlement logic for buying an ERC1155 asset.
// Used by `buyERC1155` and `batchBuyERC1155s`.
function _buyERC1155(
LibNFTOrder.ERC1155Order memory sellOrder,
LibSignature.Signature memory signature,
BuyParams memory params
)
public
payable
{
uint256 erc20FillAmount = _buyNFT(
sellOrder.asNFTOrder(),
signature,
params
);
emit ERC1155OrderFilled(
sellOrder.direction,
sellOrder.maker,
msg.sender,
sellOrder.nonce,
sellOrder.erc20Token,
erc20FillAmount,
sellOrder.erc1155Token,
sellOrder.erc1155TokenId,
params.buyAmount,
address(0)
);
}
/// @dev Checks whether the given signature is valid for the
/// the given ERC1155 order. Reverts if not.
/// @param order The ERC1155 order.
/// @param signature The signature to validate.
function validateERC1155OrderSignature(
LibNFTOrder.ERC1155Order memory order,
LibSignature.Signature memory signature
)
public
override
view
{
bytes32 orderHash = getERC1155OrderHash(order);
_validateOrderSignature(orderHash, signature, order.maker);
}
/// @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) {
// Check if order hash has been pre-signed by the maker.
bool isPreSigned = LibERC1155OrdersStorage.getStorage()
.orderState[orderHash].preSigned;
if (!isPreSigned) {
LibNFTOrdersRichErrors.InvalidSignerError(maker, address(0)).rrevert();
}
} else {
address signer = LibSignature.getSignerOfHash(orderHash, signature);
if (signer != maker) {
LibNFTOrdersRichErrors.InvalidSignerError(maker, signer).rrevert();
}
}
}
/// @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
override
{
_transferERC1155AssetFrom(IERC1155Token(token), from, to, tokenId, amount);
}
/// @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.NFTOrder 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
assert(filledAmount + fillAmount > filledAmount);
stor.orderState[orderHash].filledAmount = filledAmount + fillAmount;
}
/// @dev If the given order is buying an ERC1155 asset, checks
/// whether or not the given token ID satisfies the required
/// properties specified in the order. If the order does not
/// specify any properties, this function instead checks
/// whether the given token ID matches the ID in the order.
/// Reverts if any checks fail, or if the order is selling
/// an ERC1155 asset.
/// @param order The ERC1155 order.
/// @param erc1155TokenId The ID of the ERC1155 asset.
function validateERC1155OrderProperties(
LibNFTOrder.ERC1155Order memory order,
uint256 erc1155TokenId
)
public
override
view
{
_validateOrderProperties(
order.asNFTOrder(),
erc1155TokenId
);
}
/// @dev Get the order info for an ERC1155 order.
/// @param order The ERC1155 order.
/// @return orderInfo Info about the order.
function getERC1155OrderInfo(LibNFTOrder.ERC1155Order memory order)
public
override
view
returns (LibNFTOrder.OrderInfo memory orderInfo)
{
orderInfo.orderAmount = order.erc1155TokenAmount;
orderInfo.orderHash = getERC1155OrderHash(order);
// Only buy orders with `erc1155TokenId` == 0 can be property
// orders.
if (order.erc1155TokenProperties.length > 0 &&
(order.direction != LibNFTOrder.TradeDirection.BUY_NFT ||
order.erc1155TokenId != 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 (order.direction == LibNFTOrder.TradeDirection.BUY_NFT &&
address(order.erc20Token) == NATIVE_TOKEN_ADDRESS)
{
orderInfo.status = LibNFTOrder.OrderStatus.INVALID;
return orderInfo;
}
// Check for expiry.
if (order.expiry <= 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
.safeSub128(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;
}
/// @dev Get the order info for an NFT order.
/// @param order The NFT order.
/// @return orderInfo Info about the order.
function _getOrderInfo(LibNFTOrder.NFTOrder memory order)
internal
override
view
returns (LibNFTOrder.OrderInfo memory orderInfo)
{
return getERC1155OrderInfo(order.asERC1155Order());
}
/// @dev Get the EIP-712 hash of an ERC1155 order.
/// @param order The ERC1155 order.
/// @return orderHash The order hash.
function getERC1155OrderHash(LibNFTOrder.ERC1155Order memory order)
public
override
view
returns (bytes32 orderHash)
{
return _getEIP712Hash(LibNFTOrder.getERC1155OrderStructHash(order));
}
}
|
Sells an ERC1155 asset to fill the given order. buyOrder The ERC1155 buy order. signature The order signature from the maker. 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. erc1155SellAmount The amount of the ERC1155 asset to sell. 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. 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 sellERC1155(
LibNFTOrder.ERC1155Order memory buyOrder,
LibSignature.Signature memory signature,
uint256 erc1155TokenId,
uint128 erc1155SellAmount,
bool unwrapNativeToken,
bytes memory callbackData
)
public
override
{
_sellERC1155(
buyOrder,
signature,
SellParams(
erc1155SellAmount,
erc1155TokenId,
unwrapNativeToken,
callbackData
)
);
}
| 13,001,148
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import '@openzeppelin/contracts/math/Math.sol';
import './interfaces/IOracle.sol';
import './interfaces/IBoardroom.sol';
import './interfaces/IBasisAsset.sol';
import './interfaces/ISimpleERCFund.sol';
import './interfaces/ITreasury.sol';
import './interfaces/IRewardPool.sol';
import './lib/FixedPoint.sol';
import './utils/Epoch.sol';
import './lib/Safe112.sol';
import './lib/AdminRole.sol';
import './utils/ContractGuard.sol';
/**
* @title GoCash Cash Treasury合约
* 实现功能:
* 1.通过预言机获取GOC价格,根据GOC价格不同,用GOC购买GOB,或赎回GOB获得GOC
* 2.根据GOC价格不同,增发GOC,并把新增发的GOC分配给fund treasury shareBoardroom
* 注解:TimBear 20210107
* @notice Monetary policy logic to adjust supplies of basis cash assets
* @author Summer Smith & Rick Sanchez
*/
contract Treasury is ContractGuard, Epoch {
using FixedPoint for *;
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
using Safe112 for uint112;
/* ========== STATE VARIABLES ========== */
// ========== FLAGS 标记
/// @notice 已迁移
bool public migrated = false;
/// @notice 已初始化
bool public initialized = false;
// ========== CORE 核心
/// @notice 开发者基金
address public fund;
/// @notice GoCash Cash地址
address public cash;
/// @notice GoCash Bond地址
address public bond;
/// @notice GoCash Token地址
address public share;
/// @notice share质押董事会合约地址
address public shareBoardroom;
/// @notice lp质押董事会合约地址
address public lpBoardroom;
/// @notice bond奖励池地址
address public bondRewardPool;
/// @notice 预言机地址
address public oracle;
// ========== PARAMS 参数
/// @notice cash基准价格
uint256 public cashPriceOne;
/// @notice oracle基准价格
uint256 public oraclePriceOne;
/// @notice 价格天花板
uint256 public cashPriceCeiling;
/// @notice cash价格下限
uint256 public cashPriceFloor;
/// @notice cash价格bond奖励
uint256 public cashPriceBondReward;
/// @notice bond基准价格 1
uint256 public bondPrice;
/// @notice 最低bond价格 0.5
uint256 public minBondPrice;
/// @notice bondPriceDelta 0.02
uint256 public bondPriceDelta;
/// @dev 累计铸币税
uint256 private accumulatedSeigniorage = 0;
/// @notice 开发者基金分配比例 2%
uint256 public fundAllocationRate = 2; // %
/// @dev 累计债务
uint256 private accumulatedDebt = 0;
/// @notice 最大通胀率
uint256 public maxInflationRate = 10;
/// @notice 债务增加比率
uint256 public debtAddRate = 2;
/// @notice 最大债务比率
uint256 public maxDebtRate = 20;
// ========== MIGRATE
/// @dev 旧国库合约地址
address public legacyTreasury;
/* ========== CONSTRUCTOR ========== */
/**
* @dev 构造函数
* @param _cash GoCash Cash地址
* @param _bond GoCash Bond地址
* @param _share GoCash Token地址
* @param _oracle Bond预言机地址
* @param _shareBoardroom share质押董事会合约地址
* @param _lpBoardroom lp质押董事会合约地址
* @param _bondRewardPool bond奖励池地址
* @param _fund 开发者基金
* @param _startTime 开始时间
*/
constructor(
address _cash,
address _bond,
address _share,
address _oracle,
address _shareBoardroom,
address _lpBoardroom,
address _bondRewardPool,
address _fund,
uint256 _startTime
) public Epoch(12 hours, _startTime, 0) {
cash = _cash;
bond = _bond;
share = _share;
oracle = _oracle;
shareBoardroom = _shareBoardroom;
lpBoardroom = _lpBoardroom;
bondRewardPool = _bondRewardPool;
fund = _fund;
// Cash基准价格为1
cashPriceOne = 10**18;
// oracle基准价格,防止有些token精度不是18
oraclePriceOne = 10**18;
// cash价格天花板为1.02 102 * 10**18 / 10**2 = 1.05
cashPriceCeiling = uint256(102).mul(cashPriceOne).div(10**2);
// band亏损下限 1000 * 10**18
// bondDepletionFloor = uint256(1000).mul(cashPriceOne);
// cash价格下限 98 * 10**18 / 10**2 = 0.98
cashPriceFloor = uint256(98).mul(cashPriceOne).div(10**2);
// cash价格bond奖励 95 * 10**18 / 10**2 = 0.98
cashPriceBondReward = uint256(95).mul(cashPriceOne).div(10**2);
// bond基准价格
bondPrice = 10**18;
// 最低bond基准价格 0.5
minBondPrice = 5 * 10**17;
// bond基准价Delta 0.02
bondPriceDelta = 2 * 10**16;
}
/* =================== Modifier =================== */
/// @notice 修饰符:需要完成Migration,即完成更换Admin为本合约
modifier checkMigration {
require(!migrated, 'Treasury: migrated');
_;
}
/// @notice 修饰符:合约cash bond share boardroom的Admin必须为本合约
modifier checkAdmin {
require(
AdminRole(cash).isAdmin(address(this)) &&
AdminRole(bond).isAdmin(address(this)) &&
AdminRole(share).isAdmin(address(this)) &&
AdminRole(bondRewardPool).isAdmin(address(this)) &&
AdminRole(lpBoardroom).isAdmin(address(this)) &&
AdminRole(shareBoardroom).isAdmin(address(this)),
'Treasury: need more permission'
);
_;
}
/* ========== VIEW FUNCTIONS ========== */
//一些只读方法
/**
* @dev 返回累计铸币税,预算?
* @return 预算
*/
function getReserve() public view returns (uint256) {
return accumulatedSeigniorage;
}
// debt
/**
* @dev 返回债务
* @return 累计债务
*/
function getDebt() public view returns (uint256) {
return accumulatedDebt;
}
// oracle
/**
* @dev 返回预言机中Cash价格
* @return 价格
*/
function getOraclePrice() public view returns (uint256) {
// 通过预言机取Cash价格
return _getCashPrice(oracle);
}
/**
* @dev 根据不同的场景选择不同的预言机进行喂价
* @param _oracle 预言机地址
* @return 价格
*/
function _getCashPrice(address _oracle) internal view returns (uint256) {
try IOracle(_oracle).consult(cash, 1e18) returns (uint256 price) {
// 返回价格 * 1e18 / 1e18 防止有些token精度不是18
return price.mul(cashPriceOne).div(oraclePriceOne);
} catch {
revert('Treasury: failed to consult cash price from the oracle');
}
}
/* ========== GOVERNANCE ========== */
/**
* @dev 设置旧国库合约地址
*/
function setLegacyTreasury(address _legacyTreasury) public onlyAdmin {
legacyTreasury = _legacyTreasury;
}
/**
* @dev 合约初始化
* @param _accumulatedSeigniorage 累计铸币税
* @param _accumulatedDebt 累计债务
* @param _bondPrice bond基准价格
* @param _oraclePriceOne 预言机基准价格
*/
function initialize(
uint256 _accumulatedSeigniorage,
uint256 _accumulatedDebt,
uint256 _bondPrice,
uint256 _oraclePriceOne
) public {
// 确认合约未经初始化
require(!initialized, 'Treasury: initialized');
// 确认必须由旧国库合约调用
require(msg.sender == legacyTreasury, 'Treasury: on legacy treasury');
// 变量赋值
accumulatedSeigniorage = _accumulatedSeigniorage;
accumulatedDebt = _accumulatedDebt;
bondPrice = _bondPrice;
oraclePriceOne = _oraclePriceOne;
initialized = true;
//触发合约初始化事件
emit Initialized(msg.sender, block.number);
}
/**
* @dev 迁移国库合约到新合约
* @param target 目标地址
*/
function migrate(address target) public onlyAdmin checkAdmin {
require(!migrated, 'Treasury: migrated');
// cash
//更换GOC合约的Admin,Owner为target,并把原合约的GOC发送至target
AdminRole(cash).addAdmin(target);
AdminRole(cash).renounceAdmin();
IERC20(cash).transfer(target, IERC20(cash).balanceOf(address(this)));
// bond
//更换GOB合约的Admin,Owner为target,并把原合约的GOB发送至target
AdminRole(bond).addAdmin(target);
AdminRole(bond).renounceAdmin();
IERC20(bond).transfer(target, IERC20(bond).balanceOf(address(this)));
// share
//更换GOT合约的Admin,Owner为target,并把原合约的GOT发送至target
AdminRole(share).addAdmin(target);
AdminRole(share).renounceAdmin();
IERC20(share).transfer(target, IERC20(share).balanceOf(address(this)));
// Boardroom
//更换boardroom合约的Admin
AdminRole(bondRewardPool).addAdmin(target);
AdminRole(bondRewardPool).renounceAdmin();
AdminRole(shareBoardroom).addAdmin(target);
AdminRole(shareBoardroom).renounceAdmin();
AdminRole(lpBoardroom).addAdmin(target);
AdminRole(lpBoardroom).renounceAdmin();
// params
ITreasury(target).initialize(
accumulatedSeigniorage,
accumulatedDebt,
bondPrice,
oraclePriceOne
);
migrated = true;
//触发所有权转移事件
emit Migration(target);
}
/**
* @dev 设置开发者基金地址
* @param newFund 新开发者基金地址
*/
function setFund(address newFund) public onlyAdmin {
//设置开发贡献者奖金池
fund = newFund;
//触发更换开发贡献者奖金池事件
emit ContributionPoolChanged(msg.sender, newFund);
}
/**
* @dev 设置开发者奖励比例
* @param rate 新比例
*/
function setFundAllocationRate(uint256 rate) public onlyAdmin {
//设置开发贡献者奖金比例
fundAllocationRate = rate;
//触发更换开发贡献者奖金比例事件
emit ContributionPoolRateChanged(msg.sender, rate);
}
/**
* @dev 设置预言机基准价格1
* @param _oraclePriceOne 新基准价格1
*/
function setOraclePriceOne(uint256 _oraclePriceOne) public onlyAdmin {
oraclePriceOne = _oraclePriceOne;
//触发事件
emit SetOraclePriceOne(oraclePriceOne);
}
/**
* @dev 设置最大通胀比例
* @param rate 最大通胀比例
*/
function setMaxInflationRate(uint256 rate) public onlyAdmin {
maxInflationRate = rate;
emit MaxInflationRateChanged(msg.sender, rate);
}
/**
* @dev 设置债务增加比率
* @param rate 债务增加比率
*/
function setDebtAddRate(uint256 rate) public onlyAdmin {
debtAddRate = rate;
emit DebtAddRateChanged(msg.sender, rate);
}
/**
* @dev 设置最大债务比例
* @param rate 最大债务比例
*/
function setMaxDebtRate(uint256 rate) public onlyAdmin {
maxDebtRate = rate;
emit MaxDebtRateChanged(msg.sender, rate);
}
/* ========== MUTABLE FUNCTIONS ========== */
/**
* @dev 预言机更新GOC价格
*/
function _updateCashPrice() internal {
try IOracle(oracle).update() {} catch {}
}
/**
* @dev 当GOC价格低于1时,使用GOC购买GOB
* @param amount 购买数额
*/
function buyBonds(uint256 amount)
external
onlyOneBlock // 同一区块只能调用一次合约
checkMigration // 检查是否迁移
checkStartTime // 检查开始时间
checkAdmin // 检查铸币权限
{
//通过预言机获取GOC价格
uint256 cashPrice = _getCashPrice(oracle);
//需要GOC价格小于1
require(
cashPrice < cashPriceOne, // price < $1
'Treasury: cashPrice not eligible for bond purchase'
);
// 销毁数量 = 最小值(购买数量,累计债务 * bond基准价 / 1e18)
uint256 burnAmount = Math.min(
amount,
accumulatedDebt.mul(bondPrice).div(1e18)
);
// 确认销毁数量 > 0
require(
burnAmount > 0,
'Treasury: cannot purchase bonds with zero amount'
);
// 铸造bond数量 = 销毁数量 * 1e18 / bond基准价
uint256 mintBondAmount = burnAmount.mul(1e18).div(bondPrice);
//销毁用户持有的amount数量的GOC
IBasisAsset(cash).burnFrom(msg.sender, burnAmount);
//铸造GOB: 铸造bond数量
IBasisAsset(bond).mint(msg.sender, mintBondAmount);
// 累计债务 = 累计债务 - 铸造bond数量
accumulatedDebt = accumulatedDebt.sub(mintBondAmount);
//更新GOC价格
_updateCashPrice();
//触发购买GOB事件
emit BoughtBonds(msg.sender, amount);
}
/**
* @dev 当GOC价格大于1.05时,使用GOB换回GOC
* @param amount 赎回数额
*/
function redeemBonds(uint256 amount)
external
onlyOneBlock // 同一区块只能调用一次合约
checkMigration // 检查是否迁移
checkStartTime // 检查开始时间
checkAdmin // 检查铸币权限
{
//通过预言机获取GOC价格
uint256 cashPrice = _getCashPrice(oracle);
// 确认GOC价格大于cashPriceCeiling,即1.02
require(
cashPrice > cashPriceCeiling, // price > $1.02
'Treasury: cashPrice not eligible for bond purchase'
);
// 赎回数量 = 最小值(GOC的累计储备量,赎回数额)
uint256 redeemAmount = Math.min(accumulatedSeigniorage, amount);
// 确认赎回数量>0
require(
redeemAmount > 0,
'Treasury: cannot redeem bonds with zero amount'
);
// 确认当前合约的GOC数量大于要赎回的GOB数量
require(
IERC20(cash).balanceOf(address(this)) >= redeemAmount,
'Treasury: treasury has no more budget'
);
// GOC的累计储备量 = 累计储备量 - 赎回数量,即1GOB换取1GOC
accumulatedSeigniorage = accumulatedSeigniorage.sub(redeemAmount);
// 销毁用户持有的GOB
IBasisAsset(bond).burnFrom(msg.sender, redeemAmount);
// 将当前合约的GOC发送给用户
IERC20(cash).safeTransfer(msg.sender, redeemAmount);
// 更新GOC价格
_updateCashPrice();
// 触发赎回GOB事件
emit RedeemedBonds(msg.sender, amount);
}
/**
* @dev 增发GOC,并分配GOC
*/
function allocateSeigniorage()
external
onlyOneBlock
checkMigration
checkStartTime
checkEpoch
checkAdmin
{
//更新GOC价格
_updateCashPrice();
//通过预言机获取GOC价格
uint256 cashPrice = _getCashPrice(oracle);
// circulating supply
// 流通的GOC数量 = GOC总供应量 - GOC累计储备量
uint256 cashSupply = IERC20(cash).totalSupply().sub(
accumulatedSeigniorage
);
//判断当GOC价格小于等于cashPriceBondReward即小于0.95
if (cashPrice <= cashPriceBondReward) {
// 奖励数量 = bond的1%
uint256 rewardAmount = IERC20(bond).totalSupply().div(100);
// bond铸造奖励,发给bond奖励池
IBasisAsset(bond).mint(bondRewardPool, rewardAmount);
// bond奖励池通知奖励数量
IRewardPool(bondRewardPool).notifyRewardAmount(rewardAmount);
// 触发奖励事件
emit BondReward(block.timestamp, rewardAmount);
}
// add debt
//判断当GOC价格小于等于0.98(cash价格下限)
if (cashPrice <= cashPriceFloor) {
// 增加债务 = 流通的GOC数量 * 2%(债务增加比率)
uint256 addDebt = cashSupply.mul(debtAddRate).div(100);
// 最大债务 = 流通的GOC数量 * 20%(最大债务比率)
uint256 maxDebt = cashSupply.mul(maxDebtRate).div(100);
// 累计债务 = 累计债务 + 增加的债务
accumulatedDebt = accumulatedDebt.add(addDebt);
// 如果累计债务 > 最大债务
if (accumulatedDebt > maxDebt) {
// 累计债务 = 最大债务 20%
accumulatedDebt = maxDebt;
}
// bond基准价 = bond基准价 - 0.02(bond基准价Delta)
bondPrice = bondPrice.sub(bondPriceDelta);
// 如果 bond基准价 <= 0.5(最低bond基准价格)
if (bondPrice <= minBondPrice) {
// bond基准价 = 0.5(最低bond基准价格)
bondPrice = minBondPrice;
}
}
// clear the debt
// 如果GOC价格>0.98(cash价格下限)
if (cashPrice > cashPriceFloor) {
// 累计债务清零
accumulatedDebt = 0;
// bond价格=1
bondPrice = 10**18;
}
//判断当GOC价格小于等于cashPriceCeiling即小于1.05则返回,不增发GOC
if (cashPrice <= cashPriceCeiling) {
return; // just advance epoch instead revert
}
//增发比例 = GOC价格 - 1 例:0.8
uint256 percentage = cashPrice.sub(cashPriceOne);
//新铸造的GOC数量 = 流通的GOC数量 * 增发比例
uint256 seigniorage = cashSupply.mul(percentage).div(1e18);
// 最大铸造的GOC数量 = 流通的GOC数量 * 10%(最大通胀比例)
uint256 maxSeigniorage = cashSupply.mul(maxInflationRate).div(100);
// 如果新铸造的GOC数量 > 最大铸造的GOC数量
if (seigniorage > maxSeigniorage) {
// 新铸造的GOC数量 = 最大铸造的GOC数量
seigniorage = maxSeigniorage;
}
//新铸造GOC,并发送至本合约
IBasisAsset(cash).mint(address(this), seigniorage);
// ======================== BIP-3
// 开发者基金储备 = 新铸造的GOC数量 * fundAllocationRate / 100 = 新铸造的GOC数量 * 2%
uint256 fundReserve = seigniorage.mul(fundAllocationRate).div(100);
if (fundReserve > 0) {
// 当前合约批准fund地址,开发者准备金数额
IERC20(cash).safeApprove(fund, fundReserve);
// 调用fund合约的存款方法存入开发者准备金
ISimpleERCFund(fund).deposit(
cash,
fundReserve,
'Treasury: Seigniorage Allocation'
);
//触发GOC已发放至开发贡献池事件
emit ContributionPoolFunded(now, fundReserve);
}
//新铸造的GOC数量 = 新铸造的GOC数量 - 开发者基金储备
seigniorage = seigniorage.sub(fundReserve);
// ======================== BIP-4
//新增国库储备 = min(新铸造的GOC数量 / 2, GOB总供应量-累计GOC储备量)
//即新铸造的GOC要先预留给GOB,剩下的才能分配给Boardroom
uint256 treasuryReserve = Math.min(
seigniorage.div(2), // 只有50%的通胀
IERC20(bond).totalSupply().sub(accumulatedSeigniorage)
);
// 如果 新增国库储备 > 0
if (treasuryReserve > 0) {
//累计GOC储备量 = 累计GOC储备量 + 新增国库储备量
accumulatedSeigniorage = accumulatedSeigniorage.add(
treasuryReserve
);
//触发已发放国库储备事件
emit TreasuryFunded(now, treasuryReserve);
}
// shareBoardroom
//董事会GOC新增储备量 = 新铸造的GOC - 新增国库储备量
uint256 boardroomReserve = seigniorage.sub(treasuryReserve);
if (boardroomReserve > 0) {
// share董事会分到60%
uint256 shareBoardroomReserve = boardroomReserve.mul(6).div(10);
// lp董事会分到40%
uint256 lpBoardroomReserve = boardroomReserve.sub(shareBoardroomReserve);
// 批准国库合约储备量数额
IERC20(cash).safeApprove(shareBoardroom, shareBoardroomReserve);
//调用Boardroom合约的allocateSeigniorage方法,将GOC存入董事会
IBoardroom(shareBoardroom).allocateSeigniorage(shareBoardroomReserve);
// 批准国库合约储备量数额
IERC20(cash).safeApprove(lpBoardroom, lpBoardroomReserve);
//调用Boardroom合约的allocateSeigniorage方法,将GOC存入董事会
IBoardroom(lpBoardroom).allocateSeigniorage(lpBoardroomReserve);
//触发已发放资金至董事会事件
emit BoardroomFunded(now, boardroomReserve);
}
}
// GOV
event Initialized(address indexed executor, uint256 at);
event Migration(address indexed target);
event ContributionPoolChanged(address indexed operator, address newFund);
event ContributionPoolRateChanged(
address indexed operator,
uint256 newRate
);
event MaxInflationRateChanged(address indexed operator, uint256 newRate);
event DebtAddRateChanged(address indexed operator, uint256 newRate);
event MaxDebtRateChanged(address indexed operator, uint256 newRate);
// CORE
event RedeemedBonds(address indexed from, uint256 amount);
event BoughtBonds(address indexed from, uint256 amount);
event TreasuryFunded(uint256 timestamp, uint256 seigniorage);
event BoardroomFunded(uint256 timestamp, uint256 seigniorage);
event ContributionPoolFunded(uint256 timestamp, uint256 seigniorage);
event SetOraclePriceOne(uint256 cashPriceOne);
event BondReward(uint256 timestamp, uint256 seigniorage);
}
|
迁移国库合约到新合约 target 目标地址/ cash更换GOC合约的Admin,Owner为target,并把原合约的GOC发送至target bond更换GOB合约的Admin,Owner为target,并把原合约的GOB发送至target share更换GOT合约的Admin,Owner为target,并把原合约的GOT发送至target Boardroom更换boardroom合约的Admin params触发所有权转移事件
|
function migrate(address target) public onlyAdmin checkAdmin {
require(!migrated, 'Treasury: migrated');
AdminRole(cash).addAdmin(target);
AdminRole(cash).renounceAdmin();
IERC20(cash).transfer(target, IERC20(cash).balanceOf(address(this)));
AdminRole(bond).addAdmin(target);
AdminRole(bond).renounceAdmin();
IERC20(bond).transfer(target, IERC20(bond).balanceOf(address(this)));
AdminRole(share).addAdmin(target);
AdminRole(share).renounceAdmin();
IERC20(share).transfer(target, IERC20(share).balanceOf(address(this)));
AdminRole(bondRewardPool).addAdmin(target);
AdminRole(bondRewardPool).renounceAdmin();
AdminRole(shareBoardroom).addAdmin(target);
AdminRole(shareBoardroom).renounceAdmin();
AdminRole(lpBoardroom).addAdmin(target);
AdminRole(lpBoardroom).renounceAdmin();
ITreasury(target).initialize(
accumulatedSeigniorage,
accumulatedDebt,
bondPrice,
oraclePriceOne
);
migrated = true;
emit Migration(target);
}
| 6,464,094
|
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.4;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "../interface/IKeeperWhitelist.sol";
import "../libraries/Utils.sol";
contract KeeperWhitelist is Initializable, OwnableUpgradeable, IKeeperWhitelist {
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
using Utils for EnumerableSetUpgradeable.AddressSet;
EnumerableSetUpgradeable.AddressSet internal _keepers;
event AddKeeperToWhitelist(address indexed keeper);
event RemoveKeeperFromWhitelist(address indexed keeper);
/**
* @notice Add an address to keeper whitelist.
*/
function addKeeper(address keeper) external virtual override onlyOwner {
require(keeper != address(0), "account is zero-address");
require(!isKeeper(keeper), "keeper is already in the whitelist");
bool success = _keepers.add(keeper);
require(success, "fail to add keeper");
emit AddKeeperToWhitelist(keeper);
}
/**
* @notice Remove an address from keeper whitelist.
*/
function removeKeeper(address keeper) external virtual override onlyOwner {
require(keeper != address(0), "account is zero-address");
require(isKeeper(keeper), "keeper is not in the whitelist");
bool success = _keepers.remove(keeper);
require(success, "fail to remove keeper");
emit RemoveKeeperFromWhitelist(keeper);
}
/**
* @notice Check if an address is in keeper whitelist.
*/
function isKeeper(address keeper) public view virtual override returns (bool) {
return _keepers.contains(keeper);
}
/**
* @notice Get count of current keepers.
* @return Number of keepers.
*/
function getKeeperCount() public view returns (uint256) {
return _keepers.length();
}
/**
* @notice List all local keepers.
* @param begin The begin index of keeper to retrieve.
* @param end The end index of keeper, exclusive.
* @return result An array of keeper addresses.
*/
function listKeepers(uint256 begin, uint256 end)
public
view
virtual
returns (address[] memory)
{
return _keepers.toArray(begin, end);
}
}
|
List all local keepers. begin The begin index of keeper to retrieve. end The end index of keeper, exclusive. return result An array of keeper addresses./
|
function listKeepers(uint256 begin, uint256 end)
public
view
virtual
returns (address[] memory)
{
return _keepers.toArray(begin, end);
}
| 6,439,537
|
pragma solidity ^0.5.16;
contract FlightCompensation{
/*
* Compensation amounts
*/
uint256 small3 = 125;
uint256 small6 = 250;
uint256 small9 = 500;
uint256 large3 = 400;
uint256 large6 = 700;
uint256 large9 = 1000;
uint256 private availableFunds; //variable storing the contract funds
/*
* Posible statuses for the claim:
* 0: ongoing
* 1: flight landed before maxArrivalTime0
* 2: flight landed after maxArrivalTime0 but before maxArrivalTime1
* 3: flight landed after maxArrivalTime1 but before maxArrivalTime2
* 4: flight landed after maxArrivalTime2
* 5: flight cancelled by the passenger
* 6: flight cancelled by the airline
*/
struct Claim{ //all information related to a passenger claim
uint256 ID; //ID identifying the claim/passenger
uint8 airlineType; //Possible airline types: 0: small airline, 1: large airline
uint256 maxArrivalTime0; //Original Arrival time + 3 hours
uint256 maxArrivalTime1; //Original Arrival time + 6 hours
uint256 maxArrivalTime2; //Original Arrival time + 9 hours
uint8 status; //status of the flight
uint256 compensation; //amount owed to the passenger: $0-$1000
address payable compensationAddress; //address to which we will send the compensation
}
event ClaimCreation( //event sent when a new claim is added to the smart contract
uint256 ID, //ID identifying the claim/passenger
uint8 airlineType, //Possible airline types: 0: small airline, 1: large airline
bytes32 flightID // <carrier_code><flight_number>.<timestamp_in_sec_of_departure_date>
);
event ClaimResolve( //event sent when the claim is resolved
uint256 ID, //ID identifying the claim/passenger
bytes32 flightID, // <carrier_code><flight_number>.<timestamp_in_sec_of_departure_date>
uint8 status, //status of the flight
uint256 compensation //amount owed to the passenger: $0-$1000
);
event CompensationPaid( //event sent when the claim's determined compensation has been payed to passenger
uint256 ID, //ID identifying the claim/passenger
uint256 compensation, //confirmed amount sent to the passenger's account in WEI
address recipient //passenger's address
);
event CompensationError( //event sent when there is an error in sending the compensation to the passenger
uint256 ID, //ID identifying the claim/passenger
uint256 compensation, //confirmed amount sent to the passenger's account in WEI
address recipient, //passenger's address
bytes32 errorMessage //error message
);
address payable creator; // address of the creator of the contract
// All the insurances handled by this smart contract are contained in this mapping
// key: a string containing the flight number and the timestamp separated by a dot
// value: an array of insurance contracts for this flight
mapping (bytes32 => Claim[]) claimList;
/**
* @dev This modifier checks that only the creator of the contract can call this smart contract
*/
modifier onlyIfCreator {
if (msg.sender == creator) _;
}
modifier enoughFunds(uint256 compensation) {
require(availableFunds >= compensation/150, "Not enough funds in contract to pay compensation");
_;
}
/**
* @dev Constructor
*/
constructor () public {
creator = msg.sender;
}
function addNewClaim(
uint256 ID,
bytes32 flightID,
uint8 airlineType,
uint256 maxArrivalTime0,
uint256 maxArrivalTime1,
uint256 maxArrivalTime2,
address payable compensationAddress
)
external onlyIfCreator {
Claim memory claimToAdd;
claimToAdd.ID = ID;
claimToAdd.airlineType = airlineType;
claimToAdd.maxArrivalTime0 = maxArrivalTime0;
claimToAdd.maxArrivalTime1 = maxArrivalTime1;
claimToAdd.maxArrivalTime2 = maxArrivalTime2;
claimToAdd.compensationAddress = compensationAddress;
claimToAdd.status = 0; //when we create a claim, it is ongoing -> code:0
claimToAdd.compensation = 0; //when we create a claim, initial compensation is 0
claimList[flightID].push(claimToAdd);
emit ClaimCreation(ID, airlineType, flightID);
}
/*
* @dev Update the status of a flight
* @param flightId <carrier_code><flight_number>.<timestamp_in_sec_of_departure_date>
* @param actualArrivalTime The actual arrival time of the flight (timestamp in sec)
*/
function updateFlightStatus(
bytes32 flightID,
uint256 actualArrivalTime
)
external onlyIfCreator {
//default is that the flight landed on time, we hope!
uint8 updatedStatus = 1;
//for all claims in a flight, do this...
for (uint i = 0; i < claimList[flightID].length; i++) {
//going through only the ongoing claims
if (claimList[flightID][i].status == 0) {
if (actualArrivalTime > claimList[flightID][i].maxArrivalTime2){
updatedStatus = 4;
if (claimList[flightID][i].airlineType == 0){
claimList[flightID][i].compensation = small9;
}
else {
claimList[flightID][i].compensation = large9;
}
}
else if (actualArrivalTime > claimList[flightID][i].maxArrivalTime1){
updatedStatus = 3;
if (claimList[flightID][i].airlineType == 0){
claimList[flightID][i].compensation = small6;
}
else {
claimList[flightID][i].compensation = large6;
}
}
else if (actualArrivalTime > claimList[flightID][i].maxArrivalTime0){
updatedStatus = 2;
if (claimList[flightID][i].airlineType == 0){
claimList[flightID][i].compensation = small3;
}
else {
claimList[flightID][i].compensation = large3;
}
}
// update the status of the claim
claimList[flightID][i].status = updatedStatus;
emit ClaimResolve(
claimList[flightID][i].ID,
flightID,
updatedStatus,
claimList[flightID][i].compensation
);
compensateIfEnoughFunds(claimList[flightID][i]);
}
}
}
function getClaimsCount(bytes32 flightID) public view onlyIfCreator returns (uint) {
return claimList[flightID].length;
}
function getClaim(bytes32 flightID, uint i) public view onlyIfCreator returns (
uint256, uint8, uint256, uint256, uint256, uint8, uint256, address payable) {
Claim memory claim = claimList[flightID][i];
return (claim.ID, claim.airlineType, claim.maxArrivalTime0, claim.maxArrivalTime1,
claim.maxArrivalTime2, claim.status, claim.compensation, claim.compensationAddress);
}
//Requires pragma experimental ABIEncoderV2;
// function getAllClaims(bytes32 flightID) public view onlyIfCreator returns (Claim[] memory) {
// return claimList[flightID];
// }
//Fallback function. All deposits without any calling function by default go to this function
//https://solidity.readthedocs.io/en/v0.5.3/contracts.html#fallback-function
function() external payable {
availableFunds = availableFunds + msg.value;
}
function CADtoWei(uint256 amount) internal pure returns (uint256) {
return (amount*1000000000000000000)/200;
}
function WeiToETH(uint256 amount) internal pure returns (uint256) {
return amount/1000000000000000000;
}
//Deposits made with deposit() go to this function
function deposit() external payable onlyIfCreator {
availableFunds = availableFunds + msg.value;
}
function withdraw(uint256 amount) external onlyIfCreator enoughFunds(amount){
availableFunds = availableFunds - amount;
creator.transfer(amount);
}
function compensate(
uint256 ID,
uint256 compensation,
address payable recipient
)
internal enoughFunds(compensation){
uint256 WEIcompensation = CADtoWei(compensation);
recipient.transfer(WEIcompensation);
uint256 ETHcompensation = WeiToETH(WEIcompensation);
emit CompensationPaid(ID, ETHcompensation, recipient);
}
function compensateIfEnoughFunds(Claim memory claimToPay) private {
if (claimToPay.compensationAddress != address(0)) {
compensate(claimToPay.ID, claimToPay.compensation, claimToPay.compensationAddress);
}
}
}
|
going through only the ongoing claims
|
function addNewClaim(
uint256 ID,
bytes32 flightID,
uint8 airlineType,
uint256 maxArrivalTime0,
uint256 maxArrivalTime1,
uint256 maxArrivalTime2,
address payable compensationAddress
)
}
function updateFlightStatus(
bytes32 flightID,
uint256 actualArrivalTime
)
for (uint i = 0; i < claimList[flightID].length; i++) {
if (claimList[flightID][i].status == 0) {
if (actualArrivalTime > claimList[flightID][i].maxArrivalTime2){
updatedStatus = 4;
if (claimList[flightID][i].airlineType == 0){
claimList[flightID][i].compensation = small9;
}
else {
claimList[flightID][i].compensation = large9;
}
}
else if (actualArrivalTime > claimList[flightID][i].maxArrivalTime1){
updatedStatus = 3;
if (claimList[flightID][i].airlineType == 0){
claimList[flightID][i].compensation = small6;
}
else {
claimList[flightID][i].compensation = large6;
}
}
else if (actualArrivalTime > claimList[flightID][i].maxArrivalTime0){
updatedStatus = 2;
if (claimList[flightID][i].airlineType == 0){
claimList[flightID][i].compensation = small3;
}
else {
claimList[flightID][i].compensation = large3;
}
}
emit ClaimResolve(
claimList[flightID][i].ID,
flightID,
updatedStatus,
claimList[flightID][i].compensation
);
compensateIfEnoughFunds(claimList[flightID][i]);
}
}
| 15,825,085
|
./full_match/4/0x134C164ba6c5ba1A380317c2A9BE4BA33f080161/sources/testtest.sol
|
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;
}
| 648,474
|
pragma solidity >=0.5.0;
import "6_DBClientInterface.sol";
// This contract demonstrates how to send different amounts of information to another contract.
contract DataBase {
// Modifier that allows public function to accept all external calls.
modifier alwaysAccept {
// Runtime function that allows contract to process inbound messages spending
// its own resources (it's necessary if contract should process all inbound messages,
// not only those that carry value with them).
tvm.accept();
_;
}
// State variable storing the number of send* functions were called.
uint sendCounter = 0;
//Function to obtain state variables.
function getData() public view alwaysAccept returns (uint) {
return (sendCounter);
}
// Contract can store or generate different coefficients and provide them
// upon request as an array of integers.
// Function sends an array of uint64 with size 'count' to the contract
// with address 'receiver'.
function sendArray(address receiver, uint64 count) public alwaysAccept {
uint64[] arr = new uint64[](count);
for (uint64 i = 0; i < count; i++) {
arr[i] = i + 1;
}
IDataBaseClient(receiver).receiveArray(arr);
sendCounter++;
}
// Function sends five arrays of uint to the contract with address 'receiver'.
function sendFiveArrays(address receiver) public alwaysAccept {
uint256[] arr0 = new uint[](1);
arr0[0] = 1;
uint256[] arr1 = new uint[](1);
arr1[0] = 2;
uint256[] arr2 = new uint[](1);
arr2[0] = 3;
uint256[] arr3 = new uint[](1);
arr3[0] = 4;
uint256[] arr4 = new uint[](1);
arr4[0] = 5;
IDataBaseClient(receiver).receiveFiveArrays(arr0, arr1, arr2, arr3, arr4);
sendCounter++;
}
// Function sends five uint256 to the contract with address 'receiver'.
function sendFiveUint256(address receiver) public alwaysAccept {
uint256 a0 = 5;
uint256 a1 = 4;
uint256 a2 = 3;
uint256 a3 = 2;
uint256 a4 = 1;
IDataBaseClient(receiver).receiveFiveUint256(a0, a1, a2, a3, a4);
sendCounter++;
}
// Private function to create an array of structures, that will be sent to another contract.
function createStructArray() private pure returns (IDataBaseClient.MyStruct[]) {
IDataBaseClient.MyStruct[] arr = new IDataBaseClient.MyStruct[](2);
arr[0].ID = 1;
arr[0].value = 2;
arr[1].ID = 3;
arr[1].value = 4;
return arr;
}
// Function sends an array of structures to the contract with address 'receiver'.
function sendStructArray(address receiver) public alwaysAccept {
IDataBaseClient.MyStruct[] arr = createStructArray();
IDataBaseClient(receiver).receiveStructArray(arr);
sendCounter++;
}
}
|
Function sends an array of structures to the contract with address 'receiver'.
|
function sendStructArray(address receiver) public alwaysAccept {
IDataBaseClient.MyStruct[] arr = createStructArray();
IDataBaseClient(receiver).receiveStructArray(arr);
sendCounter++;
}
| 5,408,049
|
// @author Unstoppable Domains, Inc.
// @date August 12th, 2021
pragma solidity ^0.8.0;
import '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol';
import './IForwarder.sol';
import './BaseForwarder.sol';
/**
* @title BaseRoutingForwarder
* @dev BaseRoutingForwarder simplifies operation with legacy meta-transactions by routing calls
*/
abstract contract BaseRoutingForwarder is BaseForwarder {
mapping(bytes4 => bytes4) private _routes;
function _buildRouteData(
bytes4 selector,
bytes memory data,
bytes memory signature
) internal view virtual returns (bytes memory);
function _verify(
ForwardRequest memory req,
address target,
bytes memory signature
) internal view override returns (bool) {
return super._verify(req, target, signature) && _isKnownRoute(req.data);
}
function _buildData(
address, /* from */
uint256, /* tokenId */
bytes memory data,
bytes memory signature
) internal view override returns (bytes memory) {
bytes4 route = _getRoute(data);
require(route != 0, 'BaseRoutingForwarder: ROUTE_UNKNOWN');
bytes memory _data;
assembly {
_data := add(data, 4)
mstore(_data, sub(mload(data), 4))
}
return _buildRouteData(route, _data, signature);
}
function _addRoute(bytes memory from, bytes memory to) internal {
_routes[bytes4(keccak256(from))] = bytes4(keccak256(to));
}
function _getRoute(bytes memory data) internal view returns (bytes4) {
bytes4 selector;
/* solium-disable-next-line security/no-inline-assembly */
assembly {
selector := mload(add(data, add(0x20, 0)))
}
return _routes[selector];
}
function _isKnownRoute(bytes memory data) internal view returns (bool) {
bytes4 route = _getRoute(data);
return route != 0;
}
}
|
solium-disable-next-line security/no-inline-assembly /
|
function _getRoute(bytes memory data) internal view returns (bytes4) {
bytes4 selector;
assembly {
selector := mload(add(data, add(0x20, 0)))
}
return _routes[selector];
}
| 6,474,704
|
// File: contracts/vaults/IStrategy.sol
pragma solidity 0.5.17;
interface istrategy59 { //inject NONSTANDARD NAMING
function GETNAME35() external pure returns (string memory); //inject NONSTANDARD NAMING
function WANT31() external view returns (address); //inject NONSTANDARD NAMING
function WITHDRAW24(address) external; //inject NONSTANDARD NAMING
function WITHDRAW24(uint256) external; //inject NONSTANDARD NAMING
function WITHDRAWALL24() external returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF3() external view returns (uint256); //inject NONSTANDARD NAMING
}
// File: contracts/IERC20.sol
//SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.5.17;
interface ierc2080 { //inject NONSTANDARD NAMING
function TOTALSUPPLY74() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF3(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER92(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE58(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE17(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM23(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER57(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL94(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
// File: contracts/ITreasury.sol
pragma solidity 0.5.17;
interface itreasury2 { //inject NONSTANDARD NAMING
function DEFAULTTOKEN28() external view returns (ierc2080); //inject NONSTANDARD NAMING
function DEPOSIT94(ierc2080 token, uint256 amount) external; //inject NONSTANDARD NAMING
function WITHDRAW24(uint256 amount, address withdrawAddress) external; //inject NONSTANDARD NAMING
}
// File: contracts/vaults/IVault.sol
pragma solidity 0.5.17;
interface ivault53 { //inject NONSTANDARD NAMING
function WANT31() external view returns (ierc2080); //inject NONSTANDARD NAMING
function TRANSFERFUNDSTOSTRATEGY94(address strategy, uint256 amount) external; //inject NONSTANDARD NAMING
function AVAILABLEFUNDS75() external view returns (uint256); //inject NONSTANDARD NAMING
}
// File: contracts/vaults/IVaultRewards.sol
pragma solidity 0.5.17;
interface ivaultrewards63 { //inject NONSTANDARD NAMING
function WANT31() external view returns (ierc2080); //inject NONSTANDARD NAMING
function NOTIFYREWARDAMOUNT2(uint256 reward) external; //inject NONSTANDARD NAMING
}
// File: contracts/vaults/IController.sol
pragma solidity 0.5.17;
interface icontroller20 { //inject NONSTANDARD NAMING
function CURRENTEPOCHTIME27() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF3(address) external view returns (uint256); //inject NONSTANDARD NAMING
function REWARDS0(address token) external view returns (ivaultrewards63); //inject NONSTANDARD NAMING
function VAULT69(address token) external view returns (ivault53); //inject NONSTANDARD NAMING
function ALLOWABLEAMOUNT15(address) external view returns (uint256); //inject NONSTANDARD NAMING
function TREASURY79() external view returns (itreasury2); //inject NONSTANDARD NAMING
function APPROVEDSTRATEGIES44(address, address) external view returns (bool); //inject NONSTANDARD NAMING
function GETHARVESTINFO14(address strategy, address user) //inject NONSTANDARD NAMING
external view returns (
uint256 vaultRewardPercentage,
uint256 hurdleAmount,
uint256 harvestPercentage
);
function WITHDRAW24(address, uint256) external; //inject NONSTANDARD NAMING
function EARN37(address, uint256) external; //inject NONSTANDARD NAMING
function INCREASEHURDLERATE27(address token) external; //inject NONSTANDARD NAMING
}
// File: contracts/ISwapRouter.sol
//SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.5.17;
interface swaprouter18 { //inject NONSTANDARD NAMING
function WETH90() external pure returns (address); //inject NONSTANDARD NAMING
function SWAPEXACTTOKENSFORTOKENS91( //inject NONSTANDARD NAMING
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
}
// File: contracts/SafeMath.sol
pragma solidity 0.5.17;
// Note: This file has been modified to include the sqrt function for quadratic voting
library math29 { //inject NONSTANDARD NAMING
function MAX82(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return a >= b ? a : b;
}
function MIN43(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return a < b ? a : b;
}
function AVERAGE17(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
function SQRT87(uint256 x) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 n = x / 2;
uint256 lstX = 0;
while (n != lstX){
lstX = n;
n = (n + x/n) / 2;
}
return uint256(n);
}
}
library safemath85 { //inject NONSTANDARD NAMING
function ADD14(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB75(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB75(a, b, "SafeMath: subtraction overflow");
}
function SUB75(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 MUL41(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 DIV62(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV62(a, b, "SafeMath: division by zero");
}
function DIV62(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// 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;
}
function MOD3(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD3(a, b, "SafeMath: modulo by zero");
}
function MOD3(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
// File: contracts/zeppelin/Address.sol
pragma solidity 0.5.17;
library address35 { //inject NONSTANDARD NAMING
function ISCONTRACT42(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// 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);
}
function TOPAYABLE96(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING
return address(uint160(account));
}
function SENDVALUE71(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
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: contracts/zeppelin/SafeERC20.sol
pragma solidity 0.5.17;
library safeerc2099 { //inject NONSTANDARD NAMING
using safemath85 for uint256;
using address35 for address;
function SAFETRANSFER62(ierc2080 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.TRANSFER92.selector, to, value));
}
function SAFETRANSFERFROM40(ierc2080 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.TRANSFERFROM23.selector, from, to, value));
}
function SAFEAPPROVE5(ierc2080 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
// 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.ALLOWANCE58(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.APPROVE17.selector, spender, value));
}
function SAFEINCREASEALLOWANCE71(ierc2080 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE58(address(this), spender).ADD14(value);
CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.APPROVE17.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE44(ierc2080 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE58(address(this), spender).SUB75(value, "SafeERC20: decreased allowance below zero");
CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.APPROVE17.selector, spender, newAllowance));
}
function CALLOPTIONALRETURN65(ierc2080 token, bytes memory data) private { //inject NONSTANDARD NAMING
// 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).ISCONTRACT42(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts/vaults/strategy/MStableStrategy.sol
//SPDX-License-Identifier: MIT
pragma solidity 0.5.17;
interface ibpt3 { //inject NONSTANDARD NAMING
function TOTALSUPPLY74() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF3(address whom) external view returns (uint); //inject NONSTANDARD NAMING
function GETSPOTPRICE26(address tokenIn, address tokenOut) external view returns (uint spotPrice); //inject NONSTANDARD NAMING
function SWAPEXACTAMOUNTIN69(address, uint, address, uint, uint) external returns (uint, uint); //inject NONSTANDARD NAMING
function SWAPEXACTAMOUNTOUT77(address, uint, address, uint, uint) external returns (uint, uint); //inject NONSTANDARD NAMING
function JOINSWAPEXTERNAMOUNTIN73( //inject NONSTANDARD NAMING
address tokenIn,
uint tokenAmountIn,
uint minPoolAmountOut
) external returns (uint poolAmountOut);
function EXITSWAPEXTERNAMOUNTOUT85( //inject NONSTANDARD NAMING
address tokenOut,
uint tokenAmountOut,
uint maxPoolAmountIn
) external returns (uint poolAmountIn);
function EXITSWAPPOOLAMOUNTIN6( //inject NONSTANDARD NAMING
address tokenOut,
uint poolAmountIn,
uint minAmountOut
) external returns (uint tokenAmountOut);
}
interface impool6 { //inject NONSTANDARD NAMING
function BALANCEOF3(address _account) external view returns (uint256); //inject NONSTANDARD NAMING
function EARNED23(address _account) external view returns (uint256, uint256); //inject NONSTANDARD NAMING
function STAKE12(uint256 _amount) external; //inject NONSTANDARD NAMING
function CLAIMREWARD81() external; //inject NONSTANDARD NAMING
function EXIT39() external; //inject NONSTANDARD NAMING
}
interface imtagov79 { //inject NONSTANDARD NAMING
function BALANCEOF3(address _account) external view returns (uint256); //inject NONSTANDARD NAMING
function EARNED23(address _account) external view returns (uint256); //inject NONSTANDARD NAMING
function CREATELOCK73(uint256 _value, uint256 _unlockTime) external; //inject NONSTANDARD NAMING
function WITHDRAW24() external; //inject NONSTANDARD NAMING
function INCREASELOCKAMOUNT91(uint256 _value) external; //inject NONSTANDARD NAMING
function CLAIMREWARD81() external; //inject NONSTANDARD NAMING
}
contract mstablestrat66 is istrategy59 { //inject NONSTANDARD NAMING
using safeerc2099 for ierc2080;
using address35 for address;
using safemath85 for uint256;
uint256 public constant performance_fee63 = 500; // 5% //inject NONSTANDARD NAMING
uint256 public constant denom43 = 10000; //inject NONSTANDARD NAMING
uint256 public hurdleLastUpdateTime;
uint256 public harvestAmountThisEpoch;
uint256 public strategistCollectedFee;
uint256 public numPools = 1;
ierc2080 internal usdc = ierc2080(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
ierc2080 internal musd = ierc2080(0xe2f2a5C287993345a840Db3B0845fbC70f5935a5);
ierc2080 internal mta = ierc2080(0xa3BeD4E1c75D00fa6f4E5E6922DB7261B5E9AcD2);
ibpt3 internal musdcBpt = ibpt3(0x72Cd8f4504941Bf8c5a21d1Fd83A96499FD71d2C);
swaprouter18 public swapRouter = swaprouter18(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
impool6 internal mPool = impool6(0x881c72D1e6317f10a1cDCBe05040E7564E790C80);
imtagov79 internal mtaGov = imtagov79(0xaE8bC96DA4F9A9613c323478BE181FDb2Aa0E1BF);
ierc2080 public want = usdc; // should be set only in constructor or hardcoded
icontroller20 public controller; // should be set only in constructor
address public strategist; // mutable, but only by strategist
// want must be equal to an underlying vault token (Eg. USDC)
constructor(icontroller20 _controller) public {
controller = _controller;
strategist = msg.sender;
}
function GETNAME35() external pure returns (string memory) { //inject NONSTANDARD NAMING
return "MstableStrategy";
}
function SETSTRATEGIST71(address _strategist) external { //inject NONSTANDARD NAMING
require(msg.sender == strategist, "!strategist");
strategist = _strategist;
}
function SETNUMPOOLSFORSWAP74(uint256 _numPools) external { //inject NONSTANDARD NAMING
require(msg.sender == strategist, "!strategist");
numPools = _numPools;
}
function SETALLOWANCES18(ierc2080 token, address[] calldata recipients, bool isIncrease) external { //inject NONSTANDARD NAMING
require(msg.sender == strategist, "!strategist");
for (uint i = 0; i < recipients.length; i++) {
require(
recipients[i] == address(musdcBpt) ||
recipients[i] == address(swapRouter) ||
recipients[i] == address(mPool) ||
recipients[i] == address(mtaGov),
"bad recipient"
);
uint256 allowance = isIncrease ? uint256(-1) : 0;
token.SAFEAPPROVE5(recipients[i], allowance);
}
}
// Assumed that caller checks against available funds in vault
function DEPOSIT94(uint256 amount) public { //inject NONSTANDARD NAMING
uint256 availFunds = controller.ALLOWABLEAMOUNT15(address(this));
require(amount <= availFunds, "exceed contAllowance");
controller.EARN37(address(this), amount);
// deposit into musdcBpt
uint256 bptTokenAmt = musdcBpt.JOINSWAPEXTERNAMOUNTIN73(address(want), amount, 0);
// deposit into mstable pool
mPool.STAKE12(bptTokenAmt);
// deposit any MTA token in this contract into mStaking contract
DEPOSITMTAINSTAKING28();
}
function BALANCEOF3() external view returns (uint256) { //inject NONSTANDARD NAMING
// get balance in mPool
uint256 bptStakeAmt = mPool.BALANCEOF3(address(this));
// get usdc + musd amts in BPT, and total BPT
uint256 usdcAmt = usdc.BALANCEOF3(address(musdcBpt));
uint256 musdAmt = musd.BALANCEOF3(address(musdcBpt));
uint256 totalBptAmt = musdcBpt.TOTALSUPPLY74();
// convert musd to usdc
usdcAmt = usdcAmt.ADD14(
musdAmt.MUL41(1e18).DIV62(musdcBpt.GETSPOTPRICE26(address(musd), address(usdc)))
);
return bptStakeAmt.MUL41(usdcAmt).DIV62(totalBptAmt);
}
function EARNED23() external view returns (uint256) { //inject NONSTANDARD NAMING
(uint256 earnedAmt,) = mPool.EARNED23(address(this));
return earnedAmt.ADD14(mtaGov.EARNED23(address(this)));
}
function WITHDRAW24(address token) external { //inject NONSTANDARD NAMING
ierc2080 erc20Token = ierc2080(token);
require(msg.sender == address(controller), "!controller");
erc20Token.SAFETRANSFER62(address(controller), erc20Token.BALANCEOF3(address(this)));
}
function WITHDRAW24(uint256 amount) external { //inject NONSTANDARD NAMING
require(msg.sender == address(controller), "!controller");
// exit fully
mPool.EXIT39();
// convert to desired amount
musdcBpt.EXITSWAPEXTERNAMOUNTOUT85(address(want), amount, uint256(-1));
// deposit whatever remaining bpt back into mPool
mPool.STAKE12(musdcBpt.BALANCEOF3(address(this)));
// send funds to vault
want.SAFETRANSFER62(address(controller.VAULT69(address(want))), amount);
}
function WITHDRAWALL24() external returns (uint256 balance) { //inject NONSTANDARD NAMING
require(msg.sender == address(controller), "!controller");
// exit fully
mPool.EXIT39();
// convert reward to want tokens
// in case swap fails, continue
(bool success, ) = address(this).call(
abi.encodeWithSignature(
"exchangeRewardForWant(bool)",
true
)
);
// to remove compiler warning
success;
// convert bpt to want tokens
musdcBpt.EXITSWAPPOOLAMOUNTIN6(
address(want),
musdcBpt.BALANCEOF3(address(this)),
0
);
// exclude collected strategist fee
balance = want.BALANCEOF3(address(this)).SUB75(strategistCollectedFee);
// send funds to vault
want.SAFETRANSFER62(address(controller.VAULT69(address(want))), balance);
}
function HARVEST87(bool claimMPool, bool claimGov) external { //inject NONSTANDARD NAMING
if (claimMPool) mPool.CLAIMREWARD81();
if (claimGov) mtaGov.CLAIMREWARD81();
// convert 80% reward to want tokens
// in case swap fails, return
(bool success, ) = address(this).call(
abi.encodeWithSignature(
"exchangeRewardForWant(bool)",
false
)
);
// to remove compiler warning
if (!success) return;
uint256 amount = want.BALANCEOF3(address(this)).SUB75(strategistCollectedFee);
uint256 vaultRewardPercentage;
uint256 hurdleAmount;
uint256 harvestPercentage;
uint256 epochTime;
(vaultRewardPercentage, hurdleAmount, harvestPercentage) =
controller.GETHARVESTINFO14(address(this), msg.sender);
// check if harvest amount has to be reset
if (hurdleLastUpdateTime < epochTime) {
// reset collected amount
harvestAmountThisEpoch = 0;
}
// update variables
hurdleLastUpdateTime = block.timestamp;
harvestAmountThisEpoch = harvestAmountThisEpoch.ADD14(amount);
// first, take harvester fee
uint256 harvestFee = amount.MUL41(harvestPercentage).DIV62(denom43);
want.SAFETRANSFER62(msg.sender, harvestFee);
uint256 fee;
// then, if hurdle amount has been exceeded, take performance fee
if (harvestAmountThisEpoch >= hurdleAmount) {
fee = amount.MUL41(performance_fee63).DIV62(denom43);
strategistCollectedFee = strategistCollectedFee.ADD14(fee);
}
// do the subtraction of harvester and strategist fees
amount = amount.SUB75(harvestFee).SUB75(fee);
// calculate how much is to be re-invested
// fee = vault reward amount, reusing variable
fee = amount.MUL41(vaultRewardPercentage).DIV62(denom43);
want.SAFETRANSFER62(address(controller.REWARDS0(address(want))), fee);
controller.REWARDS0(address(want)).NOTIFYREWARDAMOUNT2(fee);
amount = amount.SUB75(fee);
// finally, use remaining want amount for reinvestment
amount = musdcBpt.JOINSWAPEXTERNAMOUNTIN73(address(want), amount, 0);
// deposit into mstable pool
mPool.STAKE12(amount);
// deposit any MTA token in this contract into mStaking contract
DEPOSITMTAINSTAKING28();
}
function WITHDRAWSTRATEGISTFEE97() external { //inject NONSTANDARD NAMING
strategistCollectedFee = 0;
want.SAFETRANSFER62(strategist, strategistCollectedFee);
}
function EXITMGOV72() external { //inject NONSTANDARD NAMING
mtaGov.WITHDRAW24();
// convert to want tokens
// in case swap fails, continue
(bool success, ) = address(this).call(
abi.encodeWithSignature(
"exchangeRewardForWant(bool)",
true
)
);
// to remove compiler warning
success;
want.SAFETRANSFER62(
address(controller.REWARDS0(address(want))),
want.BALANCEOF3(address(this)).SUB75(strategistCollectedFee)
);
}
function EXCHANGEREWARDFORWANT67(bool exchangeAll) public { //inject NONSTANDARD NAMING
uint256 swapAmt = mta.BALANCEOF3(address(this));
if (swapAmt == 0) return;
// do the exchange
address[] memory routeDetails = new address[](3);
routeDetails[0] = address(mta);
routeDetails[1] = swapRouter.WETH90();
routeDetails[2] = address(want);
swapRouter.SWAPEXACTTOKENSFORTOKENS91(
exchangeAll ? swapAmt : swapAmt.MUL41(8000).DIV62(denom43),
0,
routeDetails,
address(this),
block.timestamp + 100
);
}
function DEPOSITMTAINSTAKING28() internal { //inject NONSTANDARD NAMING
uint256 mtaBal = mta.BALANCEOF3(address(this));
if (mtaBal == 0) return;
if (mtaGov.BALANCEOF3(address(this)) == 0) {
// create lock with max time
mtaGov.CREATELOCK73(mtaBal, 1632580257);
} else {
// increase amount
mtaGov.INCREASELOCKAMOUNT91(mtaBal);
}
}
}
|
inject NONSTANDARD NAMING
|
function SWAPEXACTAMOUNTOUT77(address, uint, address, uint, uint) external returns (uint, uint);
| 1,825,117
|
./partial_match/1/0x1E7407b5f0c3ec55cFEEb0B19Dfb006e32F8EBB0/sources/TOW3.sol
|
0 is always defined as the O from HOST 9 image will just be 6 upside down
|
function getNumberDefinitions( uint n ) private pure returns (string memory) {
bytes memory b = bytes(n.toString());
string memory definitions = getNumberSVG(0);
uint isDefined = 0;
for(uint i; i < b.length; i++){
uint digit = uint(uint8(b[i])) - 48;
if( digit != 0 ){
uint position = digit == 9 ? 6 : digit;
bool alreadyDefined = ((isDefined >> position) & 1) == 1;
if( !alreadyDefined ){
definitions = string.concat( definitions, getNumberSVG(position));
isDefined = isDefined | uint(1) << position;
}
}
}
return definitions;
}
| 2,838,338
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "./lib/RLPReader.sol";
import "./lib/RLPEncode.sol";
import "./interface/ILightNode.sol";
import "./bls/WeightedMultiSig.sol";
import "./lib/MPT.sol";
interface IVerifyProof {
function verifyTrieProof(bytes32 hash, bytes memory _expectedValue, bytes[] memory proofs,bytes memory _key)
pure external returns (bool success);
}
contract LightNode is UUPSUpgradeable, Initializable, ILightNode{
using RLPReader for bytes;
using RLPReader for uint256;
using RLPReader for RLPReader.RLPItem;
using RLPReader for RLPReader.Iterator;
uint256 public epochSize = 1000;
address[] public validatorAddresss ;
event validitorsSet(uint256 epoch);
WeightedMultiSig weightedMultisig;
constructor() {}
/** initialize **********************************************************/
function initialize(uint _threshold, address[] memory _validatorAddresss, G1[] memory _pairKeys,
uint[] memory _weights, uint _epoch, uint _epochSize)
external initializer {
epochSize = _epochSize;
validatorAddresss = _validatorAddresss;
weightedMultisig.setStateInternal(_threshold,_pairKeys,_weights,_epoch);
}
function verifyProofData(receiptProof memory _receiptProof) external view returns (bool success, string memory message){
(success, message) = getVerifyTrieProof(_receiptProof);
if (!success) {
message = "receipt mismatch";
}
//todo verify header
}
function updateBlockHeader(blockHeader memory bh, G2 memory aggPk) external {
require(bh.number % epochSize == 0, "Header number is error");
//todo verify
//weightedMultisig.checkSig()
}
function getStatus(bool _tag) public view returns (bytes memory PostStateOrStatus){
PostStateOrStatus = abi.encode(_tag);
}
function getVerifyTrieProof(receiptProof memory _receiptProof) public view returns (
bool success, string memory message){
MPT.MerkleProof memory mProof ;
//todo set proof
success = MPT.verifyTrieProof(mProof);
if (!success) {
message = "receipt mismatch";
} else {
message = "success";
}
}
function _bytesSlice32(bytes memory data, uint256 offset)
public
pure
returns (uint256 slice){
bytes memory tmp = new bytes(32);
for (uint256 i = 0; i < 32; i++) {
tmp[i] = data[offset + i];
}
slice = uint256(bytes32(tmp));
}
function _decodeHeader(bytes memory rlpBytes)
public
pure
returns (blockHeader memory bh){
RLPReader.RLPItem[] memory ls = rlpBytes.toRlpItem().toList();
bh = blockHeader({
parentHash : ls[0].toBytes(),
coinbase : ls[1].toAddress(),
root : ls[2].toBytes(),
txHash : ls[3].toBytes(),
receiptHash : ls[4].toBytes(),
number : ls[6].toUint(),
extraData : ls[10].toBytes(),
bloom : ls[5].toBytes(),
gasLimit : ls[7].toUint(),
gasUsed : ls[8].toUint(),
time : ls[9].toUint(),
mixDigest : ls[11].toBytes(),
nonce : ls[12].toBytes(),
baseFee : ls[13].toUint()
});
}
function _encodeHeader(blockHeader memory bh)
public
pure
returns (bytes memory output){
bytes[] memory list = new bytes[](14);
list[0] = RLPEncode.encodeBytes(bh.parentHash);
list[1] = RLPEncode.encodeAddress(bh.coinbase);
list[2] = RLPEncode.encodeBytes(bh.root);
list[3] = RLPEncode.encodeBytes(bh.txHash);
list[4] = RLPEncode.encodeBytes(bh.receiptHash);
list[5] = RLPEncode.encodeBytes(bh.bloom);
list[6] = RLPEncode.encodeUint(bh.number);
list[7] = RLPEncode.encodeUint(bh.gasLimit);
list[8] = RLPEncode.encodeUint(bh.gasUsed);
list[9] = RLPEncode.encodeUint(bh.time);
list[10] = RLPEncode.encodeBytes(bh.extraData);
list[11] = RLPEncode.encodeBytes(bh.mixDigest);
list[12] = RLPEncode.encodeBytes(bh.nonce);
list[13] = RLPEncode.encodeUint(bh.baseFee);
output = RLPEncode.encodeList(list);
}
function _decodeExtraData(bytes memory extraData)
public
pure
returns (istanbulExtra memory ist){
bytes memory decodeBytes = _splitExtra(extraData);
RLPReader.RLPItem[] memory ls = decodeBytes.toRlpItem().toList();
RLPReader.RLPItem[] memory item0 = ls[0].toList();
RLPReader.RLPItem[] memory item1 = ls[1].toList();
RLPReader.RLPItem[] memory item2 = ls[2].toList();
RLPReader.RLPItem memory item3 = ls[3];
RLPReader.RLPItem memory item4 = ls[4];
RLPReader.RLPItem memory item5 = ls[5];
RLPReader.RLPItem memory item6 = ls[6];
address[] memory validatorTemp = new address[](item0.length);
bytes[] memory addedPubKeyTemp = new bytes[](item1.length);
bytes[] memory addedG1PubKeyTemp = new bytes[](item2.length);
if (item0.length >0 ){
for (uint256 i = 0; i < item0.length; i++) {
validatorTemp[i] = item0[i].toAddress();
}
}
if (item1.length >0 ){
for (uint256 j = 0; j < item1.length; j++) {
addedPubKeyTemp[j] = item1[j].toBytes();
}
}
if (item2.length >0 ){
for (uint256 k = 0; k < item2.length; k++) {
addedG1PubKeyTemp[k] = item2[k].toBytes();
}
}
ist = istanbulExtra({
validators: validatorTemp,
addedPubKey: addedPubKeyTemp,
addedG1PubKey: addedG1PubKeyTemp,
removeList: item3.toUint(),
seal: item4.toBytes(),
aggregatedSeal: istanbulAggregatedSeal({
bitmap: item5.toList()[0].toUint(),
signature: item5.toList()[1].toBytes(),
round: item5.toList()[2].toUint()
}),
parentAggregatedSeal: istanbulAggregatedSeal({
bitmap: item6.toList()[0].toUint(),
signature: item6.toList()[1].toBytes(),
round: item6.toList()[2].toUint()
})
});
}
function _splitExtra(bytes memory extra)
public
pure
returns (bytes memory newExtra){
newExtra = new bytes(extra.length - 32);
uint256 n = 0;
for (uint256 i = 32; i < extra.length; i++) {
newExtra[n] = extra[i];
n = n + 1;
}
return newExtra;
}
function splitExtra(bytes memory extra)
public
pure
returns (bytes memory newExtra){
newExtra = new bytes(32);
uint m = 0;
for (uint i = 0; i < 32; i++) {
newExtra[m] = extra[i];
m = m + 1;
}
return newExtra;
}
function _verifyHeader(bytes memory rlpHeader)
public
view
returns (bool ret, uint256 removeList, bytes[] memory addedPubKey){
blockHeader memory bh = _decodeHeader(rlpHeader);
istanbulExtra memory ist = _decodeExtraData(bh.extraData);
bytes memory extraDataPre = splitExtra(bh.extraData);
bh.extraData = _deleteAgg(ist, extraDataPre);
bytes memory headerWithoutAgg = _encodeHeader(bh);
bytes32 hash1 = keccak256(abi.encodePacked(headerWithoutAgg));
bh.extraData = _deleteSealAndAgg(ist, bh.extraData);
bytes memory headerWithoutSealAndAgg = _encodeHeader(bh);
bytes32 hash2 = keccak256(abi.encodePacked(headerWithoutSealAndAgg));
ret = _verifySign(
ist.seal,
keccak256(abi.encodePacked(hash2)),
bh.coinbase
);
if (ret == false) {
revert("verifyEscaSign fail");
}
}
function _deleteAgg(istanbulExtra memory ist,bytes memory extraDataPre)
public
pure
returns (bytes memory newExtra){
bytes[] memory list1 = new bytes[](ist.validators.length);
bytes[] memory list2 = new bytes[](ist.addedPubKey.length);
bytes[] memory list3 = new bytes[](ist.addedG1PubKey.length);
for (uint256 i = 0; i < ist.validators.length; i++) {
list1[i] = RLPEncode.encodeAddress(ist.validators[i]); //
list2[i] = RLPEncode.encodeBytes(ist.addedPubKey[i]); //
list3[i] = RLPEncode.encodeBytes(ist.addedG1PubKey[i]);
}
bytes[] memory list = new bytes[](7);
list[0] = RLPEncode.encodeList(list1);//
list[1] = RLPEncode.encodeList(list2);//
list[2] = RLPEncode.encodeList(list3);
list[3] = RLPEncode.encodeUint(ist.removeList);//
list[4] = RLPEncode.encodeBytes(ist.seal);//
list[5] = new bytes(4);
list[5][0] = bytes1(uint8(195));
list[5][1] = bytes1(uint8(128));
list[5][2] = bytes1(uint8(128));
list[5][3] = bytes1(uint8(128));
list[6] = _encodeAggregatedSeal(ist.parentAggregatedSeal.bitmap,ist.parentAggregatedSeal.signature,ist.parentAggregatedSeal.round);
bytes memory b = RLPEncode.encodeList(list);
bytes memory output = new bytes(b.length+32);
for (uint i=0;i<b.length+32;i++){
if (i<32){
output[i] = extraDataPre[i];
}else{
output[i] = b[i-32];
}
}
newExtra = output;
}
function _deleteSealAndAgg(istanbulExtra memory ist,bytes memory rlpHeader)
public
pure
returns (bytes memory newExtra){
bytes[] memory list1 = new bytes[](ist.validators.length);
bytes[] memory list2 = new bytes[](ist.addedPubKey.length);
bytes[] memory list3 = new bytes[](ist.addedG1PubKey.length);
for (uint256 i = 0; i < ist.validators.length; i++) {
list1[i] = RLPEncode.encodeAddress(ist.validators[i]); //
list2[i] = RLPEncode.encodeBytes(ist.addedPubKey[i]); //
list3[i] = RLPEncode.encodeBytes(ist.addedG1PubKey[i]);
}
bytes[] memory list = new bytes[](7);
list[0] = RLPEncode.encodeList(list1); //
list[1] = RLPEncode.encodeList(list2); //
list[2] = RLPEncode.encodeList(list3); //
list[3] = RLPEncode.encodeUint(ist.removeList); //
list[4] = new bytes(1);
list[4][0] = bytes1(uint8(128)); //
list[5] = new bytes(4);
list[5][0] = bytes1(uint8(195));
list[5][1] = bytes1(uint8(128));
list[5][2] = bytes1(uint8(128));
list[5][3] = bytes1(uint8(128));
list[6] = _encodeAggregatedSeal(
ist.parentAggregatedSeal.bitmap,
ist.parentAggregatedSeal.signature,
ist.parentAggregatedSeal.round
);
bytes memory b = RLPEncode.encodeList(list);
newExtra = abi.encodePacked(bytes32(rlpHeader),b);
}
function _encodeAggregatedSeal(
uint256 bitmap,
bytes memory signature,
uint256 round
) public pure returns (bytes memory output) {
bytes memory output1 = RLPEncode.encodeUint(bitmap);
bytes memory output2 = RLPEncode.encodeBytes(signature);
bytes memory output3 = RLPEncode.encodeUint(round);
bytes[] memory list = new bytes[](3);
list[0] = output1;
list[1] = output2;
list[2] = output3;
output = RLPEncode.encodeList(list);
}
function _encodeSealHash(
uint256 bitmap,
bytes memory signature,
address round
) public pure returns (bytes memory output) {
bytes memory output1 = RLPEncode.encodeUint(bitmap);
bytes memory output2 = RLPEncode.encodeBytes(signature);
bytes memory output3 = RLPEncode.encodeAddress(round);
bytes[] memory list = new bytes[](3);
list[0] = output1;
list[1] = output2;
list[2] = output3;
output = RLPEncode.encodeList(list);
}
function _verifySign(
bytes memory seal,
bytes32 hash,
address coinbase
) public pure returns (bool) {
(bytes32 r, bytes32 s, uint8 v) = splitSignature(seal);
v = v + 27;
return coinbase == ecrecover(hash, v, r, s);
}
function splitSignature(bytes memory sig)
public
pure
returns
(bytes32 r, bytes32 s, uint8 v){
require(sig.length == 65, "invalid signature length");
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
}
function _addsuffix(bytes32 hash, uint8 round)
public
pure
returns (bytes memory){
bytes memory result = new bytes(34);
for (uint256 i = 0; i < 32; i++) {
result[i] = hash[i];
}
result[32] = bytes1(round);
result[33] = bytes1(uint8(2));
return result;
}
/** UUPS *********************************************************/
function _authorizeUpgrade(address) internal view override {
require(msg.sender == _getAdmin(), "LightNode: only Admin can upgrade");
}
}
|
UUPS /
|
function _authorizeUpgrade(address) internal view override {
require(msg.sender == _getAdmin(), "LightNode: only Admin can upgrade");
}
| 12,668,546
|
./full_match/1/0x5C65b21FeD9e97369d0e04b03B3180dB3249759d/sources/contracts/growth/growth.sol
|
getters and setters for Presale access
|
function canAccessPresale(address addr) public view returns (bool) {
return _presaleAccess[addr];
}
| 3,849,117
|
pragma solidity >=0.7.0 <0.8.0;
/**
* SPDX-License-Identifier: MIT
* Copyright (c) 2020 Kim Il Yong
*/
// Connect Remix to: http://localhost:49796
import "./safemath.sol";
import "./signedsafemath.sol";
import "./math.sol";
/**
* @title OwnedContract
* @dev Set & change contract owner
*/
contract OwnedContract {
// 104 name interface is bytes32
// 104 published to '0x4b7c29e9c7e5132B140884A9dAc98427dcF97AbF'
// 105 name interface is string
// 105 published to '0xfC79349137862639A035c71C36fD4d71B2a5D668'
// 106 add country
// 106 published to '0x1EDf7947F7b95bA658D0A74024Dd8092e4D4831c'
// 107 one more require(_amount <= getBalance(), "not enough contract funds");
// set name and country at every donation & request
// fixed parent constructor calling
// no abi changes
// 107 published to 0x57B98F76bB39546F97BccD1EF0A38b2d9E074494
uint16 constant public version = 107;
// The creator of this contract
address payable private owner;
// event for EVM logging
event OwnerSet(address indexed oldOwner, address indexed newOwner);
// modifier to check if caller is owner
modifier isOwner() {
// If the first argument of 'require' evaluates to 'false', execution terminates and all
// changes to the state and to Ether balances are reverted.
// This used to consume all gas in old EVM versions, but not anymore.
// It is often a good idea to use 'require' to check if functions are called correctly.
// As a second argument, you can also provide an explanation about what went wrong.
require(msg.sender == owner, "Caller is not owner");
_;
}
/**
* @dev Set contract deployer as owner
*/
constructor() {
owner = msg.sender; // 'msg.sender' is sender of current call, contract deployer for a constructor
emit OwnerSet(address(0), owner);
}
/**
* @dev Change owner
* @param newOwner address of new owner
*/
function changeOwner(address payable newOwner) public isOwner {
address payable oldOwner = owner;
owner = newOwner;
emit OwnerSet(oldOwner, newOwner);
}
/**
* @dev Return owner address
* @return address of owner
*/
function getOwner() public view returns (address payable) {
return owner;
}
/**
* @dev Return owner address
* @return address of owner
*/
function getVersion() public pure returns (uint16) {
return version;
}
}
/**
* @title Faucet
* @dev Donate money to Developers in Need
*/
contract Faucet is OwnedContract {
using SafeMath for uint;
using SafeMath for uint64;
using SignedSafeMath for int;
event ReceivedDonation(address indexed donor, uint amount, uint donationnumber);
event GivenDonation(address indexed recipient, uint amount, uint donationnumber);
event WithdrawMoney(address indexed to, uint indexed amount);
struct Payment {
uint amount;
bool withdraw;
uint timestamp;
}
struct Balance {
uint totalBalance;
uint64 numPayments;
uint64 index;
string name;
bytes8 country;
mapping(uint => Payment) payments;
}
// Allow a request only every 4 hours
uint16 constant private graceTimeout = 14400; //60*60*4
uint private totalBalance;
address[] private Donors;
address[] private Recipients;
mapping(address => Balance) private Donations;
mapping(address => Balance) private Payments;
/**
* @dev Set contract deployer as owner
*/
constructor() OwnedContract() {
totalBalance = 0;
}
/**
* @dev Delete the smart contract
*/
function destroySmartContract() public isOwner {
selfdestruct(super.getOwner());
}
receive() external payable {
string memory name = "Anonymous Donor";
bytes8 country = "Terra";
Donation(name, country);
}
fallback() external {
revert("Have a look at https://github.com/kimxilxyong/Energi-Smart-Contract-Tutorial/blob/master/solidity/faucet.sol");
}
/**
* @dev Return the address of the contract
* @return address
*/
function getAddress() public view returns (address) {
return address(this);
}
/**
* @dev Return balance of contract
* @return balance
*/
function getBalance() public view returns (uint) {
return (payable(address(this))).balance;
}
/**
* @dev Return total calculated balance
* @return uint balance
*/
function getCalculatedBalance() public view returns (uint) {
return totalBalance;
}
/**
* @dev Get the number of donors
* @return amount of donors
*/
function getDonorCount() public view returns (uint) {
return Donors.length;
}
/**
* @dev Get the address of a donor
* @return address of donor
*/
function getDonorAddress(uint _i) public view returns (address) {
require(_i < Donors.length, "index _i out of bounds");
return Donors[_i];
}
/**
* @dev Get the address and name of a donor
* @param _i index of the address of a donor
* @return _from address of donor
* @return _totalBalance
* @return _numPayments
* @return _name name of donor
*/
function getDonorByIndex(uint _i) public view returns (address _from, uint _totalBalance, uint _numPayments, string memory _name, bytes8 _country) {
require(_i < Donors.length, "Invalid Donor index");
_from = Donors[_i];
_totalBalance = Donations[_from].totalBalance;
_numPayments = Donations[_from].numPayments;
_name = Donations[_from].name;
_country = Donations[_from].country;
}
/**
* @dev Get the number of donors
* @return amount of donors
*/
function getRecipientsCount() public view returns (uint) {
return Recipients.length;
}
/**
* @dev Get the address of a recipient
* @return address of recipient
*/
function getRecipientAddress(uint _i) public view returns (address) {
require(_i < Recipients.length, "index _i out of bounds");
return Recipients[_i];
}
/**
* @dev Get the address and name of a recipient
* @param _i index of the address of a recipient
* @return _recipient address of recipient
* @return _totalBalance
* @return _numPayments
* @return _name name of recipient
*/
function getRecipientByIndex(uint _i) public view returns (address _recipient, uint _totalBalance, uint _numPayments, string memory _name, bytes8 _country) {
require(_i < Recipients.length, "Invalid Recipient index");
_recipient = Recipients[_i];
_totalBalance = Payments[_recipient].totalBalance;
_numPayments = Payments[_recipient].numPayments;
_name = Payments[_recipient].name;
_country = Payments[_recipient].country;
}
/**
* @dev Return Donations from Address
* @param _from Address
* @return Balance
*/
function getDonorBalance(address _from) public view returns (uint) {
return Donations[_from].totalBalance;
}
/**
* @dev Return Donations to Address
* @param _to Address
* @return Balance
*/
function getRecipientBalance(address _to) public view returns (uint) {
return Payments[_to].totalBalance;
}
/**
* @dev Return Donations count from Address
* @param _from Address
* @return number of donations
*/
function getDonationCounts(address _from) public view returns (uint) {
return Donations[_from].numPayments;
}
/**
* @dev Return Payments count to Address
* @param _to Address
* @return number of payments
*/
function getPaymentCounts(address _to) public view returns (uint) {
return Payments[_to].numPayments;
}
/**
* @dev Return Donations from Address name
* @param _from Address
* @return name of donor
*/
function getDonorName(address _from) public view returns (string memory) {
return Donations[_from].name;
}
/**
* @dev Return Donations from Address country
* @param _from Address
* @return country of donor
*/
function getDonorCountry(address _from) public view returns (bytes8) {
return Donations[_from].country;
}
/**
* @dev Return Payments to Address name
* @param _to Address
* @return name of recipient
*/
function getRecipientName(address _to) public view returns (string memory) {
return Payments[_to].name;
}
/**
* @dev Return Payments to Address country
* @param _to Address
* @return country of recipient
*/
function getRecipientCountry(address _to) public view returns (bytes8) {
return Payments[_to].country;
}
/**
* @dev Sets a donor name
* @param _name of donor
*/
function setDonorName(string calldata _name) public {
Donations[msg.sender].name = _name;
}
/**
* @dev Sets a donor country
* @param _country of donor
*/
function setDonorCountry(bytes8 _country) public {
Donations[msg.sender].country = _country;
}
/**
* @dev Sets a recipients name
* @param _name of recipient
*/
function setRecipientName(string calldata _name) public {
Payments[msg.sender].name = _name;
}
/**
* @dev Sets a recipients country
* @param _country of recipient
*/
function setRecipientCountry(bytes8 _country) public {
Payments[msg.sender].country = _country;
}
/**
* @dev Return Donor info
* @param _from Address
* @return _totalBalance
* @return _numPayments
*/
function getDonorByAddress(address _from) public view returns (uint _totalBalance, uint _numPayments, string memory _name, bytes8 _country) {
_totalBalance = getDonorBalance(_from);
_numPayments = getDonationCounts(_from);
_name = getDonorName(_from);
_country = getDonorCountry(_from);
}
/**
* @dev Return Recipient info
* @param _to Address
* @return _totalBalance
* @return _numPayments
*/
function getRecipientByAddress(address _to) public view returns (uint _totalBalance, uint _numPayments, string memory _name, bytes8 _country) {
_totalBalance = getRecipientBalance(_to);
_numPayments = getPaymentCounts(_to);
_name = getRecipientName(_to);
_country = getRecipientCountry(_to);
}
/**
* @dev Return Donation details
* @param _from Address
* @param _nr index
* @return _amount
* @return _withdraw
* @return _timestamp
*/
function getDonationDetails(address _from, uint32 _nr) public view returns (uint _amount, bool _withdraw, uint _timestamp) {
_amount = Donations[_from].payments[_nr].amount;
_withdraw = Donations[_from].payments[_nr].withdraw;
_timestamp = Donations[_from].payments[_nr].timestamp;
}
/**
* @dev Return Payments details
* @param _to Address
* @param _nr index
* @return _amount
* @return _withdraw
* @return _timestamp
*/
function getPaymentDetails(address _to, uint32 _nr) public view returns (uint _amount, bool _withdraw, uint _timestamp) {
_amount = Payments[_to].payments[_nr].amount;
_withdraw = Payments[_to].payments[_nr].withdraw;
_timestamp = Payments[_to].payments[_nr].timestamp;
}
/**
* @dev called to provide funding to contract
* @param _name Name of Recipient
* @param _country emoji flag
*/
function Donation(string memory _name, bytes8 _country) public payable {
require(msg.sender != address(0), "address is null");
require(msg.value > 0, "amount should be greater than 0");
uint64 numPayments;
numPayments = Donations[msg.sender].numPayments.add64(uint64(1));
assert(numPayments > 0);
if (numPayments == 1) {
Donations[msg.sender].index = uint64(Donors.length);
Donors.push(msg.sender);
}
Donations[msg.sender].name = _name;
Donations[msg.sender].country = _country;
Donations[msg.sender].totalBalance = Donations[msg.sender].totalBalance.add(msg.value);
Donations[msg.sender].numPayments = numPayments;
Donations[msg.sender].payments[numPayments].amount = msg.value;
Donations[msg.sender].payments[numPayments].withdraw = false;
Donations[msg.sender].payments[numPayments].timestamp = block.timestamp;
totalBalance = totalBalance.add(msg.value);
emit ReceivedDonation(msg.sender, msg.value, numPayments);
}
/**
* @dev Withdraw money from contract
* @param _to address to send money to
* @param _amount Amount of money to send
*/
function withdrawDonation(address payable _to, uint _amount) public {
require(_to != address(0), "null address supplied");
require(_amount <= Donations[_to].totalBalance, "withdraw amount higher than your Donations");
require(_amount <= getBalance(), "not enough contract funds");
//require(Donations[_to].numPayments + 1 > Donations[_to].numPayments, "uint32 overflow");
uint64 numPayments;
numPayments = Donations[_to].numPayments.add64(uint64(1));
Donations[_to].totalBalance = Donations[_to].totalBalance.sub(_amount);
Donations[_to].numPayments = numPayments;
Donations[_to].payments[numPayments].amount = _amount;
Donations[_to].payments[numPayments].withdraw = true;
Donations[_to].payments[numPayments].timestamp = block.timestamp;
totalBalance = totalBalance.sub(_amount);
_to.transfer(_amount);
emit WithdrawMoney(_to, _amount);
}
/**
* @dev Request a donation from the faucet
* @param _to address to send money to
* @param _amount Amount of money to send
* @param _name Name of Recipient
* @param _country emoji flag
*/
function requestDonation(address payable _to, uint _amount, string memory _name, bytes8 _country) public {
require(_to != address(0), "null address supplied");
require(_amount <= getBalance(), "not enough contract funds");
// allow only 1/10th of funds to pay out
require(_amount <= getBalance().div(10), "amount too high, maximum is one tenth of faucet funds");
//bool AllowTransfer = true;
uint timeLastTransfer = 0; // time of last request
uint64 numPayments;
numPayments = Payments[_to].numPayments.add64(1);
assert(numPayments > 0);
if (numPayments == 1) {
// new Recipient
Payments[_to].index = uint64(Recipients.length);
Recipients.push(_to);
} else if (numPayments == 0) {
revert("Internal error, integer overflow");
} else {
// check if the last payment is more than 12 hours ago
timeLastTransfer = Payments[_to].payments[numPayments.sub64(1)].timestamp;
if (timeLastTransfer > block.timestamp.sub( graceTimeout )) { // 60*60*4
revert("Only one request per 4 hours is possible");
}
}
Payments[_to].name = _name;
Payments[_to].country = _country;
Payments[_to].totalBalance = Payments[_to].totalBalance.add(_amount);
Payments[_to].numPayments = numPayments;
Payments[_to].payments[numPayments].amount = _amount;
Payments[_to].payments[numPayments].withdraw = true;
Payments[_to].payments[numPayments].timestamp = block.timestamp;
totalBalance = totalBalance.sub(_amount);
_to.transfer(_amount);
emit GivenDonation(_to, _amount, numPayments);
}
/**
* @dev Request bootstrap gas from the faucet
* @param _to address to send the gas to
* @param _amount of gas to send
*/
function giveBootstrapGas(address payable _to, uint _amount) public isOwner {
require(_amount <= 0.1 ether, "Max 0.1 NRG is more than enough gas!");
_to.transfer(_amount);
}
}
|
Request bootstrap gas from the faucet _to address to send the gas to _amount of gas to send/
|
function giveBootstrapGas(address payable _to, uint _amount) public isOwner {
require(_amount <= 0.1 ether, "Max 0.1 NRG is more than enough gas!");
_to.transfer(_amount);
}
| 7,321,479
|
// 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: 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: 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
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 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 Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
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);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IDispatcher Interface
/// @author Enzyme Council <[email protected]>
interface IDispatcher {
function cancelMigration(address _vaultProxy, bool _bypassFailure) external;
function claimOwnership() external;
function deployVaultProxy(
address _vaultLib,
address _owner,
address _vaultAccessor,
string calldata _fundName
) external returns (address vaultProxy_);
function executeMigration(address _vaultProxy, bool _bypassFailure) external;
function getCurrentFundDeployer() external view returns (address currentFundDeployer_);
function getFundDeployerForVaultProxy(address _vaultProxy)
external
view
returns (address fundDeployer_);
function getMigrationRequestDetailsForVaultProxy(address _vaultProxy)
external
view
returns (
address nextFundDeployer_,
address nextVaultAccessor_,
address nextVaultLib_,
uint256 executableTimestamp_
);
function getMigrationTimelock() external view returns (uint256 migrationTimelock_);
function getNominatedOwner() external view returns (address nominatedOwner_);
function getOwner() external view returns (address owner_);
function getSharesTokenSymbol() external view returns (string memory sharesTokenSymbol_);
function getTimelockRemainingForMigrationRequest(address _vaultProxy)
external
view
returns (uint256 secondsRemaining_);
function hasExecutableMigrationRequest(address _vaultProxy)
external
view
returns (bool hasExecutableRequest_);
function hasMigrationRequest(address _vaultProxy)
external
view
returns (bool hasMigrationRequest_);
function removeNominatedOwner() external;
function setCurrentFundDeployer(address _nextFundDeployer) external;
function setMigrationTimelock(uint256 _nextTimelock) external;
function setNominatedOwner(address _nextNominatedOwner) external;
function setSharesTokenSymbol(string calldata _nextSymbol) external;
function signalMigration(
address _vaultProxy,
address _nextVaultAccessor,
address _nextVaultLib,
bool _bypassFailure
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IFundDeployer Interface
/// @author Enzyme Council <[email protected]>
interface IFundDeployer {
function getOwner() external view returns (address);
function hasReconfigurationRequest(address) external view returns (bool);
function isAllowedBuySharesOnBehalfCaller(address) external view returns (bool);
function isAllowedVaultCall(
address,
bytes4,
bytes32
) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IIntegrationManager interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for the IntegrationManager
interface IIntegrationManager {
enum SpendAssetsHandleType {None, Approve, Transfer}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../IIntegrationManager.sol";
/// @title Integration Adapter interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for all integration adapters
interface IIntegrationAdapter {
function parseAssetsForAction(
address _vaultProxy,
bytes4 _selector,
bytes calldata _encodedCallArgs
)
external
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.6.12;
import "../../../../infrastructure/price-feeds/derivatives/feeds/CurvePriceFeed.sol";
import "../../../../infrastructure/staking-wrappers/convex-curve-lp/ConvexCurveLpStakingWrapperFactory.sol";
import "../utils/actions/StakingWrapperActionsMixin.sol";
import "../utils/bases/CurveLiquidityAdapterBase.sol";
/// @title ConvexCurveLpStakingAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for staking Curve LP tokens via Convex,
/// with optional combined end-to-end liquidity provision via Curve
/// @dev Rewards tokens are not included as incoming assets for claimRewards()
/// Rationale:
/// - rewards tokens can be claimed to the vault outside of the IntegrationManager, so no need
/// to enforce policy management or emit an event
/// - rewards tokens can be outside of the asset universe, in which case they cannot be tracked
contract ConvexCurveLpStakingAdapter is CurveLiquidityAdapterBase, StakingWrapperActionsMixin {
ConvexCurveLpStakingWrapperFactory private immutable STAKING_WRAPPER_FACTORY_CONTRACT;
CurvePriceFeed private immutable CURVE_PRICE_FEED_CONTRACT;
constructor(
address _integrationManager,
address _curvePriceFeed,
address _wrappedNativeAsset,
address _stakingWrapperFactory,
address _nativeAssetAddress
)
public
CurveLiquidityAdapterBase(_integrationManager, _wrappedNativeAsset, _nativeAssetAddress)
{
CURVE_PRICE_FEED_CONTRACT = CurvePriceFeed(_curvePriceFeed);
STAKING_WRAPPER_FACTORY_CONTRACT = ConvexCurveLpStakingWrapperFactory(
_stakingWrapperFactory
);
}
// EXTERNAL FUNCTIONS
/// @notice Claims all rewards for a given staking token
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _actionData Data specific to this action
function claimRewards(
address _vaultProxy,
bytes calldata _actionData,
bytes calldata
) external onlyIntegrationManager {
__stakingWrapperClaimRewardsFor(__decodeClaimRewardsCallArgs(_actionData), _vaultProxy);
}
/// @notice Lends assets for LP tokens, then stakes the received LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _actionData Data specific to this action
/// @param _assetData Parsed spend assets and incoming assets data for this action
function lendAndStake(
address _vaultProxy,
bytes calldata _actionData,
bytes calldata _assetData
) external onlyIntegrationManager {
(
address pool,
uint256[] memory orderedOutgoingAssetAmounts,
address incomingStakingToken,
uint256 minIncomingStakingTokenAmount,
bool useUnderlyings
) = __decodeLendAndStakeCallArgs(_actionData);
(address[] memory spendAssets, , ) = __decodeAssetData(_assetData);
address lpToken = CURVE_PRICE_FEED_CONTRACT.getLpTokenForPool(pool);
__curveAddLiquidity(
pool,
spendAssets,
orderedOutgoingAssetAmounts,
minIncomingStakingTokenAmount,
useUnderlyings
);
__stakingWrapperStake(
incomingStakingToken,
_vaultProxy,
ERC20(lpToken).balanceOf(address(this)),
lpToken
);
}
/// @notice Stakes LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _actionData Data specific to this action
/// @param _assetData Parsed spend assets and incoming assets data for this action
function stake(
address _vaultProxy,
bytes calldata _actionData,
bytes calldata _assetData
) external onlyIntegrationManager {
(, address incomingStakingToken, uint256 amount) = __decodeStakeCallArgs(_actionData);
(address[] memory spendAssets, , ) = __decodeAssetData(_assetData);
__stakingWrapperStake(incomingStakingToken, _vaultProxy, amount, spendAssets[0]);
}
/// @notice Unstakes LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _actionData Data specific to this action
function unstake(
address _vaultProxy,
bytes calldata _actionData,
bytes calldata
) external onlyIntegrationManager {
(, address outgoingStakingToken, uint256 amount) = __decodeUnstakeCallArgs(_actionData);
__stakingWrapperUnstake(outgoingStakingToken, _vaultProxy, _vaultProxy, amount, false);
}
/// @notice Unstakes LP tokens, then redeems them
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _actionData Data specific to this action
/// @param _assetData Parsed spend assets and incoming assets data for this action
function unstakeAndRedeem(
address _vaultProxy,
bytes calldata _actionData,
bytes calldata _assetData
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _assetData)
{
(
address pool,
address outgoingStakingToken,
uint256 outgoingStakingTokenAmount,
bool useUnderlyings,
RedeemType redeemType,
bytes memory incomingAssetsData
) = __decodeUnstakeAndRedeemCallArgs(_actionData);
__stakingWrapperUnstake(
outgoingStakingToken,
_vaultProxy,
address(this),
outgoingStakingTokenAmount,
false
);
__curveRedeem(
pool,
outgoingStakingTokenAmount,
useUnderlyings,
redeemType,
incomingAssetsData
);
}
/////////////////////////////
// PARSE ASSETS FOR METHOD //
/////////////////////////////
/// @notice Parses the expected assets in a particular action
/// @param _selector The function selector for the callOnIntegration
/// @param _actionData Data specific to this action
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForAction(
address,
bytes4 _selector,
bytes calldata _actionData
)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
if (_selector == CLAIM_REWARDS_SELECTOR) {
return __parseAssetsForClaimRewards();
} else if (_selector == LEND_AND_STAKE_SELECTOR) {
return __parseAssetsForLendAndStake(_actionData);
} else if (_selector == STAKE_SELECTOR) {
return __parseAssetsForStake(_actionData);
} else if (_selector == UNSTAKE_SELECTOR) {
return __parseAssetsForUnstake(_actionData);
} else if (_selector == UNSTAKE_AND_REDEEM_SELECTOR) {
return __parseAssetsForUnstakeAndRedeem(_actionData);
}
revert("parseAssetsForAction: _selector invalid");
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during claimRewards() calls.
/// No action required, all values empty.
function __parseAssetsForClaimRewards()
private
pure
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
return (
IIntegrationManager.SpendAssetsHandleType.None,
new address[](0),
new uint256[](0),
new address[](0),
new uint256[](0)
);
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during lendAndStake() calls
function __parseAssetsForLendAndStake(bytes calldata _actionData)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
(
address pool,
uint256[] memory orderedOutgoingAssetAmounts,
address incomingStakingToken,
uint256 minIncomingStakingTokenAmount,
bool useUnderlyings
) = __decodeLendAndStakeCallArgs(_actionData);
__validatePoolForWrapper(pool, incomingStakingToken);
(spendAssets_, spendAssetAmounts_) = __parseSpendAssetsForLendingCalls(
pool,
orderedOutgoingAssetAmounts,
useUnderlyings
);
incomingAssets_ = new address[](1);
incomingAssets_[0] = incomingStakingToken;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingStakingTokenAmount;
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during stake() calls
function __parseAssetsForStake(bytes calldata _actionData)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
(, address incomingStakingToken, uint256 amount) = __decodeStakeCallArgs(_actionData);
spendAssets_ = new address[](1);
spendAssets_[0] = STAKING_WRAPPER_FACTORY_CONTRACT.getCurveLpTokenForWrapper(
incomingStakingToken
);
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = amount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = incomingStakingToken;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = amount;
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during unstake() calls
function __parseAssetsForUnstake(bytes calldata _actionData)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
(, address outgoingStakingToken, uint256 amount) = __decodeUnstakeCallArgs(_actionData);
spendAssets_ = new address[](1);
spendAssets_[0] = outgoingStakingToken;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = amount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = STAKING_WRAPPER_FACTORY_CONTRACT.getCurveLpTokenForWrapper(
outgoingStakingToken
);
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = amount;
// SpendAssetsHandleType is `Approve`, since staking wrapper allows unstaking on behalf
return (
IIntegrationManager.SpendAssetsHandleType.Approve,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during unstakeAndRedeem() calls
function __parseAssetsForUnstakeAndRedeem(bytes calldata _actionData)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
(
address pool,
address outgoingStakingToken,
uint256 outgoingStakingTokenAmount,
bool useUnderlyings,
RedeemType redeemType,
bytes memory incomingAssetsData
) = __decodeUnstakeAndRedeemCallArgs(_actionData);
__validatePoolForWrapper(pool, outgoingStakingToken);
spendAssets_ = new address[](1);
spendAssets_[0] = outgoingStakingToken;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingStakingTokenAmount;
(incomingAssets_, minIncomingAssetAmounts_) = __parseIncomingAssetsForRedemptionCalls(
pool,
useUnderlyings,
redeemType,
incomingAssetsData
);
// SpendAssetsHandleType is `Approve`, since staking wrapper allows unstaking on behalf
return (
IIntegrationManager.SpendAssetsHandleType.Approve,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Helper to validate a given Curve `pool` for a given convex staking wrapper
function __validatePoolForWrapper(address _pool, address _wrapper) private view {
address lpToken = STAKING_WRAPPER_FACTORY_CONTRACT.getCurveLpTokenForWrapper(_wrapper);
require(
lpToken == CURVE_PRICE_FEED_CONTRACT.getLpTokenForPool(_pool),
"__validatePoolForWrapper: Invalid"
);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../../../utils/AssetHelpers.sol";
import "../IIntegrationAdapter.sol";
import "./IntegrationSelectors.sol";
/// @title AdapterBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice A base contract for integration adapters
abstract contract AdapterBase is IIntegrationAdapter, IntegrationSelectors, AssetHelpers {
using SafeERC20 for ERC20;
address internal immutable INTEGRATION_MANAGER;
/// @dev Provides a standard implementation for transferring incoming assets
/// from an adapter to a VaultProxy at the end of an adapter action
modifier postActionIncomingAssetsTransferHandler(
address _vaultProxy,
bytes memory _assetData
) {
_;
(, , address[] memory incomingAssets) = __decodeAssetData(_assetData);
__pushFullAssetBalances(_vaultProxy, incomingAssets);
}
/// @dev Provides a standard implementation for transferring unspent spend assets
/// from an adapter to a VaultProxy at the end of an adapter action
modifier postActionSpendAssetsTransferHandler(address _vaultProxy, bytes memory _assetData) {
_;
(address[] memory spendAssets, , ) = __decodeAssetData(_assetData);
__pushFullAssetBalances(_vaultProxy, spendAssets);
}
modifier onlyIntegrationManager {
require(
msg.sender == INTEGRATION_MANAGER,
"Only the IntegrationManager can call this function"
);
_;
}
constructor(address _integrationManager) public {
INTEGRATION_MANAGER = _integrationManager;
}
// INTERNAL FUNCTIONS
/// @dev Helper to decode the _assetData param passed to adapter call
function __decodeAssetData(bytes memory _assetData)
internal
pure
returns (
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_
)
{
return abi.decode(_assetData, (address[], uint256[], address[]));
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `INTEGRATION_MANAGER` variable
/// @return integrationManager_ The `INTEGRATION_MANAGER` variable value
function getIntegrationManager() external view returns (address integrationManager_) {
return INTEGRATION_MANAGER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IntegrationSelectors Contract
/// @author Enzyme Council <[email protected]>
/// @notice Selectors for integration actions
/// @dev Selectors are created from their signatures rather than hardcoded for easy verification
abstract contract IntegrationSelectors {
// Trading
bytes4 public constant TAKE_ORDER_SELECTOR = bytes4(
keccak256("takeOrder(address,bytes,bytes)")
);
// Lending
bytes4 public constant LEND_SELECTOR = bytes4(keccak256("lend(address,bytes,bytes)"));
bytes4 public constant REDEEM_SELECTOR = bytes4(keccak256("redeem(address,bytes,bytes)"));
// Staking
bytes4 public constant STAKE_SELECTOR = bytes4(keccak256("stake(address,bytes,bytes)"));
bytes4 public constant UNSTAKE_SELECTOR = bytes4(keccak256("unstake(address,bytes,bytes)"));
// Rewards
bytes4 public constant CLAIM_REWARDS_SELECTOR = bytes4(
keccak256("claimRewards(address,bytes,bytes)")
);
// Combined
bytes4 public constant LEND_AND_STAKE_SELECTOR = bytes4(
keccak256("lendAndStake(address,bytes,bytes)")
);
bytes4 public constant UNSTAKE_AND_REDEEM_SELECTOR = bytes4(
keccak256("unstakeAndRedeem(address,bytes,bytes)")
);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/utils/Strings.sol";
import "../../../../../interfaces/IWETH.sol";
import "../../../../../utils/AssetHelpers.sol";
/// @title CurveLiquidityActionsMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice Mixin contract for interacting with the Curve pool liquidity functions
/// @dev Inheriting contract must have a receive() function if lending or redeeming for the native asset
abstract contract CurveLiquidityActionsMixin is AssetHelpers {
using Strings for uint256;
uint256 private constant ASSET_APPROVAL_TOP_UP_THRESHOLD = 1e76; // Arbitrary, slightly less than 1/11 of max uint256
bytes4 private constant CURVE_REMOVE_LIQUIDITY_ONE_COIN_SELECTOR = 0x1a4d01d2;
bytes4 private constant CURVE_REMOVE_LIQUIDITY_ONE_COIN_USE_UNDERLYINGS_SELECTOR = 0x517a55a3;
address private immutable CURVE_LIQUIDITY_WRAPPED_NATIVE_ASSET;
constructor(address _wrappedNativeAsset) public {
CURVE_LIQUIDITY_WRAPPED_NATIVE_ASSET = _wrappedNativeAsset;
}
/// @dev Helper to add liquidity to the pool.
/// _squashedOutgoingAssets are only those pool assets that are actually used to add liquidity,
/// which can be verbose and ordered, but it is more gas-efficient to only include non-0 amounts.
function __curveAddLiquidity(
address _pool,
address[] memory _squashedOutgoingAssets,
uint256[] memory _orderedOutgoingAssetAmounts,
uint256 _minIncomingLpTokenAmount,
bool _useUnderlyings
) internal {
// Approve and/or unwrap native asset as necessary.
// Rather than using exact amounts for approvals,
// this tops up to max approval if 1/2 max is reached.
uint256 outgoingNativeAssetAmount;
for (uint256 i; i < _squashedOutgoingAssets.length; i++) {
if (_squashedOutgoingAssets[i] == getCurveLiquidityWrappedNativeAsset()) {
// It is never the case that a pool has multiple slots for the same native asset,
// so this is not additive
outgoingNativeAssetAmount = ERC20(getCurveLiquidityWrappedNativeAsset()).balanceOf(
address(this)
);
IWETH(getCurveLiquidityWrappedNativeAsset()).withdraw(outgoingNativeAssetAmount);
} else {
// Once an asset it approved for a given pool, it will almost definitely
// never need approval again, but it is topped up to max once an arbitrary
// threshold is reached
__approveAssetMaxAsNeeded(
_squashedOutgoingAssets[i],
_pool,
ASSET_APPROVAL_TOP_UP_THRESHOLD
);
}
}
// Dynamically call the appropriate selector
(bool success, bytes memory returnData) = _pool.call{value: outgoingNativeAssetAmount}(
__curveAddLiquidityEncodeCalldata(
_orderedOutgoingAssetAmounts,
_minIncomingLpTokenAmount,
_useUnderlyings
)
);
require(success, string(returnData));
}
/// @dev Helper to remove liquidity from the pool.
/// if using _redeemSingleAsset, must pre-validate that one - and only one - asset
/// has a non-zero _orderedMinIncomingAssetAmounts value.
function __curveRemoveLiquidity(
address _pool,
uint256 _outgoingLpTokenAmount,
uint256[] memory _orderedMinIncomingAssetAmounts,
bool _useUnderlyings
) internal {
// Dynamically call the appropriate selector
(bool success, bytes memory returnData) = _pool.call(
__curveRemoveLiquidityEncodeCalldata(
_outgoingLpTokenAmount,
_orderedMinIncomingAssetAmounts,
_useUnderlyings
)
);
require(success, string(returnData));
// Wrap native asset
__curveLiquidityWrapNativeAssetBalance();
}
/// @dev Helper to remove liquidity from the pool and receive all value owed in one specified token
function __curveRemoveLiquidityOneCoin(
address _pool,
uint256 _outgoingLpTokenAmount,
int128 _incomingAssetPoolIndex,
uint256 _minIncomingAssetAmount,
bool _useUnderlyings
) internal {
bytes memory callData;
if (_useUnderlyings) {
callData = abi.encodeWithSelector(
CURVE_REMOVE_LIQUIDITY_ONE_COIN_USE_UNDERLYINGS_SELECTOR,
_outgoingLpTokenAmount,
_incomingAssetPoolIndex,
_minIncomingAssetAmount,
true
);
} else {
callData = abi.encodeWithSelector(
CURVE_REMOVE_LIQUIDITY_ONE_COIN_SELECTOR,
_outgoingLpTokenAmount,
_incomingAssetPoolIndex,
_minIncomingAssetAmount
);
}
// Dynamically call the appropriate selector
(bool success, bytes memory returnData) = _pool.call(callData);
require(success, string(returnData));
// Wrap native asset
__curveLiquidityWrapNativeAssetBalance();
}
// PRIVATE FUNCTIONS
/// @dev Helper to encode calldata for a call to add liquidity on Curve
function __curveAddLiquidityEncodeCalldata(
uint256[] memory _orderedOutgoingAssetAmounts,
uint256 _minIncomingLpTokenAmount,
bool _useUnderlyings
) private pure returns (bytes memory callData_) {
bytes memory finalEncodedArgOrEmpty;
if (_useUnderlyings) {
finalEncodedArgOrEmpty = abi.encode(true);
}
return
abi.encodePacked(
__curveAddLiquidityEncodeSelector(
_orderedOutgoingAssetAmounts.length,
_useUnderlyings
),
abi.encodePacked(_orderedOutgoingAssetAmounts),
_minIncomingLpTokenAmount,
finalEncodedArgOrEmpty
);
}
/// @dev Helper to encode selector for a call to add liquidity on Curve
function __curveAddLiquidityEncodeSelector(uint256 _numberOfCoins, bool _useUnderlyings)
private
pure
returns (bytes4 selector_)
{
string memory finalArgOrEmpty;
if (_useUnderlyings) {
finalArgOrEmpty = ",bool";
}
return
bytes4(
keccak256(
abi.encodePacked(
"add_liquidity(uint256[",
_numberOfCoins.toString(),
"],",
"uint256",
finalArgOrEmpty,
")"
)
)
);
}
/// @dev Helper to wrap the full native asset balance of the current contract
function __curveLiquidityWrapNativeAssetBalance() private {
uint256 nativeAssetBalance = payable(address(this)).balance;
if (nativeAssetBalance > 0) {
IWETH(payable(getCurveLiquidityWrappedNativeAsset())).deposit{
value: nativeAssetBalance
}();
}
}
/// @dev Helper to encode calldata for a call to remove liquidity from Curve
function __curveRemoveLiquidityEncodeCalldata(
uint256 _outgoingLpTokenAmount,
uint256[] memory _orderedMinIncomingAssetAmounts,
bool _useUnderlyings
) private pure returns (bytes memory callData_) {
bytes memory finalEncodedArgOrEmpty;
if (_useUnderlyings) {
finalEncodedArgOrEmpty = abi.encode(true);
}
return
abi.encodePacked(
__curveRemoveLiquidityEncodeSelector(
_orderedMinIncomingAssetAmounts.length,
_useUnderlyings
),
_outgoingLpTokenAmount,
abi.encodePacked(_orderedMinIncomingAssetAmounts),
finalEncodedArgOrEmpty
);
}
/// @dev Helper to encode selector for a call to remove liquidity on Curve
function __curveRemoveLiquidityEncodeSelector(uint256 _numberOfCoins, bool _useUnderlyings)
private
pure
returns (bytes4 selector_)
{
string memory finalArgOrEmpty;
if (_useUnderlyings) {
finalArgOrEmpty = ",bool";
}
return
bytes4(
keccak256(
abi.encodePacked(
"remove_liquidity(uint256,",
"uint256[",
_numberOfCoins.toString(),
"]",
finalArgOrEmpty,
")"
)
)
);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `CURVE_LIQUIDITY_WRAPPED_NATIVE_ASSET` variable
/// @return addressProvider_ The `CURVE_LIQUIDITY_WRAPPED_NATIVE_ASSET` variable value
function getCurveLiquidityWrappedNativeAsset() public view returns (address addressProvider_) {
return CURVE_LIQUIDITY_WRAPPED_NATIVE_ASSET;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../../infrastructure/staking-wrappers/IStakingWrapper.sol";
import "../../../../../utils/AssetHelpers.sol";
/// @title StakingWrapperActionsMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice Mixin contract for interacting with IStakingWrapper implementations
abstract contract StakingWrapperActionsMixin is AssetHelpers {
/// @dev Helper to claim rewards via a IStakingWrapper implementation
function __stakingWrapperClaimRewardsFor(address _wrapper, address _for) internal {
IStakingWrapper(_wrapper).claimRewardsFor(_for);
}
/// @dev Helper to stake via a IStakingWrapper implementation
function __stakingWrapperStake(
address _wrapper,
address _to,
uint256 _amount,
address _outgoingAsset
) internal {
__approveAssetMaxAsNeeded(_outgoingAsset, _wrapper, _amount);
IStakingWrapper(_wrapper).depositTo(_to, _amount);
}
/// @dev Helper to unstake via a IStakingWrapper implementation
function __stakingWrapperUnstake(
address _wrapper,
address _from,
address _to,
uint256 _amount,
bool _claimRewards
) internal {
IStakingWrapper(_wrapper).withdrawToOnBehalf(_from, _to, _amount, _claimRewards);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.6.12;
import "../../../../../interfaces/ICurveLiquidityPool.sol";
import "../actions/CurveLiquidityActionsMixin.sol";
import "../AdapterBase.sol";
/// @title CurveLiquidityAdapterBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice Base adapter for liquidity provision in Curve pools that adhere to pool templates,
/// as well as some old pools that have almost the same required interface (e.g., 3pool).
/// Implementing contracts can allow staking via Curve gauges, Convex, etc.
abstract contract CurveLiquidityAdapterBase is AdapterBase, CurveLiquidityActionsMixin {
enum RedeemType {Standard, OneCoin}
address private immutable CURVE_LIQUIDITY_NATIVE_ASSET_ADDRESS;
constructor(
address _integrationManager,
address _wrappedNativeAsset,
address _nativeAssetAddress
) public AdapterBase(_integrationManager) CurveLiquidityActionsMixin(_wrappedNativeAsset) {
CURVE_LIQUIDITY_NATIVE_ASSET_ADDRESS = _nativeAssetAddress;
}
/// @dev Needed to unwrap and receive the native asset
receive() external payable {}
// INTERNAL FUNCTIONS
/// @dev Helper to return the wrappedNativeAsset if the input is the native asset
function __castWrappedIfNativeAsset(address _tokenOrNativeAsset)
internal
view
returns (address token_)
{
if (_tokenOrNativeAsset == CURVE_LIQUIDITY_NATIVE_ASSET_ADDRESS) {
return getCurveLiquidityWrappedNativeAsset();
}
return _tokenOrNativeAsset;
}
/// @dev Helper to correctly call the relevant redeem function based on RedeemType
function __curveRedeem(
address _pool,
uint256 _outgoingLpTokenAmount,
bool _useUnderlyings,
RedeemType _redeemType,
bytes memory _incomingAssetsData
) internal {
if (_redeemType == RedeemType.OneCoin) {
(
uint256 incomingAssetPoolIndex,
uint256 minIncomingAssetAmount
) = __decodeIncomingAssetsDataRedeemOneCoin(_incomingAssetsData);
__curveRemoveLiquidityOneCoin(
_pool,
_outgoingLpTokenAmount,
int128(incomingAssetPoolIndex),
minIncomingAssetAmount,
_useUnderlyings
);
} else {
__curveRemoveLiquidity(
_pool,
_outgoingLpTokenAmount,
__decodeIncomingAssetsDataRedeemStandard(_incomingAssetsData),
_useUnderlyings
);
}
}
/// @dev Helper function to parse spend assets for redeem() and unstakeAndRedeem() calls
function __parseIncomingAssetsForRedemptionCalls(
address _pool,
bool _useUnderlyings,
RedeemType _redeemType,
bytes memory _incomingAssetsData
)
internal
view
returns (address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_)
{
if (_redeemType == RedeemType.OneCoin) {
(
uint256 incomingAssetPoolIndex,
uint256 minIncomingAssetAmount
) = __decodeIncomingAssetsDataRedeemOneCoin(_incomingAssetsData);
// No need to validate incomingAssetPoolIndex,
// as an out-of-bounds index will fail in the call to Curve
incomingAssets_ = new address[](1);
incomingAssets_[0] = __getPoolAsset(_pool, incomingAssetPoolIndex, _useUnderlyings);
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingAssetAmount;
} else {
minIncomingAssetAmounts_ = __decodeIncomingAssetsDataRedeemStandard(
_incomingAssetsData
);
// No need to validate minIncomingAssetAmounts_.length,
// as an incorrect length will fail with the wrong n_tokens in the call to Curve
incomingAssets_ = new address[](minIncomingAssetAmounts_.length);
for (uint256 i; i < incomingAssets_.length; i++) {
incomingAssets_[i] = __getPoolAsset(_pool, i, _useUnderlyings);
}
}
return (incomingAssets_, minIncomingAssetAmounts_);
}
/// @dev Helper function to parse spend assets for lend() and lendAndStake() calls
function __parseSpendAssetsForLendingCalls(
address _pool,
uint256[] memory _orderedOutgoingAssetAmounts,
bool _useUnderlyings
) internal view returns (address[] memory spendAssets_, uint256[] memory spendAssetAmounts_) {
uint256 spendAssetsCount;
for (uint256 i; i < _orderedOutgoingAssetAmounts.length; i++) {
if (_orderedOutgoingAssetAmounts[i] > 0) {
spendAssetsCount++;
}
}
spendAssets_ = new address[](spendAssetsCount);
spendAssetAmounts_ = new uint256[](spendAssetsCount);
uint256 spendAssetsIndex;
for (uint256 i; i < _orderedOutgoingAssetAmounts.length; i++) {
if (_orderedOutgoingAssetAmounts[i] > 0) {
spendAssets_[spendAssetsIndex] = __getPoolAsset(_pool, i, _useUnderlyings);
spendAssetAmounts_[spendAssetsIndex] = _orderedOutgoingAssetAmounts[i];
spendAssetsIndex++;
if (spendAssetsIndex == spendAssetsCount) {
break;
}
}
}
return (spendAssets_, spendAssetAmounts_);
}
/// @dev Helper to get a pool asset at a given index
function __getPoolAsset(
address _pool,
uint256 _index,
bool _useUnderlying
) internal view returns (address asset_) {
if (_useUnderlying) {
try ICurveLiquidityPool(_pool).underlying_coins(_index) returns (
address underlyingCoin
) {
asset_ = underlyingCoin;
} catch {
asset_ = ICurveLiquidityPool(_pool).underlying_coins(int128(_index));
}
} else {
try ICurveLiquidityPool(_pool).coins(_index) returns (address coin) {
asset_ = coin;
} catch {
asset_ = ICurveLiquidityPool(_pool).coins(int128(_index));
}
}
return __castWrappedIfNativeAsset(asset_);
}
///////////////////////
// ENCODED CALL ARGS //
///////////////////////
// Some of these decodings are not relevant to inheriting contracts,
// and some parameters will be ignored, but this keeps the payloads
// consistent for all inheriting adapters.
/// @dev Helper to decode the encoded call arguments for claiming rewards
function __decodeClaimRewardsCallArgs(bytes memory _actionData)
internal
pure
returns (address stakingToken_)
{
return abi.decode(_actionData, (address));
}
/// @dev Helper to decode the encoded call arguments for lending and then staking
function __decodeLendAndStakeCallArgs(bytes memory _actionData)
internal
pure
returns (
address pool_,
uint256[] memory orderedOutgoingAssetAmounts_,
address incomingStakingToken_,
uint256 minIncomingStakingTokenAmount_,
bool useUnderlyings_
)
{
return abi.decode(_actionData, (address, uint256[], address, uint256, bool));
}
/// @dev Helper to decode the encoded call arguments for lending
function __decodeLendCallArgs(bytes memory _actionData)
internal
pure
returns (
address pool_,
uint256[] memory orderedOutgoingAssetAmounts_,
uint256 minIncomingLpTokenAmount_,
bool useUnderlyings_
)
{
return abi.decode(_actionData, (address, uint256[], uint256, bool));
}
/// @dev Helper to decode the encoded call arguments for redeeming
function __decodeRedeemCallArgs(bytes memory _actionData)
internal
pure
returns (
address pool_,
uint256 outgoingLpTokenAmount_,
bool useUnderlyings_,
RedeemType redeemType_,
bytes memory incomingAssetsData_
)
{
return abi.decode(_actionData, (address, uint256, bool, RedeemType, bytes));
}
/// @dev Helper to decode the encoded incoming assets arguments for RedeemType.OneCoin
function __decodeIncomingAssetsDataRedeemOneCoin(bytes memory _incomingAssetsData)
internal
pure
returns (uint256 incomingAssetPoolIndex_, uint256 minIncomingAssetAmount_)
{
return abi.decode(_incomingAssetsData, (uint256, uint256));
}
/// @dev Helper to decode the encoded incoming assets arguments for RedeemType.Standard
function __decodeIncomingAssetsDataRedeemStandard(bytes memory _incomingAssetsData)
internal
pure
returns (uint256[] memory orderedMinIncomingAssetAmounts_)
{
return abi.decode(_incomingAssetsData, (uint256[]));
}
/// @dev Helper to decode the encoded call arguments for staking
function __decodeStakeCallArgs(bytes memory _actionData)
internal
pure
returns (
address pool_,
address incomingStakingToken_,
uint256 amount_
)
{
return abi.decode(_actionData, (address, address, uint256));
}
/// @dev Helper to decode the encoded call arguments for unstaking and then redeeming
function __decodeUnstakeAndRedeemCallArgs(bytes memory _actionData)
internal
pure
returns (
address pool_,
address outgoingStakingToken_,
uint256 outgoingStakingTokenAmount_,
bool useUnderlyings_,
RedeemType redeemType_,
bytes memory incomingAssetsData_
)
{
return abi.decode(_actionData, (address, address, uint256, bool, RedeemType, bytes));
}
/// @dev Helper to decode the encoded call arguments for unstaking
function __decodeUnstakeCallArgs(bytes memory _actionData)
internal
pure
returns (
address pool_,
address outgoingStakingToken_,
uint256 amount_
)
{
return abi.decode(_actionData, (address, address, uint256));
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IDerivativePriceFeed Interface
/// @author Enzyme Council <[email protected]>
/// @notice Simple interface for derivative price source oracle implementations
interface IDerivativePriceFeed {
function calcUnderlyingValues(address, uint256)
external
returns (address[] memory, uint256[] memory);
function isSupportedAsset(address) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../../../interfaces/ICurveAddressProvider.sol";
import "../../../../interfaces/ICurveLiquidityPool.sol";
import "../../../../interfaces/ICurvePoolOwner.sol";
import "../../../../interfaces/ICurveRegistryMain.sol";
import "../../../../interfaces/ICurveRegistryMetapoolFactory.sol";
import "../../../../utils/FundDeployerOwnerMixin.sol";
import "../IDerivativePriceFeed.sol";
/// @title CurvePriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price feed for Curve pool tokens
contract CurvePriceFeed is IDerivativePriceFeed, FundDeployerOwnerMixin {
using SafeMath for uint256;
event CurvePoolOwnerSet(address poolOwner);
event DerivativeAdded(address indexed derivative, address indexed pool);
event DerivativeRemoved(address indexed derivative);
event InvariantProxyAssetForPoolSet(address indexed pool, address indexed invariantProxyAsset);
event PoolRemoved(address indexed pool);
event ValidatedVirtualPriceForPoolUpdated(address indexed pool, uint256 virtualPrice);
uint256 private constant ADDRESS_PROVIDER_METAPOOL_FACTORY_ID = 3;
uint256 private constant VIRTUAL_PRICE_DEVIATION_DIVISOR = 10000;
uint256 private constant VIRTUAL_PRICE_UNIT = 10**18;
ICurveAddressProvider private immutable ADDRESS_PROVIDER_CONTRACT;
uint256 private immutable VIRTUAL_PRICE_DEVIATION_THRESHOLD;
// We take one asset as representative of the pool's invariant, e.g., WETH for ETH-based pools.
// Caching invariantProxyAssetDecimals in a packed storage slot
// removes an additional external call and cold SLOAD operation during value lookups.
struct PoolInfo {
address invariantProxyAsset; // 20 bytes
uint8 invariantProxyAssetDecimals; // 1 byte
uint88 lastValidatedVirtualPrice; // 11 bytes (could safely be 8-10 bytes)
}
address private curvePoolOwner;
// Pool tokens and liquidity gauge tokens are treated the same for pricing purposes
mapping(address => address) private derivativeToPool;
mapping(address => PoolInfo) private poolToPoolInfo;
// Not necessary for this contract, but used by Curve liquidity adapters
mapping(address => address) private poolToLpToken;
constructor(
address _fundDeployer,
address _addressProvider,
address _poolOwner,
uint256 _virtualPriceDeviationThreshold
) public FundDeployerOwnerMixin(_fundDeployer) {
ADDRESS_PROVIDER_CONTRACT = ICurveAddressProvider(_addressProvider);
VIRTUAL_PRICE_DEVIATION_THRESHOLD = _virtualPriceDeviationThreshold;
__setCurvePoolOwner(_poolOwner);
}
/// @notice Converts a given amount of a derivative to its underlying asset values
/// @param _derivative The derivative to convert
/// @param _derivativeAmount The amount of the derivative to convert
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
address pool = getPoolForDerivative(_derivative);
require(pool != address(0), "calcUnderlyingValues: _derivative is not supported");
PoolInfo memory poolInfo = getPoolInfo(pool);
uint256 virtualPrice = ICurveLiquidityPool(pool).get_virtual_price();
// Validate and update the cached lastValidatedVirtualPrice if:
/// 1. a pool requires virtual price validation, and
/// 2. the unvalidated `virtualPrice` deviates from the PoolInfo.lastValidatedVirtualPrice value
/// by more than the tolerated "deviation threshold" (e.g., 1%).
/// This is an optimization to save gas on validating non-reentrancy during the virtual price query,
/// since the virtual price increases relatively slowly as the pool accrues fees over time.
if (
poolInfo.lastValidatedVirtualPrice > 0 &&
__virtualPriceDiffExceedsThreshold(
virtualPrice,
uint256(poolInfo.lastValidatedVirtualPrice)
)
) {
__updateValidatedVirtualPrice(pool, virtualPrice);
}
underlyings_ = new address[](1);
underlyings_[0] = poolInfo.invariantProxyAsset;
underlyingAmounts_ = new uint256[](1);
if (poolInfo.invariantProxyAssetDecimals == 18) {
underlyingAmounts_[0] = _derivativeAmount.mul(virtualPrice).div(VIRTUAL_PRICE_UNIT);
} else {
underlyingAmounts_[0] = _derivativeAmount
.mul(virtualPrice)
.mul(10**uint256(poolInfo.invariantProxyAssetDecimals))
.div(VIRTUAL_PRICE_UNIT)
.div(VIRTUAL_PRICE_UNIT);
}
return (underlyings_, underlyingAmounts_);
}
/// @notice Checks if an asset is supported by the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is supported
function isSupportedAsset(address _asset) external view override returns (bool isSupported_) {
return getPoolForDerivative(_asset) != address(0);
}
//////////////////////////
// DERIVATIVES REGISTRY //
//////////////////////////
// addPools() is the primary action to add validated lpTokens and gaugeTokens as derivatives.
// addGaugeTokens() can be used to add validated gauge tokens for an already-registered pool.
// addPoolsWithoutValidation() and addGaugeTokensWithoutValidation() can be used as overrides.
// It is possible to remove all pool data and derivatives (separately).
// It is possible to update the invariant proxy asset for any pool.
// It is possible to update whether the pool's virtual price is reenterable.
/// @notice Adds validated gaugeTokens to the price feed
/// @param _gaugeTokens The ordered gauge tokens
/// @param _pools The ordered pools corresponding to _gaugeTokens
/// @dev All params are corresponding, equal length arrays.
/// _pools must already have been added via an addPools~() function
function addGaugeTokens(address[] calldata _gaugeTokens, address[] calldata _pools)
external
onlyFundDeployerOwner
{
ICurveRegistryMain registryContract = __getRegistryMainContract();
ICurveRegistryMetapoolFactory factoryContract = __getRegistryMetapoolFactoryContract();
for (uint256 i; i < _gaugeTokens.length; i++) {
if (factoryContract.get_gauge(_pools[i]) != _gaugeTokens[i]) {
__validateGaugeMainRegistry(_gaugeTokens[i], _pools[i], registryContract);
}
}
__addGaugeTokens(_gaugeTokens, _pools);
}
/// @notice Adds unvalidated gaugeTokens to the price feed
/// @param _gaugeTokens The ordered gauge tokens
/// @param _pools The ordered pools corresponding to _gaugeTokens
/// @dev Should only be used if something is incorrectly failing in the registry validation,
/// or if gauge tokens exist outside of the registries supported by this price feed,
/// e.g., a wrapper for non-tokenized gauges.
/// All params are corresponding, equal length arrays.
/// _pools must already have been added via an addPools~() function.
function addGaugeTokensWithoutValidation(
address[] calldata _gaugeTokens,
address[] calldata _pools
) external onlyFundDeployerOwner {
__addGaugeTokens(_gaugeTokens, _pools);
}
/// @notice Adds validated Curve pool info, lpTokens, and gaugeTokens to the price feed
/// @param _pools The ordered Curve pools
/// @param _invariantProxyAssets The ordered invariant proxy assets corresponding to _pools,
/// e.g., WETH for ETH-based pools
/// @param _reentrantVirtualPrices The ordered flags corresponding to _pools,
/// true if the get_virtual_price() function is potentially reenterable
/// @param _lpTokens The ordered lpToken corresponding to _pools
/// @param _gaugeTokens The ordered gauge token corresponding to _pools
/// @dev All params are corresponding, equal length arrays.
/// address(0) can be used for any _gaugeTokens index to omit the gauge (e.g., no gauge token exists).
/// _lpTokens is not technically necessary since it is knowable from a Curve registry,
/// but it's better to use Curve's upgradable contracts as an input validation rather than fully-trusted.
function addPools(
address[] calldata _pools,
address[] calldata _invariantProxyAssets,
bool[] calldata _reentrantVirtualPrices,
address[] calldata _lpTokens,
address[] calldata _gaugeTokens
) external onlyFundDeployerOwner {
ICurveRegistryMain registryContract = __getRegistryMainContract();
ICurveRegistryMetapoolFactory factoryContract = __getRegistryMetapoolFactoryContract();
for (uint256 i; i < _pools.length; i++) {
// Validate the lpToken and gauge token based on registry
if (_lpTokens[i] == registryContract.get_lp_token(_pools[i])) {
// Main registry
if (_gaugeTokens[i] != address(0)) {
__validateGaugeMainRegistry(_gaugeTokens[i], _pools[i], registryContract);
}
} else if (_lpTokens[i] == _pools[i] && factoryContract.get_n_coins(_pools[i]) > 0) {
// Metapool factory registry
// lpToken and pool are the same address
// get_n_coins() is arbitrarily used to validate the pool is on this registry
if (_gaugeTokens[i] != address(0)) {
__validateGaugeMetapoolFactoryRegistry(
_gaugeTokens[i],
_pools[i],
factoryContract
);
}
} else {
revert("addPools: Invalid inputs");
}
}
__addPools(
_pools,
_invariantProxyAssets,
_reentrantVirtualPrices,
_lpTokens,
_gaugeTokens
);
}
/// @notice Adds unvalidated Curve pool info, lpTokens, and gaugeTokens to the price feed
/// @param _pools The ordered Curve pools
/// @param _invariantProxyAssets The ordered invariant proxy assets corresponding to _pools,
/// e.g., WETH for ETH-based pools
/// @param _reentrantVirtualPrices The ordered flags corresponding to _pools,
/// true if the get_virtual_price() function is potentially reenterable
/// @param _lpTokens The ordered lpToken corresponding to _pools
/// @param _gaugeTokens The ordered gauge token corresponding to _pools
/// @dev Should only be used if something is incorrectly failing in the registry validation,
/// or if pools exist outside of the registries supported by this price feed.
/// All params are corresponding, equal length arrays.
/// address(0) can be used for any _gaugeTokens index to omit the gauge (e.g., no gauge token exists).
function addPoolsWithoutValidation(
address[] calldata _pools,
address[] calldata _invariantProxyAssets,
bool[] calldata _reentrantVirtualPrices,
address[] calldata _lpTokens,
address[] calldata _gaugeTokens
) external onlyFundDeployerOwner {
__addPools(
_pools,
_invariantProxyAssets,
_reentrantVirtualPrices,
_lpTokens,
_gaugeTokens
);
}
/// @notice Removes derivatives from the price feed
/// @param _derivatives The derivatives to remove
/// @dev Unlikely to be needed, just in case of bad storage entry.
/// Can remove both lpToken and gaugeToken from derivatives list,
/// but does not remove lpToken from pool info cache.
function removeDerivatives(address[] calldata _derivatives) external onlyFundDeployerOwner {
for (uint256 i; i < _derivatives.length; i++) {
delete derivativeToPool[_derivatives[i]];
emit DerivativeRemoved(_derivatives[i]);
}
}
/// @notice Removes pools from the price feed
/// @param _pools The pools to remove
/// @dev Unlikely to be needed, just in case of bad storage entry.
/// Does not remove lpToken nor gauge tokens from derivatives list.
function removePools(address[] calldata _pools) external onlyFundDeployerOwner {
for (uint256 i; i < _pools.length; i++) {
delete poolToPoolInfo[_pools[i]];
delete poolToLpToken[_pools[i]];
emit PoolRemoved(_pools[i]);
}
}
/// @notice Sets the Curve pool owner
/// @param _nextPoolOwner The next pool owner value
function setCurvePoolOwner(address _nextPoolOwner) external onlyFundDeployerOwner {
__setCurvePoolOwner(_nextPoolOwner);
}
/// @notice Updates the PoolInfo for the given pools
/// @param _pools The ordered pools
/// @param _invariantProxyAssets The ordered invariant asset proxy assets
/// @param _reentrantVirtualPrices The ordered flags corresponding to _pools,
/// true if the get_virtual_price() function is potentially reenterable
function updatePoolInfo(
address[] calldata _pools,
address[] calldata _invariantProxyAssets,
bool[] calldata _reentrantVirtualPrices
) external onlyFundDeployerOwner {
require(
_pools.length == _invariantProxyAssets.length &&
_pools.length == _reentrantVirtualPrices.length,
"updatePoolInfo: Unequal arrays"
);
for (uint256 i; i < _pools.length; i++) {
__setPoolInfo(_pools[i], _invariantProxyAssets[i], _reentrantVirtualPrices[i]);
}
}
// PRIVATE FUNCTIONS
/// @dev Helper to add a derivative to the price feed
function __addDerivative(address _derivative, address _pool) private {
require(
getPoolForDerivative(_derivative) == address(0),
"__addDerivative: Already exists"
);
// Assert that the assumption that all Curve pool tokens are 18 decimals
require(ERC20(_derivative).decimals() == 18, "__addDerivative: Not 18-decimal");
derivativeToPool[_derivative] = _pool;
emit DerivativeAdded(_derivative, _pool);
}
/// @dev Helper for common logic in addGauges~() functions
function __addGaugeTokens(address[] calldata _gaugeTokens, address[] calldata _pools) private {
require(_gaugeTokens.length == _pools.length, "__addGaugeTokens: Unequal arrays");
for (uint256 i; i < _gaugeTokens.length; i++) {
require(
getLpTokenForPool(_pools[i]) != address(0),
"__addGaugeTokens: Pool not registered"
);
// Not-yet-registered _gaugeTokens[i] tested in __addDerivative()
__addDerivative(_gaugeTokens[i], _pools[i]);
}
}
/// @dev Helper for common logic in addPools~() functions
function __addPools(
address[] calldata _pools,
address[] calldata _invariantProxyAssets,
bool[] calldata _reentrantVirtualPrices,
address[] calldata _lpTokens,
address[] calldata _gaugeTokens
) private {
require(
_pools.length == _invariantProxyAssets.length &&
_pools.length == _reentrantVirtualPrices.length &&
_pools.length == _lpTokens.length &&
_pools.length == _gaugeTokens.length,
"__addPools: Unequal arrays"
);
for (uint256 i; i < _pools.length; i++) {
// Redundant for validated addPools()
require(_lpTokens[i] != address(0), "__addPools: Empty lpToken");
// Empty _pools[i] reverts during __validatePoolCompatibility
// Empty _invariantProxyAssets[i] reverts during __setPoolInfo
// Validate new pool's compatibility with price feed
require(getLpTokenForPool(_pools[i]) == address(0), "__addPools: Already registered");
__validatePoolCompatibility(_pools[i]);
// Register pool info
__setPoolInfo(_pools[i], _invariantProxyAssets[i], _reentrantVirtualPrices[i]);
poolToLpToken[_pools[i]] = _lpTokens[i];
// Add lpToken and gauge token as derivatives
__addDerivative(_lpTokens[i], _pools[i]);
if (_gaugeTokens[i] != address(0)) {
__addDerivative(_gaugeTokens[i], _pools[i]);
}
}
}
/// @dev Helper to get the main Curve registry contract
function __getRegistryMainContract() private view returns (ICurveRegistryMain contract_) {
return ICurveRegistryMain(ADDRESS_PROVIDER_CONTRACT.get_registry());
}
/// @dev Helper to get the Curve metapool factory registry contract
function __getRegistryMetapoolFactoryContract()
private
view
returns (ICurveRegistryMetapoolFactory contract_)
{
return
ICurveRegistryMetapoolFactory(
ADDRESS_PROVIDER_CONTRACT.get_address(ADDRESS_PROVIDER_METAPOOL_FACTORY_ID)
);
}
/// @dev Helper to call a known non-reenterable pool function
function __makeNonReentrantPoolCall(address _pool) private {
ICurvePoolOwner(getCurvePoolOwner()).withdraw_admin_fees(_pool);
}
/// @dev Helper to set the Curve pool owner
function __setCurvePoolOwner(address _nextPoolOwner) private {
curvePoolOwner = _nextPoolOwner;
emit CurvePoolOwnerSet(_nextPoolOwner);
}
/// @dev Helper to set the PoolInfo for a given pool
function __setPoolInfo(
address _pool,
address _invariantProxyAsset,
bool _reentrantVirtualPrice
) private {
uint256 lastValidatedVirtualPrice;
if (_reentrantVirtualPrice) {
// Validate the virtual price by calling a non-reentrant pool function
__makeNonReentrantPoolCall(_pool);
lastValidatedVirtualPrice = ICurveLiquidityPool(_pool).get_virtual_price();
emit ValidatedVirtualPriceForPoolUpdated(_pool, lastValidatedVirtualPrice);
}
poolToPoolInfo[_pool] = PoolInfo({
invariantProxyAsset: _invariantProxyAsset,
invariantProxyAssetDecimals: ERC20(_invariantProxyAsset).decimals(),
lastValidatedVirtualPrice: uint88(lastValidatedVirtualPrice)
});
emit InvariantProxyAssetForPoolSet(_pool, _invariantProxyAsset);
}
/// @dev Helper to update the last validated virtual price for a given pool
function __updateValidatedVirtualPrice(address _pool, uint256 _virtualPrice) private {
// Validate the virtual price by calling a non-reentrant pool function
__makeNonReentrantPoolCall(_pool);
// _virtualPrice is now considered valid
poolToPoolInfo[_pool].lastValidatedVirtualPrice = uint88(_virtualPrice);
emit ValidatedVirtualPriceForPoolUpdated(_pool, _virtualPrice);
}
/// @dev Helper to validate a gauge on the main Curve registry
function __validateGaugeMainRegistry(
address _gauge,
address _pool,
ICurveRegistryMain _mainRegistryContract
) private view {
(address[10] memory gauges, ) = _mainRegistryContract.get_gauges(_pool);
for (uint256 i; i < gauges.length; i++) {
if (_gauge == gauges[i]) {
return;
}
}
revert("__validateGaugeMainRegistry: Invalid gauge");
}
/// @dev Helper to validate a gauge on the Curve metapool factory registry
function __validateGaugeMetapoolFactoryRegistry(
address _gauge,
address _pool,
ICurveRegistryMetapoolFactory _metapoolFactoryRegistryContract
) private view {
require(
_gauge == _metapoolFactoryRegistryContract.get_gauge(_pool),
"__validateGaugeMetapoolFactoryRegistry: Invalid gauge"
);
}
/// @dev Helper to validate a pool's compatibility with the price feed.
/// Pool must implement expected get_virtual_price() function.
function __validatePoolCompatibility(address _pool) private view {
require(
ICurveLiquidityPool(_pool).get_virtual_price() > 0,
"__validatePoolCompatibility: Incompatible"
);
}
/// @dev Helper to check if the difference between lastValidatedVirtualPrice and the current virtual price
/// exceeds the allowed threshold before the current virtual price must be validated and stored
function __virtualPriceDiffExceedsThreshold(
uint256 _currentVirtualPrice,
uint256 _lastValidatedVirtualPrice
) private view returns (bool exceedsThreshold_) {
// Uses the absolute delta between current and last validated virtual prices for the rare
// case where a virtual price might have decreased (e.g., rounding, slashing, yet unknown
// manipulation vector, etc)
uint256 absDiff;
if (_currentVirtualPrice > _lastValidatedVirtualPrice) {
absDiff = _currentVirtualPrice.sub(_lastValidatedVirtualPrice);
} else {
absDiff = _lastValidatedVirtualPrice.sub(_currentVirtualPrice);
}
return
absDiff >
_lastValidatedVirtualPrice.mul(VIRTUAL_PRICE_DEVIATION_THRESHOLD).div(
VIRTUAL_PRICE_DEVIATION_DIVISOR
);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the Curve pool owner
/// @return poolOwner_ The Curve pool owner
function getCurvePoolOwner() public view returns (address poolOwner_) {
return curvePoolOwner;
}
/// @notice Gets the lpToken for a given pool
/// @param _pool The pool
/// @return lpToken_ The lpToken
function getLpTokenForPool(address _pool) public view returns (address lpToken_) {
return poolToLpToken[_pool];
}
/// @notice Gets the stored PoolInfo for a given pool
/// @param _pool The pool
/// @return poolInfo_ The PoolInfo
function getPoolInfo(address _pool) public view returns (PoolInfo memory poolInfo_) {
return poolToPoolInfo[_pool];
}
/// @notice Gets the pool for a given derivative
/// @param _derivative The derivative
/// @return pool_ The pool
function getPoolForDerivative(address _derivative) public view returns (address pool_) {
return derivativeToPool[_derivative];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/// @title IStakingWrapper interface
/// @author Enzyme Council <[email protected]>
interface IStakingWrapper {
struct TotalHarvestData {
uint128 integral;
uint128 lastCheckpointBalance;
}
struct UserHarvestData {
uint128 integral;
uint128 claimableReward;
}
function claimRewardsFor(address _for)
external
returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_);
function deposit(uint256 _amount) external;
function depositTo(address _to, uint256 _amount) external;
function withdraw(uint256 _amount, bool _claimRewards)
external
returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_);
function withdrawTo(
address _to,
uint256 _amount,
bool _claimRewardsToHolder
) external;
function withdrawToOnBehalf(
address _onBehalf,
address _to,
uint256 _amount,
bool _claimRewardsToHolder
) external;
// STATE GETTERS
function getRewardTokenAtIndex(uint256 _index) external view returns (address rewardToken_);
function getRewardTokenCount() external view returns (uint256 count_);
function getRewardTokens() external view returns (address[] memory rewardTokens_);
function getTotalHarvestDataForRewardToken(address _rewardToken)
external
view
returns (TotalHarvestData memory totalHarvestData_);
function getUserHarvestDataForRewardToken(address _user, address _rewardToken)
external
view
returns (UserHarvestData memory userHarvestData_);
function isPaused() external view returns (bool isPaused_);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "../../utils/AddressArrayLib.sol";
import "./IStakingWrapper.sol";
/// @title StakingWrapperBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice A base contract for staking wrappers
/// @dev Can be used as a base for both standard deployments and proxy targets.
/// Draws on Convex's ConvexStakingWrapper implementation (https://github.com/convex-eth/platform/blob/main/contracts/contracts/wrappers/ConvexStakingWrapper.sol),
/// which is based on Curve.fi gauge wrappers (https://github.com/curvefi/curve-dao-contracts/tree/master/contracts/gauges/wrappers)
abstract contract StakingWrapperBase is IStakingWrapper, ERC20, ReentrancyGuard {
using AddressArrayLib for address[];
using SafeERC20 for ERC20;
using SafeMath for uint256;
event Deposited(address indexed from, address indexed to, uint256 amount);
event PauseToggled(bool isPaused);
event RewardsClaimed(
address caller,
address indexed user,
address[] rewardTokens,
uint256[] claimedAmounts
);
event RewardTokenAdded(address token);
event TotalHarvestIntegralUpdated(address indexed rewardToken, uint256 integral);
event TotalHarvestLastCheckpointBalanceUpdated(
address indexed rewardToken,
uint256 lastCheckpointBalance
);
event UserHarvestUpdated(
address indexed user,
address indexed rewardToken,
uint256 integral,
uint256 claimableReward
);
event Withdrawn(
address indexed caller,
address indexed from,
address indexed to,
uint256 amount
);
uint8 private constant DEFAULT_DECIMALS = 18;
uint256 private constant INTEGRAL_PRECISION = 1e18;
address internal immutable OWNER;
// Paused stops new deposits and checkpoints
bool private paused;
address[] private rewardTokens;
mapping(address => TotalHarvestData) private rewardTokenToTotalHarvestData;
mapping(address => mapping(address => UserHarvestData)) private rewardTokenToUserToHarvestData;
modifier onlyOwner() {
require(msg.sender == OWNER, "Only owner callable");
_;
}
constructor(
address _owner,
string memory _tokenName,
string memory _tokenSymbol
) public ERC20(_tokenName, _tokenSymbol) {
OWNER = _owner;
}
/// @notice Toggles pause for deposit and harvesting new rewards
/// @param _isPaused True if next state is paused, false if unpaused
function togglePause(bool _isPaused) external onlyOwner {
paused = _isPaused;
emit PauseToggled(_isPaused);
}
////////////////////////////
// DEPOSITOR INTERACTIONS //
////////////////////////////
// CLAIM REWARDS
/// @notice Claims all rewards for a given account
/// @param _for The account for which to claim rewards
/// @return rewardTokens_ The reward tokens
/// @return claimedAmounts_ The reward token amounts claimed
/// @dev Can be called off-chain to simulate the total harvestable rewards for a particular user
function claimRewardsFor(address _for)
external
override
nonReentrant
returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_)
{
return __checkpointAndClaim(_for);
}
// DEPOSIT
/// @notice Deposits tokens to be staked, minting staking token to sender
/// @param _amount The amount of tokens to deposit
function deposit(uint256 _amount) external override {
__deposit(msg.sender, msg.sender, _amount);
}
/// @notice Deposits tokens to be staked, minting staking token to a specified account
/// @param _to The account to receive staking tokens
/// @param _amount The amount of tokens to deposit
function depositTo(address _to, uint256 _amount) external override {
__deposit(msg.sender, _to, _amount);
}
/// @dev Helper to deposit tokens to be staked
function __deposit(
address _from,
address _to,
uint256 _amount
) private nonReentrant {
require(!isPaused(), "__deposit: Paused");
// Checkpoint before minting
__checkpoint([_to, address(0)]);
_mint(_to, _amount);
__depositLogic(_from, _amount);
emit Deposited(_from, _to, _amount);
}
// WITHDRAWAL
/// @notice Withdraws staked tokens, returning tokens to the sender, and optionally claiming rewards
/// @param _amount The amount of tokens to withdraw
/// @param _claimRewards True if accrued rewards should be claimed
/// @return rewardTokens_ The reward tokens
/// @return claimedAmounts_ The reward token amounts claimed
/// @dev Setting `_claimRewards` to true will save gas over separate calls to withdraw + claim
function withdraw(uint256 _amount, bool _claimRewards)
external
override
returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_)
{
return __withdraw(msg.sender, msg.sender, _amount, _claimRewards);
}
/// @notice Withdraws staked tokens, returning tokens to a specified account,
/// and optionally claims rewards to the staked token holder
/// @param _to The account to receive tokens
/// @param _amount The amount of tokens to withdraw
function withdrawTo(
address _to,
uint256 _amount,
bool _claimRewardsToHolder
) external override {
__withdraw(msg.sender, _to, _amount, _claimRewardsToHolder);
}
/// @notice Withdraws staked tokens on behalf of AccountA, returning tokens to a specified AccountB,
/// and optionally claims rewards to the staked token holder
/// @param _onBehalf The account on behalf to withdraw
/// @param _to The account to receive tokens
/// @param _amount The amount of tokens to withdraw
/// @dev The caller must have an adequate ERC20.allowance() for _onBehalf
function withdrawToOnBehalf(
address _onBehalf,
address _to,
uint256 _amount,
bool _claimRewardsToHolder
) external override {
// Validate and reduce sender approval
_approve(_onBehalf, msg.sender, allowance(_onBehalf, msg.sender).sub(_amount));
__withdraw(_onBehalf, _to, _amount, _claimRewardsToHolder);
}
/// @dev Helper to withdraw staked tokens
function __withdraw(
address _from,
address _to,
uint256 _amount,
bool _claimRewards
)
private
nonReentrant
returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_)
{
// Checkpoint before burning
if (_claimRewards) {
(rewardTokens_, claimedAmounts_) = __checkpointAndClaim(_from);
} else {
__checkpoint([_from, address(0)]);
}
_burn(_from, _amount);
__withdrawLogic(_to, _amount);
emit Withdrawn(msg.sender, _from, _to, _amount);
return (rewardTokens_, claimedAmounts_);
}
/////////////
// REWARDS //
/////////////
// Rewards tokens are added by the inheriting contract. Rewards tokens should be added, but not removed.
// If new rewards tokens need to be added over time, that logic must be handled by the inheriting contract,
// and can make use of __harvestRewardsLogic() if necessary
// INTERNAL FUNCTIONS
/// @dev Helper to add new reward tokens. Silently ignores duplicates.
function __addRewardToken(address _rewardToken) internal {
if (!rewardTokens.contains(_rewardToken)) {
rewardTokens.push(_rewardToken);
emit RewardTokenAdded(_rewardToken);
}
}
// PRIVATE FUNCTIONS
/// @dev Helper to calculate an unaccounted for reward amount due to a user based on integral values
function __calcClaimableRewardForIntegralDiff(
address _account,
uint256 _totalHarvestIntegral,
uint256 _userHarvestIntegral
) private view returns (uint256 claimableReward_) {
return
balanceOf(_account).mul(_totalHarvestIntegral.sub(_userHarvestIntegral)).div(
INTEGRAL_PRECISION
);
}
/// @dev Helper to calculate an unaccounted for integral amount based on checkpoint balance diff
function __calcIntegralForBalDiff(
uint256 _supply,
uint256 _currentBalance,
uint256 _lastCheckpointBalance
) private pure returns (uint256 integral_) {
if (_supply > 0) {
uint256 balDiff = _currentBalance.sub(_lastCheckpointBalance);
if (balDiff > 0) {
return balDiff.mul(INTEGRAL_PRECISION).div(_supply);
}
}
return 0;
}
/// @dev Helper to checkpoint harvest data for specified accounts.
/// Harvests all rewards prior to checkpoint.
function __checkpoint(address[2] memory _accounts) private {
// If paused, continue to checkpoint, but don't attempt to get new rewards
if (!isPaused()) {
__harvestRewardsLogic();
}
uint256 supply = totalSupply();
uint256 rewardTokensLength = rewardTokens.length;
for (uint256 i; i < rewardTokensLength; i++) {
__updateHarvest(rewardTokens[i], _accounts, supply);
}
}
/// @dev Helper to checkpoint harvest data for specified accounts.
/// Harvests all rewards prior to checkpoint.
function __checkpointAndClaim(address _account)
private
returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_)
{
// If paused, continue to checkpoint, but don't attempt to get new rewards
if (!isPaused()) {
__harvestRewardsLogic();
}
uint256 supply = totalSupply();
rewardTokens_ = rewardTokens;
claimedAmounts_ = new uint256[](rewardTokens_.length);
for (uint256 i; i < rewardTokens_.length; i++) {
claimedAmounts_[i] = __updateHarvestAndClaim(rewardTokens_[i], _account, supply);
}
emit RewardsClaimed(msg.sender, _account, rewardTokens_, claimedAmounts_);
return (rewardTokens_, claimedAmounts_);
}
/// @dev Helper to update harvest data
function __updateHarvest(
address _rewardToken,
address[2] memory _accounts,
uint256 _supply
) private {
TotalHarvestData storage totalHarvestData = rewardTokenToTotalHarvestData[_rewardToken];
uint256 totalIntegral = totalHarvestData.integral;
uint256 bal = ERC20(_rewardToken).balanceOf(address(this));
uint256 integralToAdd = __calcIntegralForBalDiff(
_supply,
bal,
totalHarvestData.lastCheckpointBalance
);
if (integralToAdd > 0) {
totalIntegral = totalIntegral.add(integralToAdd);
totalHarvestData.integral = uint128(totalIntegral);
emit TotalHarvestIntegralUpdated(_rewardToken, totalIntegral);
totalHarvestData.lastCheckpointBalance = uint128(bal);
emit TotalHarvestLastCheckpointBalanceUpdated(_rewardToken, bal);
}
for (uint256 i; i < _accounts.length; i++) {
// skip address(0), passed in upon mint and burn
if (_accounts[i] == address(0)) continue;
UserHarvestData storage userHarvestData
= rewardTokenToUserToHarvestData[_rewardToken][_accounts[i]];
uint256 userIntegral = userHarvestData.integral;
if (userIntegral < totalIntegral) {
uint256 claimableReward = uint256(userHarvestData.claimableReward).add(
__calcClaimableRewardForIntegralDiff(_accounts[i], totalIntegral, userIntegral)
);
userHarvestData.claimableReward = uint128(claimableReward);
userHarvestData.integral = uint128(totalIntegral);
emit UserHarvestUpdated(
_accounts[i],
_rewardToken,
totalIntegral,
claimableReward
);
}
}
}
/// @dev Helper to update harvest data and claim all rewards to holder
function __updateHarvestAndClaim(
address _rewardToken,
address _account,
uint256 _supply
) private returns (uint256 claimedAmount_) {
TotalHarvestData storage totalHarvestData = rewardTokenToTotalHarvestData[_rewardToken];
uint256 totalIntegral = totalHarvestData.integral;
uint256 integralToAdd = __calcIntegralForBalDiff(
_supply,
ERC20(_rewardToken).balanceOf(address(this)),
totalHarvestData.lastCheckpointBalance
);
if (integralToAdd > 0) {
totalIntegral = totalIntegral.add(integralToAdd);
totalHarvestData.integral = uint128(totalIntegral);
emit TotalHarvestIntegralUpdated(_rewardToken, totalIntegral);
}
UserHarvestData storage userHarvestData
= rewardTokenToUserToHarvestData[_rewardToken][_account];
uint256 userIntegral = userHarvestData.integral;
claimedAmount_ = userHarvestData.claimableReward;
if (userIntegral < totalIntegral) {
userHarvestData.integral = uint128(totalIntegral);
claimedAmount_ = claimedAmount_.add(
__calcClaimableRewardForIntegralDiff(_account, totalIntegral, userIntegral)
);
emit UserHarvestUpdated(_account, _rewardToken, totalIntegral, claimedAmount_);
}
if (claimedAmount_ > 0) {
userHarvestData.claimableReward = 0;
ERC20(_rewardToken).safeTransfer(_account, claimedAmount_);
emit UserHarvestUpdated(_account, _rewardToken, totalIntegral, 0);
}
// Repeat balance lookup since the reward token could have irregular transfer behavior
uint256 finalBal = ERC20(_rewardToken).balanceOf(address(this));
if (finalBal < totalHarvestData.lastCheckpointBalance) {
totalHarvestData.lastCheckpointBalance = uint128(finalBal);
emit TotalHarvestLastCheckpointBalanceUpdated(_rewardToken, finalBal);
}
return claimedAmount_;
}
////////////////////////////////
// REQUIRED VIRTUAL FUNCTIONS //
////////////////////////////////
/// @dev Logic to be run during a deposit, specific to the integrated protocol.
/// Do not mint staking tokens, which already happens during __deposit().
function __depositLogic(address _onBehalf, uint256 _amount) internal virtual;
/// @dev Logic to be run during a checkpoint to harvest new rewards, specific to the integrated protocol.
/// Can also be used to add new rewards tokens dynamically.
/// Do not checkpoint, only harvest the rewards.
function __harvestRewardsLogic() internal virtual;
/// @dev Logic to be run during a withdrawal, specific to the integrated protocol.
/// Do not burn staking tokens, which already happens during __withdraw().
function __withdrawLogic(address _to, uint256 _amount) internal virtual;
/////////////////////
// ERC20 OVERRIDES //
/////////////////////
/// @notice Gets the token decimals
/// @return decimals_ The token decimals
/// @dev Implementing contracts should override to set different decimals
function decimals() public view virtual override returns (uint8 decimals_) {
return DEFAULT_DECIMALS;
}
/// @dev Overrides ERC20._transfer() in order to checkpoint sender and recipient pre-transfer rewards
function _transfer(
address _from,
address _to,
uint256 _amount
) internal override nonReentrant {
__checkpoint([_from, _to]);
super._transfer(_from, _to, _amount);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the reward token at a particular index
/// @return rewardToken_ The reward token address
function getRewardTokenAtIndex(uint256 _index)
public
view
override
returns (address rewardToken_)
{
return rewardTokens[_index];
}
/// @notice Gets the count of reward tokens being harvested
/// @return count_ The count
function getRewardTokenCount() public view override returns (uint256 count_) {
return rewardTokens.length;
}
/// @notice Gets all reward tokens being harvested
/// @return rewardTokens_ The reward tokens
function getRewardTokens() public view override returns (address[] memory rewardTokens_) {
return rewardTokens;
}
/// @notice Gets the TotalHarvestData for a specified reward token
/// @param _rewardToken The reward token
/// @return totalHarvestData_ The TotalHarvestData
function getTotalHarvestDataForRewardToken(address _rewardToken)
public
view
override
returns (TotalHarvestData memory totalHarvestData_)
{
return rewardTokenToTotalHarvestData[_rewardToken];
}
/// @notice Gets the UserHarvestData for a specified account and reward token
/// @param _user The account
/// @param _rewardToken The reward token
/// @return userHarvestData_ The UserHarvestData
function getUserHarvestDataForRewardToken(address _user, address _rewardToken)
public
view
override
returns (UserHarvestData memory userHarvestData_)
{
return rewardTokenToUserToHarvestData[_rewardToken][_user];
}
/// @notice Checks if deposits and new reward harvesting are paused
/// @return isPaused_ True if paused
function isPaused() public view override returns (bool isPaused_) {
return paused;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./StakingWrapperBase.sol";
/// @title StakingWrapperLibBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice A staking wrapper base for proxy targets, extending StakingWrapperBase
abstract contract StakingWrapperLibBase is StakingWrapperBase {
event TokenNameSet(string name);
event TokenSymbolSet(string symbol);
string private tokenName;
string private tokenSymbol;
/// @dev Helper function to set token name
function __setTokenName(string memory _name) internal {
tokenName = _name;
emit TokenNameSet(_name);
}
/// @dev Helper function to set token symbol
function __setTokenSymbol(string memory _symbol) internal {
tokenSymbol = _symbol;
emit TokenSymbolSet(_symbol);
}
/////////////////////
// ERC20 OVERRIDES //
/////////////////////
/// @notice Gets the token name
/// @return name_ The token name
/// @dev Overrides the constructor-set storage for use in proxies
function name() public view override returns (string memory name_) {
return tokenName;
}
/// @notice Gets the token symbol
/// @return symbol_ The token symbol
/// @dev Overrides the constructor-set storage for use in proxies
function symbol() public view override returns (string memory symbol_) {
return tokenSymbol;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../../../../persistent/dispatcher/IDispatcher.sol";
import "../../../utils/beacon-proxy/BeaconProxyFactory.sol";
import "./ConvexCurveLpStakingWrapperLib.sol";
/// @title ConvexCurveLpStakingWrapperFactory Contract
/// @author Enzyme Council <[email protected]>
/// @notice A contract factory for ConvexCurveLpStakingWrapper instances
contract ConvexCurveLpStakingWrapperFactory is BeaconProxyFactory {
event WrapperDeployed(uint256 indexed pid, address wrapperProxy, address curveLpToken);
IDispatcher private immutable DISPATCHER_CONTRACT;
mapping(uint256 => address) private pidToWrapper;
// Handy cache for interacting contracts
mapping(address => address) private wrapperToCurveLpToken;
modifier onlyOwner {
require(msg.sender == getOwner(), "Only the owner can call this function");
_;
}
constructor(
address _dispatcher,
address _convexBooster,
address _crvToken,
address _cvxToken
) public BeaconProxyFactory(address(0)) {
DISPATCHER_CONTRACT = IDispatcher(_dispatcher);
__setCanonicalLib(
address(
new ConvexCurveLpStakingWrapperLib(
address(this),
_convexBooster,
_crvToken,
_cvxToken
)
)
);
}
/// @notice Deploys a staking wrapper for a given Convex pool
/// @param _pid The Convex Curve pool id
/// @return wrapperProxy_ The staking wrapper proxy contract address
function deploy(uint256 _pid) external returns (address wrapperProxy_) {
require(getWrapperForConvexPool(_pid) == address(0), "deploy: Wrapper already exists");
bytes memory constructData = abi.encodeWithSelector(
ConvexCurveLpStakingWrapperLib.init.selector,
_pid
);
wrapperProxy_ = deployProxy(constructData);
pidToWrapper[_pid] = wrapperProxy_;
address lpToken = ConvexCurveLpStakingWrapperLib(wrapperProxy_).getCurveLpToken();
wrapperToCurveLpToken[wrapperProxy_] = lpToken;
emit WrapperDeployed(_pid, wrapperProxy_, lpToken);
return wrapperProxy_;
}
/// @notice Pause deposits and harvesting new rewards for the given wrappers
/// @param _wrappers The wrappers to pause
function pauseWrappers(address[] calldata _wrappers) external onlyOwner {
for (uint256 i; i < _wrappers.length; i++) {
ConvexCurveLpStakingWrapperLib(_wrappers[i]).togglePause(true);
}
}
/// @notice Unpauses deposits and harvesting new rewards for the given wrappers
/// @param _wrappers The wrappers to unpause
function unpauseWrappers(address[] calldata _wrappers) external onlyOwner {
for (uint256 i; i < _wrappers.length; i++) {
ConvexCurveLpStakingWrapperLib(_wrappers[i]).togglePause(false);
}
}
////////////////////////////////////
// BEACON PROXY FACTORY OVERRIDES //
////////////////////////////////////
/// @notice Gets the contract owner
/// @return owner_ The contract owner
function getOwner() public view override returns (address owner_) {
return DISPATCHER_CONTRACT.getOwner();
}
///////////////////
// STATE GETTERS //
///////////////////
// EXTERNAL FUNCTIONS
/// @notice Gets the Curve LP token address for a given wrapper
/// @param _wrapper The wrapper proxy address
/// @return lpToken_ The Curve LP token address
function getCurveLpTokenForWrapper(address _wrapper) external view returns (address lpToken_) {
return wrapperToCurveLpToken[_wrapper];
}
// PUBLIC FUNCTIONS
/// @notice Gets the wrapper address for a given Convex pool
/// @param _pid The Convex pool id
/// @return wrapper_ The wrapper proxy address
function getWrapperForConvexPool(uint256 _pid) public view returns (address wrapper_) {
return pidToWrapper[_pid];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../../../interfaces/IConvexBaseRewardPool.sol";
import "../../../interfaces/IConvexBooster.sol";
import "../../../interfaces/IConvexVirtualBalanceRewardPool.sol";
import "../StakingWrapperLibBase.sol";
/// @title ConvexCurveLpStakingWrapperLib Contract
/// @author Enzyme Council <[email protected]>
/// @notice A library contract for ConvexCurveLpStakingWrapper instances
contract ConvexCurveLpStakingWrapperLib is StakingWrapperLibBase {
IConvexBooster private immutable CONVEX_BOOSTER_CONTRACT;
address private immutable CRV_TOKEN;
address private immutable CVX_TOKEN;
address private convexPool;
uint256 private convexPoolId;
address private curveLPToken;
constructor(
address _owner,
address _convexBooster,
address _crvToken,
address _cvxToken
) public StakingWrapperBase(_owner, "", "") {
CONVEX_BOOSTER_CONTRACT = IConvexBooster(_convexBooster);
CRV_TOKEN = _crvToken;
CVX_TOKEN = _cvxToken;
}
/// @notice Initializes the proxy
/// @param _pid The Convex pool id for which to use the proxy
function init(uint256 _pid) external {
// Can validate with any variable set here
require(getCurveLpToken() == address(0), "init: Initialized");
IConvexBooster.PoolInfo memory poolInfo = CONVEX_BOOSTER_CONTRACT.poolInfo(_pid);
// Set ERC20 info on proxy
__setTokenName(string(abi.encodePacked("Enzyme Staked: ", ERC20(poolInfo.token).name())));
__setTokenSymbol(string(abi.encodePacked("stk", ERC20(poolInfo.token).symbol())));
curveLPToken = poolInfo.lptoken;
convexPool = poolInfo.crvRewards;
convexPoolId = _pid;
__addRewardToken(CRV_TOKEN);
__addRewardToken(CVX_TOKEN);
addExtraRewards();
setApprovals();
}
/// @notice Adds rewards tokens that have not yet been added to the wrapper
/// @dev Anybody can call, in case more pool tokens are added.
/// Is called prior to every new harvest.
function addExtraRewards() public {
IConvexBaseRewardPool convexPoolContract = IConvexBaseRewardPool(getConvexPool());
// Could probably exit early after validating that extraRewardsCount + 2 <= rewardsTokens.length,
// but this protects against a reward token being removed that still needs to be paid out
uint256 extraRewardsCount = convexPoolContract.extraRewardsLength();
for (uint256 i; i < extraRewardsCount; i++) {
// __addRewardToken silently ignores duplicates
__addRewardToken(
IConvexVirtualBalanceRewardPool(convexPoolContract.extraRewards(i)).rewardToken()
);
}
}
/// @notice Sets necessary ERC20 approvals, as-needed
function setApprovals() public {
ERC20(getCurveLpToken()).safeApprove(address(CONVEX_BOOSTER_CONTRACT), type(uint256).max);
}
////////////////////////////////
// STAKING WRAPPER BASE LOGIC //
////////////////////////////////
/// @dev Logic to be run during a deposit, specific to the integrated protocol.
/// Do not mint staking tokens, which already happens during __deposit().
function __depositLogic(address _from, uint256 _amount) internal override {
ERC20(getCurveLpToken()).safeTransferFrom(_from, address(this), _amount);
CONVEX_BOOSTER_CONTRACT.deposit(convexPoolId, _amount, true);
}
/// @dev Logic to be run during a checkpoint to harvest new rewards, specific to the integrated protocol.
/// Can also be used to add new rewards tokens dynamically.
/// Do not checkpoint, only harvest the rewards.
function __harvestRewardsLogic() internal override {
// It's probably overly-cautious to check rewards on every call,
// but even when the pool has 1 extra reward token (most have 0) it only adds ~10-15k gas units,
// so more convenient to always check than to monitor for rewards changes.
addExtraRewards();
IConvexBaseRewardPool(getConvexPool()).getReward();
}
/// @dev Logic to be run during a withdrawal, specific to the integrated protocol.
/// Do not burn staking tokens, which already happens during __withdraw().
function __withdrawLogic(address _to, uint256 _amount) internal override {
IConvexBaseRewardPool(getConvexPool()).withdrawAndUnwrap(_amount, false);
ERC20(getCurveLpToken()).safeTransfer(_to, _amount);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the associated Convex reward pool address
/// @return convexPool_ The reward pool
function getConvexPool() public view returns (address convexPool_) {
return convexPool;
}
/// @notice Gets the associated Convex reward pool id (pid)
/// @return convexPoolId_ The pid
function getConvexPoolId() public view returns (uint256 convexPoolId_) {
return convexPoolId;
}
/// @notice Gets the associated Curve LP token
/// @return curveLPToken_ The Curve LP token
function getCurveLpToken() public view returns (address curveLPToken_) {
return curveLPToken;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IConvexBaseRewardPool Interface
/// @author Enzyme Council <[email protected]>
interface IConvexBaseRewardPool {
function balanceOf(address) external view returns (uint256);
function extraRewards(uint256) external view returns (address);
function extraRewardsLength() external view returns (uint256);
function getReward() external returns (bool);
function withdraw(uint256, bool) external;
function withdrawAndUnwrap(uint256, bool) external returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/// @title IConvexBooster Interface
/// @author Enzyme Council <[email protected]>
interface IConvexBooster {
struct PoolInfo {
address lptoken;
address token;
address gauge;
address crvRewards;
address stash;
bool shutdown;
}
function deposit(
uint256,
uint256,
bool
) external returns (bool);
function poolInfo(uint256) external view returns (PoolInfo memory);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IConvexVirtualBalanceRewardPool Interface
/// @author Enzyme Council <[email protected]>
interface IConvexVirtualBalanceRewardPool {
function rewardToken() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveAddressProvider interface
/// @author Enzyme Council <[email protected]>
interface ICurveAddressProvider {
function get_address(uint256) external view returns (address);
function get_registry() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveLiquidityPool interface
/// @author Enzyme Council <[email protected]>
interface ICurveLiquidityPool {
function coins(int128) external view returns (address);
function coins(uint256) external view returns (address);
function get_virtual_price() external view returns (uint256);
function underlying_coins(int128) external view returns (address);
function underlying_coins(uint256) external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurvePoolOwner interface
/// @author Enzyme Council <[email protected]>
interface ICurvePoolOwner {
function withdraw_admin_fees(address) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveRegistryMain interface
/// @author Enzyme Council <[email protected]>
/// @notice Limited interface for the Curve Registry contract at ICurveAddressProvider.get_address(0)
interface ICurveRegistryMain {
function get_gauges(address) external view returns (address[10] memory, int128[10] memory);
function get_lp_token(address) external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveRegistryMetapoolFactory interface
/// @author Enzyme Council <[email protected]>
/// @notice Limited interface for the Curve Registry contract at ICurveAddressProvider.get_address(3)
interface ICurveRegistryMetapoolFactory {
function get_gauge(address) external view returns (address);
function get_n_coins(address) external view returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title WETH Interface
/// @author Enzyme Council <[email protected]>
interface IWETH {
function deposit() external payable;
function withdraw(uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title AddressArray Library
/// @author Enzyme Council <[email protected]>
/// @notice A library to extend the address array data type
library AddressArrayLib {
/////////////
// STORAGE //
/////////////
/// @dev Helper to remove an item from a storage array
function removeStorageItem(address[] storage _self, address _itemToRemove)
internal
returns (bool removed_)
{
uint256 itemCount = _self.length;
for (uint256 i; i < itemCount; i++) {
if (_self[i] == _itemToRemove) {
if (i < itemCount - 1) {
_self[i] = _self[itemCount - 1];
}
_self.pop();
removed_ = true;
break;
}
}
return removed_;
}
////////////
// MEMORY //
////////////
/// @dev Helper to add an item to an array. Does not assert uniqueness of the new item.
function addItem(address[] memory _self, address _itemToAdd)
internal
pure
returns (address[] memory nextArray_)
{
nextArray_ = new address[](_self.length + 1);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
nextArray_[_self.length] = _itemToAdd;
return nextArray_;
}
/// @dev Helper to add an item to an array, only if it is not already in the array.
function addUniqueItem(address[] memory _self, address _itemToAdd)
internal
pure
returns (address[] memory nextArray_)
{
if (contains(_self, _itemToAdd)) {
return _self;
}
return addItem(_self, _itemToAdd);
}
/// @dev Helper to verify if an array contains a particular value
function contains(address[] memory _self, address _target)
internal
pure
returns (bool doesContain_)
{
for (uint256 i; i < _self.length; i++) {
if (_target == _self[i]) {
return true;
}
}
return false;
}
/// @dev Helper to merge the unique items of a second array.
/// Does not consider uniqueness of either array, only relative uniqueness.
/// Preserves ordering.
function mergeArray(address[] memory _self, address[] memory _arrayToMerge)
internal
pure
returns (address[] memory nextArray_)
{
uint256 newUniqueItemCount;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
newUniqueItemCount++;
}
}
if (newUniqueItemCount == 0) {
return _self;
}
nextArray_ = new address[](_self.length + newUniqueItemCount);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
uint256 nextArrayIndex = _self.length;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
nextArray_[nextArrayIndex] = _arrayToMerge[i];
nextArrayIndex++;
}
}
return nextArray_;
}
/// @dev Helper to verify if array is a set of unique values.
/// Does not assert length > 0.
function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) {
if (_self.length <= 1) {
return true;
}
uint256 arrayLength = _self.length;
for (uint256 i; i < arrayLength; i++) {
for (uint256 j = i + 1; j < arrayLength; j++) {
if (_self[i] == _self[j]) {
return false;
}
}
}
return true;
}
/// @dev Helper to remove items from an array. Removes all matching occurrences of each item.
/// Does not assert uniqueness of either array.
function removeItems(address[] memory _self, address[] memory _itemsToRemove)
internal
pure
returns (address[] memory nextArray_)
{
if (_itemsToRemove.length == 0) {
return _self;
}
bool[] memory indexesToRemove = new bool[](_self.length);
uint256 remainingItemsCount = _self.length;
for (uint256 i; i < _self.length; i++) {
if (contains(_itemsToRemove, _self[i])) {
indexesToRemove[i] = true;
remainingItemsCount--;
}
}
if (remainingItemsCount == _self.length) {
nextArray_ = _self;
} else if (remainingItemsCount > 0) {
nextArray_ = new address[](remainingItemsCount);
uint256 nextArrayIndex;
for (uint256 i; i < _self.length; i++) {
if (!indexesToRemove[i]) {
nextArray_[nextArrayIndex] = _self[i];
nextArrayIndex++;
}
}
}
return nextArray_;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
/// @title AssetHelpers Contract
/// @author Enzyme Council <[email protected]>
/// @notice A util contract for common token actions
abstract contract AssetHelpers {
using SafeERC20 for ERC20;
using SafeMath for uint256;
/// @dev Helper to aggregate amounts of the same assets
function __aggregateAssetAmounts(address[] memory _rawAssets, uint256[] memory _rawAmounts)
internal
pure
returns (address[] memory aggregatedAssets_, uint256[] memory aggregatedAmounts_)
{
if (_rawAssets.length == 0) {
return (aggregatedAssets_, aggregatedAmounts_);
}
uint256 aggregatedAssetCount = 1;
for (uint256 i = 1; i < _rawAssets.length; i++) {
bool contains;
for (uint256 j; j < i; j++) {
if (_rawAssets[i] == _rawAssets[j]) {
contains = true;
break;
}
}
if (!contains) {
aggregatedAssetCount++;
}
}
aggregatedAssets_ = new address[](aggregatedAssetCount);
aggregatedAmounts_ = new uint256[](aggregatedAssetCount);
uint256 aggregatedAssetIndex;
for (uint256 i; i < _rawAssets.length; i++) {
bool contains;
for (uint256 j; j < aggregatedAssetIndex; j++) {
if (_rawAssets[i] == aggregatedAssets_[j]) {
contains = true;
aggregatedAmounts_[j] += _rawAmounts[i];
break;
}
}
if (!contains) {
aggregatedAssets_[aggregatedAssetIndex] = _rawAssets[i];
aggregatedAmounts_[aggregatedAssetIndex] = _rawAmounts[i];
aggregatedAssetIndex++;
}
}
return (aggregatedAssets_, aggregatedAmounts_);
}
/// @dev Helper to approve a target account with the max amount of an asset.
/// This is helpful for fully trusted contracts, such as adapters that
/// interact with external protocol like Uniswap, Compound, etc.
function __approveAssetMaxAsNeeded(
address _asset,
address _target,
uint256 _neededAmount
) internal {
uint256 allowance = ERC20(_asset).allowance(address(this), _target);
if (allowance < _neededAmount) {
if (allowance > 0) {
ERC20(_asset).safeApprove(_target, 0);
}
ERC20(_asset).safeApprove(_target, type(uint256).max);
}
}
/// @dev Helper to transfer full asset balances from the current contract to a target
function __pushFullAssetBalances(address _target, address[] memory _assets)
internal
returns (uint256[] memory amountsTransferred_)
{
amountsTransferred_ = new uint256[](_assets.length);
for (uint256 i; i < _assets.length; i++) {
ERC20 assetContract = ERC20(_assets[i]);
amountsTransferred_[i] = assetContract.balanceOf(address(this));
if (amountsTransferred_[i] > 0) {
assetContract.safeTransfer(_target, amountsTransferred_[i]);
}
}
return amountsTransferred_;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../core/fund-deployer/IFundDeployer.sol";
/// @title FundDeployerOwnerMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin contract that defers ownership to the owner of FundDeployer
abstract contract FundDeployerOwnerMixin {
address internal immutable FUND_DEPLOYER;
modifier onlyFundDeployerOwner() {
require(
msg.sender == getOwner(),
"onlyFundDeployerOwner: Only the FundDeployer owner can call this function"
);
_;
}
constructor(address _fundDeployer) public {
FUND_DEPLOYER = _fundDeployer;
}
/// @notice Gets the owner of this contract
/// @return owner_ The owner
/// @dev Ownership is deferred to the owner of the FundDeployer contract
function getOwner() public view returns (address owner_) {
return IFundDeployer(FUND_DEPLOYER).getOwner();
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `FUND_DEPLOYER` variable
/// @return fundDeployer_ The `FUND_DEPLOYER` variable value
function getFundDeployer() public view returns (address fundDeployer_) {
return FUND_DEPLOYER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./IBeacon.sol";
/// @title BeaconProxy Contract
/// @author Enzyme Council <[email protected]>
/// @notice A proxy contract that uses the beacon pattern for instant upgrades
contract BeaconProxy {
address private immutable BEACON;
constructor(bytes memory _constructData, address _beacon) public {
BEACON = _beacon;
(bool success, bytes memory returnData) = IBeacon(_beacon).getCanonicalLib().delegatecall(
_constructData
);
require(success, string(returnData));
}
// solhint-disable-next-line no-complex-fallback
fallback() external payable {
address contractLogic = IBeacon(BEACON).getCanonicalLib();
assembly {
calldatacopy(0x0, 0x0, calldatasize())
let success := delegatecall(
sub(gas(), 10000),
contractLogic,
0x0,
calldatasize(),
0,
0
)
let retSz := returndatasize()
returndatacopy(0, 0, retSz)
switch success
case 0 {
revert(0, retSz)
}
default {
return(0, retSz)
}
}
}
receive() external payable {}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./BeaconProxy.sol";
import "./IBeaconProxyFactory.sol";
/// @title BeaconProxyFactory Contract
/// @author Enzyme Council <[email protected]>
/// @notice Factory contract that deploys beacon proxies
abstract contract BeaconProxyFactory is IBeaconProxyFactory {
event CanonicalLibSet(address nextCanonicalLib);
event ProxyDeployed(address indexed caller, address proxy, bytes constructData);
address private canonicalLib;
constructor(address _canonicalLib) public {
__setCanonicalLib(_canonicalLib);
}
/// @notice Deploys a new proxy instance
/// @param _constructData The constructor data with which to call `init()` on the deployed proxy
/// @return proxy_ The proxy address
function deployProxy(bytes memory _constructData) public override returns (address proxy_) {
proxy_ = address(new BeaconProxy(_constructData, address(this)));
emit ProxyDeployed(msg.sender, proxy_, _constructData);
return proxy_;
}
/// @notice Gets the canonical lib used by all proxies
/// @return canonicalLib_ The canonical lib
function getCanonicalLib() public view override returns (address canonicalLib_) {
return canonicalLib;
}
/// @notice Gets the contract owner
/// @return owner_ The contract owner
function getOwner() public view virtual returns (address owner_);
/// @notice Sets the next canonical lib used by all proxies
/// @param _nextCanonicalLib The next canonical lib
function setCanonicalLib(address _nextCanonicalLib) public override {
require(
msg.sender == getOwner(),
"setCanonicalLib: Only the owner can call this function"
);
__setCanonicalLib(_nextCanonicalLib);
}
/// @dev Helper to set the next canonical lib
function __setCanonicalLib(address _nextCanonicalLib) internal {
canonicalLib = _nextCanonicalLib;
emit CanonicalLibSet(_nextCanonicalLib);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IBeacon interface
/// @author Enzyme Council <[email protected]>
interface IBeacon {
function getCanonicalLib() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
import "./IBeacon.sol";
pragma solidity 0.6.12;
/// @title IBeaconProxyFactory interface
/// @author Enzyme Council <[email protected]>
interface IBeaconProxyFactory is IBeacon {
function deployProxy(bytes memory _constructData) external returns (address proxy_);
function setCanonicalLib(address _canonicalLib) external;
}
|
Helper function to parse spend and incoming assets from encoded call args during unstake() calls SpendAssetsHandleType is `Approve`, since staking wrapper allows unstaking on behalf
|
function __parseAssetsForUnstake(bytes calldata _actionData)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
(, address outgoingStakingToken, uint256 amount) = __decodeUnstakeCallArgs(_actionData);
spendAssets_ = new address[](1);
spendAssets_[0] = outgoingStakingToken;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = amount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = STAKING_WRAPPER_FACTORY_CONTRACT.getCurveLpTokenForWrapper(
outgoingStakingToken
);
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = amount;
return (
IIntegrationManager.SpendAssetsHandleType.Approve,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
| 10,237,952
|
/**
*Submitted for verification at Etherscan.io on 2021-04-26
*/
/**
*Submitted for verification at Etherscan.io on 2021-04-26
*/
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns (uint);
function balanceOf(address account) external view returns (uint);
function transfer(address recipient, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint amount) external returns (bool);
function transferFrom(address sender, address recipient, uint amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract Context {
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping (address => uint) private _balances;
mapping (address => mapping (address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns (uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns (uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns (uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns (uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns (uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract SwapBloexToken is ERC20, ERC20Detailed {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint;
IERC20 public btToken;
IERC20 public usdtToken;
address public governance;
uint8 public isOpenDeposit = 1;
uint8 public isOpenWithdraw = 1;
uint public btRate = 2230; //bt founding value
uint constant public rateBase = 10000;
address constant public usdt = address(0xdAC17F958D2ee523a2206206994597C13D831ec7); //Tether USD (USDT)
address constant public bt = address(0x061C266cAF366e73CeA4bdc9DC22392fb81115F2); //Bloex Token (BT)
constructor () public ERC20Detailed("BloexSwap", "BTSwap", 18) {
btToken = IERC20(bt);
usdtToken = IERC20(usdt);
governance = 0x1360CFA0606E5b057df468D540fA81F75d8146E3;
}
function setGovernance(address _governance) public {
require(msg.sender == governance, "!governance");
governance = _governance;
}
//set bt founding value
function setBTRate(uint _btRate) external {
require(msg.sender == governance, "!governance");
btRate = _btRate;
}
function setOpenDeposit(uint8 _isOpenDeposit) external {
require(msg.sender == governance, "!governance");
isOpenDeposit = _isOpenDeposit;
}
function setOpenWithdraw(uint8 _isOpenWithdraw) external {
require(msg.sender == governance, "!governance");
isOpenWithdraw = _isOpenWithdraw;
}
//buy bt with usdt
function deposit(uint _amount) public {
require(isOpenDeposit == 1, "!isOpenDeposit");
// Check usdt balance
require(_amount <= usdtToken.balanceOf(msg.sender), "!sufficient USDT");
//get bt amount
uint bt_amount = _amount.mul(rateBase).div(btRate).mul(1e12); //18 decimals
// Check bt balance
require(bt_amount <= btToken.balanceOf(address(this)), "!sufficient BT");
//deposit usdt
usdtToken.safeTransferFrom(msg.sender, address(this), _amount);
//pay bt
btToken.safeTransfer(msg.sender, bt_amount);
}
//swap bt to usdt
function withdraw(uint _amount) public {
require(isOpenWithdraw == 1, "!isOpenWithdraw");
// Check bt balance
require(_amount <= btToken.balanceOf(msg.sender), "!sufficient BT");
//swap back usdt amount
uint usdt_amount = _amount.mul(btRate).div(rateBase).div(1e12); //6 decimals
// Check usdt balance
require(usdt_amount <= usdtToken.balanceOf(address(this)), "!sufficient USDT");
//withdraw bt
btToken.safeTransferFrom(msg.sender, address(this), _amount);
//pay usdt
usdtToken.safeTransfer(msg.sender, usdt_amount);
}
function depositAll() external {
require(isOpenDeposit == 1, "!isOpenDeposit");
deposit(usdtToken.balanceOf(msg.sender));
}
function withdrawAll() external {
require(isOpenWithdraw == 1, "!isOpenWithdraw");
withdraw(balanceOf(msg.sender));
}
function moveUSDT() public {
require(msg.sender == governance, "!governance");
uint _amount = usdtToken.balanceOf(address(this));
usdtToken.safeTransfer(msg.sender, _amount);
}
function moveBT() public {
require(msg.sender == governance, "!governance");
uint _amount = btToken.balanceOf(address(this));
btToken.safeTransfer(msg.sender, _amount);
}
//bt balanceOf
function balanceOf(address _owner) public view returns (uint256) {
return btToken.balanceOf(_owner);
}
function inCaseTokensGetStuck(address _token, uint _amount) public {
//any erc20
require(msg.sender == governance, "!governance");
IERC20(_token).safeTransfer(governance, _amount);
}
function getPricePerFullShare() public view returns (uint) {
return btRate.mul(1e18).div(rateBase);
}
}
|
swap bt to usdt Check bt balanceswap back usdt amount Check usdt balancewithdraw btpay usdt
|
function withdraw(uint _amount) public {
require(isOpenWithdraw == 1, "!isOpenWithdraw");
require(_amount <= btToken.balanceOf(msg.sender), "!sufficient BT");
require(usdt_amount <= usdtToken.balanceOf(address(this)), "!sufficient USDT");
btToken.safeTransferFrom(msg.sender, address(this), _amount);
usdtToken.safeTransfer(msg.sender, usdt_amount);
}
| 15,187,772
|
/*
Copyright 2020 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;
pragma experimental "ABIEncoderV2";
import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol";
import { ICore } from "../../interfaces/ICore.sol";
import { IWhiteList } from "../../interfaces/IWhiteList.sol";
import { LibBytes } from "../../../external/0x/LibBytes.sol";
import { SetTokenLibrary } from "../../lib/SetTokenLibrary.sol";
/*
* We segmented the FactoryUtils into it's own library to lower RebalancingSetTokenV3Factory
* deployed bytecode size.
*/
library FactoryUtilsLibrary {
using SafeMath for uint256;
using LibBytes for bytes;
struct InitRebalancingParameters {
address manager;
address liquidator;
address feeRecipient;
address rebalanceFeeCalculator;
uint256 rebalanceInterval;
uint256 rebalanceFailPeriod;
uint256 lastRebalanceTimestamp;
uint256 entryFee;
bytes rebalanceFeeCalculatorData;
}
/*
* Performs set calldata validations
*/
function validateRebalanceSetCalldata(
InitRebalancingParameters memory _parameters,
address _liquidatorWhitelist,
address _feeCalculatorWhitelist,
uint256 _minimumRebalanceInterval,
uint256 _minimumFailRebalancePeriod,
uint256 _maximumFailRebalancePeriod
)
public
view
{
require(
_parameters.manager != address(0),
"Null manager"
);
require(
_parameters.lastRebalanceTimestamp <= block.timestamp,
"Bad RebalanceTimestamp"
);
// Require liquidator address is non-zero and is whitelisted by the liquidatorWhitelist
require(
_parameters.liquidator != address(0) &&
IWhiteList(_liquidatorWhitelist).whiteList(_parameters.liquidator),
"Bad liquidator"
);
// Require rebalance fee calculator is whitelisted by the liquidatorWhitelist
require(
IWhiteList(_feeCalculatorWhitelist).whiteList(address(_parameters.rebalanceFeeCalculator)),
"Bad fee calculator"
);
require(
_parameters.rebalanceInterval >= _minimumRebalanceInterval,
"Bad Rebalance interval"
);
require(
_parameters.rebalanceFailPeriod >= _minimumFailRebalancePeriod &&
_parameters.rebalanceFailPeriod <= _maximumFailRebalancePeriod,
"Bad Fail Period"
);
}
/**
* Parses the calldata, which is configured as follows:
*
*
* | CallData | Location |
* |----------------------------|-------------------------------|
* | manager | 32 |
* | liquidator | 64 |
* | feeRecipient | 96 |
* | rebalanceFeeCalculator | 128 |
* | rebalanceInterval | 160 |
* | rebalanceFailPeriod | 192 |
* | entryFee | 224 |
* | rebalanceFeeCalculatorData | 256 to end |
*/
function parseRebalanceSetCallData(
bytes memory _callData
)
public
pure
returns (InitRebalancingParameters memory)
{
InitRebalancingParameters memory parameters;
assembly {
mstore(parameters, mload(add(_callData, 32))) // manager
mstore(add(parameters, 32), mload(add(_callData, 64))) // liquidator
mstore(add(parameters, 64), mload(add(_callData, 96))) // feeRecipient
mstore(add(parameters, 96), mload(add(_callData, 128))) // rebalanceFeeCalculator
mstore(add(parameters, 128), mload(add(_callData, 160))) // rebalanceInterval
mstore(add(parameters, 160), mload(add(_callData, 192))) // rebalanceFailPeriod
mstore(add(parameters, 192), mload(add(_callData, 224))) // lastRebalanceTimestamp
mstore(add(parameters, 224), mload(add(_callData, 256))) // entryFee
}
// Extracts the fee calculator data from the remaining calldata
parameters.rebalanceFeeCalculatorData = _callData.slice(256, _callData.length);
return parameters;
}
function validateRebalancingSet(
SetTokenLibrary.SetDetails memory _setDetails,
address _core,
address _sender,
uint256 _minimumNaturalUnit,
uint256 _maximumNaturalUnit
)
public
view
{
ICore coreInstance = ICore(_core);
require(
_sender == address(coreInstance),
"Must be core"
);
// Ensure component array only includes one address which will be the currentSet
require(
_setDetails.components.length == 1 &&
_setDetails.units.length == 1,
"Components or units len != 1"
);
require(
_setDetails.units[0] > 0,
"UnitShares not > 0"
);
// Expect Set to rebalance to be valid and enabled Set
require(
coreInstance.validSets(_setDetails.components[0]),
"Bad Set"
);
// Natural unit must be within minimum and maximum bounds
require(
_setDetails.naturalUnit >= _minimumNaturalUnit &&
_setDetails.naturalUnit <= _maximumNaturalUnit,
"Bad natural unit"
);
}
}
|
Parses the calldata, which is configured as follows: | CallData | Location | |----------------------------|-------------------------------| | manager | 32 | | liquidator | 64 | | feeRecipient | 96 | | rebalanceFeeCalculator | 128 | | rebalanceInterval | 160 | | rebalanceFailPeriod | 192 | | entryFee | 224 | | rebalanceFeeCalculatorData | 256 to end |/
|
function parseRebalanceSetCallData(
bytes memory _callData
)
public
pure
returns (InitRebalancingParameters memory)
{
InitRebalancingParameters memory parameters;
assembly {
}
return parameters;
}
| 1,765,385
|
./full_match/7700/0x9B2a63F27661A468E2da22226b64A4914144f195/sources/contracts/mixins/TickCensus.sol
|
Encodes the hash key for the terminus neighborhood of the first 16-bits of a tick index. (This is all that's needed to determine terminus.) /
|
function encodeTermWord (bytes32 poolIdx, uint8 lobbyPos, uint8 mezzPos)
private pure returns (bytes32) {
int16 mezzIdx = Bitmaps.weldLobbyMezz
(Bitmaps.uncastBitmapIndex(lobbyPos), mezzPos);
return keccak256(abi.encodePacked(poolIdx, mezzIdx));
}
| 4,651,089
|
./partial_match/1/0x23b75Bc7AaF28e2d6628C3f424B3882F8f072a3c/sources/VITToken.sol
|
Reclaim all ERC20 compatible tokens, but not more than the VIT tokens which were reserved for refunds. token ERC20Basic The address of the token contract.
|
function reclaimToken(ERC20Basic token) external onlyOwner {
uint256 balance = token.balanceOf(this);
if (token == vitToken) {
balance = balance.sub(totalClaimableTokens);
}
assert(token.transfer(owner, balance));
}
| 3,936,255
|
./full_match/4/0x49B9FE0bd344c561fAb9f379D991959E92aE27B4/sources/Sora_mainnet_flat.sol
|
Returns an array of the token names under the owner.
|
function tokenNamesOfOwner(address _owner) external view returns (string[] memory) {
uint tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new string[](0);
string[] memory result = new string[](tokenCount);
for (uint index = 0; index < tokenCount; index++) {
result[index] = tokenNames[tokenOfOwnerByIndex(_owner, index)];
}
return result;
}
}
| 12,280,643
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// 🤛 👁👄👁 🤜 < Let's enjoy Solidity!!
// ----------------------------------------------------------------
// ----------------------------------------------------------------
// ----------------------------------------------------------------
import "@openzeppelin/contracts/utils/Strings.sol";
import "../common/BallcellLiquidBoyaParameters.sol";
import "./BallcellLiquidBoyaImageScript.sol";
// ----------------------------------------------------------------
// ----------------------------------------------------------------
// ----------------------------------------------------------------
contract BallcellLiquidBoyaImage {
uint256 private _passcode = 0;
function settingPasscode(uint256 value) public {
require(_passcode == 0, "already set");
_passcode = value;
}
function svg(BallcellLiquidBoyaParameters.Parameters memory parameters) external view returns (bytes memory) {
require(parameters.passcode == _passcode, "passcode error");
return _svgMain(parameters);
}
function _fixedInt(int256 valueInteger) private pure returns (int256) {
return valueInteger << 64;
}
function _fixedFloat(int256 numeratorInteger, int256 denominatorInteger) private pure returns (int256) {
return (numeratorInteger << 64) / denominatorInteger;
}
function _fixedMul(int256 value1Fixed, int256 value2Fixed) private pure returns (int256) {
return (value1Fixed * value2Fixed) >> 64;
}
function _fixedMulMul(int256 value1Fixed, int256 value2Fixed, int256 value3Fixed) private pure returns (int256) {
return (((value1Fixed * value2Fixed) >> 64) * value3Fixed) >> 64;
}
function _fixedDiv(int256 value1Fixed, int256 value2Fixed) private pure returns (int256) {
return (value1Fixed << 64) / value2Fixed;
}
function _fixedString(int256 valueFixed) private pure returns (string memory) {
if (valueFixed < 0) { return string(abi.encodePacked("-", Strings.toString(uint256(-valueFixed >> 64)))); }
return Strings.toString(uint256(valueFixed >> 64));
}
function _mathDegreesSin(int256 degreesFixed) private pure returns (int256) {
// 度数法から弧度法に変換する
int256 piFixed = _fixedFloat(314159265, 100000000);
int256 radianFixed = _fixedMul(degreesFixed, piFixed) / 180;
// 原点を中心とした1周分に範囲を変換する
int256 radianRangeFixed = (radianFixed % (2 * piFixed) + (3 * piFixed)) % (2 * piFixed) - piFixed;
int256 radianRangeSquaredFixed = _fixedMul(radianRangeFixed, radianRangeFixed);
// テイラー展開を用いて正弦関数を解く
int256 valFixed = radianRangeFixed;
int256 sumFixed = valFixed;
for (uint i = 1; i < 10; i++) {
valFixed = _fixedMul(valFixed, - radianRangeSquaredFixed / int256((2 * i) * (2 * i + 1)));
sumFixed = sumFixed + valFixed;
}
return sumFixed;
}
function _mathDegreesCos(int256 degreesFixed) private pure returns (int256) {
// 三角関数の変換公式を用いて正弦関数の結果から余弦関数を解く
return _mathDegreesSin(_fixedInt(90) - degreesFixed);
// // 度数法から弧度法に変換する
// int256 piFixed = _fixedFloat(314159265, 100000000);
// int256 radianFixed = _fixedMul(degreesFixed, piFixed) / 180;
// // 原点を中心とした1周分に範囲を変換する
// int256 radianRangeFixed = (radianFixed % (2 * piFixed) + (3 * piFixed)) % (2 * piFixed) - piFixed;
// int256 radianRangeSquaredFixed = _fixedMul(radianRangeFixed, radianRangeFixed);
// // テイラー展開を用いて余弦関数を解く
// int256 valFixed = _fixedInt(1);
// int256 sumFixed = valFixed;
// for (uint i = 1; i < 10; i++) {
// valFixed = _fixedMul(valFixed, - radianRangeSquaredFixed / int256((2 * i - 1) * (2 * i)));
// sumFixed = sumFixed + valFixed;
// }
// return sumFixed;
}
function _matCopy(int256[16] memory a, int256[16] memory b) private pure {
for (uint i = 0; i < 16; i++) {
a[i] = b[i];
}
}
function _matIdentity(int256[16] memory a) private pure {
for (uint i = 0; i < 16; i++) { a[i] = 0; }
a[0] = _fixedInt(1);
a[5] = _fixedInt(1);
a[10] = _fixedInt(1);
a[15] = _fixedInt(1);
// a[0] = _fixedInt(1);
// a[1] = 0;
// a[2] = 0;
// a[3] = 0;
// a[4] = 0;
// a[5] = _fixedInt(1);
// a[6] = 0;
// a[7] = 0;
// a[8] = 0;
// a[9] = 0;
// a[10] = _fixedInt(1);
// a[11] = 0;
// a[12] = 0;
// a[13] = 0;
// a[14] = 0;
// a[15] = _fixedInt(1);
}
function _matFrustum(int256[16] memory a) private pure {
for (uint i = 0; i < 16; i++) { a[i] = 0; }
a[0] = _fixedInt(1);
a[5] = _fixedInt(-1);
a[10] = _fixedFloat(-12, 10);
a[11] = _fixedInt(-1);
a[14] = _fixedFloat(-22, 10);
// a[0] = _fixedInt(1);
// a[1] = 0;
// a[2] = 0;
// a[3] = 0;
// a[4] = 0;
// a[5] = _fixedInt(-1);
// a[6] = 0;
// a[7] = 0;
// a[8] = 0;
// a[9] = 0;
// a[10] = _fixedFloat(-12, 10);
// a[11] = _fixedInt(-1);
// a[12] = 0;
// a[13] = 0;
// a[14] = _fixedFloat(-22, 10);
// a[15] = 0;
}
function _matMulTranslate(int256[16] memory a, int256 x, int256 y, int256 z) private pure {
a[12] = _fixedMul(a[0], x) + _fixedMul(a[4], y) + _fixedMul(a[8], z) + a[12];
a[13] = _fixedMul(a[1], x) + _fixedMul(a[5], y) + _fixedMul(a[9], z) + a[13];
a[14] = _fixedMul(a[2], x) + _fixedMul(a[6], y) + _fixedMul(a[10], z) + a[14];
a[15] = _fixedMul(a[3], x) + _fixedMul(a[7], y) + _fixedMul(a[11], z) + a[15];
}
function _matMulDegreesRotBase(int256[16] memory a, int256 r, uint8[8] memory indexes) private pure {
int256 c = _mathDegreesCos(r);
int256 s = _mathDegreesSin(r);
int256[8] memory b;
for (uint i = 0; i < 8; i++) { b[i] = a[indexes[i]]; }
for (uint i = 0; i < 4; i++) {
a[indexes[i + 0]] = _fixedMul(s, b[i + 4]) + _fixedMul(c, b[i + 0]);
a[indexes[i + 4]] = _fixedMul(c, b[i + 4]) - _fixedMul(s, b[i + 0]);
}
}
function _matMulDegreesRotX(int256[16] memory a, int256 r) private pure {
uint8[8] memory indexes = [4, 5, 6, 7, 8, 9, 10, 11];
_matMulDegreesRotBase(a, r, indexes);
// int256 c = _mathDegreesCos(r);
// int256 s = _mathDegreesSin(r);
// int256 a4 = a[4];
// int256 a5 = a[5];
// int256 a6 = a[6];
// int256 a7 = a[7];
// int256 a8 = a[8];
// int256 a9 = a[9];
// int256 a10 = a[10];
// int256 a11 = a[11];
// a[4] = _fixedMul(s, a8) + _fixedMul(c, a4);
// a[5] = _fixedMul(s, a9) + _fixedMul(c, a5);
// a[6] = _fixedMul(s, a10) + _fixedMul(c, a6);
// a[7] = _fixedMul(s, a11) + _fixedMul(c, a7);
// a[8] = _fixedMul(c, a8) - _fixedMul(s, a4);
// a[9] = _fixedMul(c, a9) - _fixedMul(s, a5);
// a[10] = _fixedMul(c, a10) - _fixedMul(s, a6);
// a[11] = _fixedMul(c, a11) - _fixedMul(s, a7);
}
function _matMulDegreesRotY(int256[16] memory a, int256 r) private pure {
uint8[8] memory indexes = [8, 9, 10, 11, 0, 1, 2, 3];
_matMulDegreesRotBase(a, r, indexes);
// int256 c = _mathDegreesCos(r);
// int256 s = _mathDegreesSin(r);
// int256 a8 = a[8];
// int256 a9 = a[9];
// int256 a10 = a[10];
// int256 a11 = a[11];
// int256 a0 = a[0];
// int256 a1 = a[1];
// int256 a2 = a[2];
// int256 a3 = a[3];
// a[8] = _fixedMul(s, a0) + _fixedMul(c, a8);
// a[9] = _fixedMul(s, a1) + _fixedMul(c, a9);
// a[10] = _fixedMul(s, a2) + _fixedMul(c, a10);
// a[11] = _fixedMul(s, a3) + _fixedMul(c, a11);
// a[0] = _fixedMul(c, a0) - _fixedMul(s, a8);
// a[1] = _fixedMul(c, a1) - _fixedMul(s, a9);
// a[2] = _fixedMul(c, a2) - _fixedMul(s, a10);
// a[3] = _fixedMul(c, a3) - _fixedMul(s, a11);
}
function _matMulDegreesRotZ(int256[16] memory a, int256 r) private pure {
uint8[8] memory indexes = [0, 1, 2, 3, 4, 5, 6, 7];
_matMulDegreesRotBase(a, r, indexes);
// int256 c = _mathDegreesCos(r);
// int256 s = _mathDegreesSin(r);
// int256 a0 = a[0];
// int256 a1 = a[1];
// int256 a2 = a[2];
// int256 a3 = a[3];
// int256 a4 = a[4];
// int256 a5 = a[5];
// int256 a6 = a[6];
// int256 a7 = a[7];
// a[0] = _fixedMul(s, a4) + _fixedMul(c, a0);
// a[1] = _fixedMul(s, a5) + _fixedMul(c, a1);
// a[2] = _fixedMul(s, a6) + _fixedMul(c, a2);
// a[3] = _fixedMul(s, a7) + _fixedMul(c, a3);
// a[4] = _fixedMul(c, a4) - _fixedMul(s, a0);
// a[5] = _fixedMul(c, a5) - _fixedMul(s, a1);
// a[6] = _fixedMul(c, a6) - _fixedMul(s, a2);
// a[7] = _fixedMul(c, a7) - _fixedMul(s, a3);
}
struct Variables {
uint n1;
uint n2;
uint n3;
int256 r0Fixed;
int256 r1Fixed;
int256 r2Fixed;
int256 r3Fixed;
string[9] color;
int256 rotFixed;
int256 angFixed;
int256 distFixed;
int256 swingFixed;
int256 thetaFixed;
int256 updownFixed;
int256[16] matrix0;
int256[16] matrix1;
int256[16] matrix2;
int256[16] matrix3;
}
function _svgMain(BallcellLiquidBoyaParameters.Parameters memory parameters) private pure returns (bytes memory) {
Variables memory variables;
variables.n1 = 5;
variables.n2 = 8;
variables.n3 = 8;
variables.r0Fixed = _fixedFloat(int256(parameters.radiusBody), 10);
variables.r1Fixed = _fixedFloat(int256(parameters.radiusFoot), 10);
variables.r2Fixed = _fixedFloat(int256(parameters.radiusHand), 10);
variables.r3Fixed = _fixedFloat(int256(parameters.radiusHead), 10);
variables.color[0] = string(abi.encodePacked("hsl(", Strings.toString(parameters.colorHueBody), ", 100%, ", Strings.toString(parameters.colorLightnessBody), "%)"));
variables.color[1] = string(abi.encodePacked("hsl(", Strings.toString(parameters.colorHueRFoot), ", 100%, ", Strings.toString(parameters.colorLightnessBody), "%)"));
variables.color[2] = string(abi.encodePacked("hsl(", Strings.toString(parameters.colorHueLFoot), ", 100%, ", Strings.toString(parameters.colorLightnessBody), "%)"));
variables.color[3] = string(abi.encodePacked("hsl(", Strings.toString(parameters.colorHueRHand), ", 100%, ", Strings.toString(parameters.colorLightnessBody), "%)"));
variables.color[4] = string(abi.encodePacked("hsl(", Strings.toString(parameters.colorHueLHand), ", 100%, ", Strings.toString(parameters.colorLightnessBody), "%)"));
variables.color[5] = string(abi.encodePacked("hsl(", Strings.toString(parameters.colorHueHead), ", 100%, ", Strings.toString(parameters.colorLightnessBody), "%)"));
variables.color[6] = string(abi.encodePacked("hsl(", Strings.toString(parameters.colorHueREye), ", 100%, ", Strings.toString(parameters.colorLightnessEye), "%)"));
variables.color[7] = string(abi.encodePacked("hsl(", Strings.toString(parameters.colorHueLEye), ", 100%, ", Strings.toString(parameters.colorLightnessEye), "%)"));
variables.color[8] = "black";
int256[5][] memory balls = new int256[5][](variables.n1 + variables.n2 + variables.n3 * 2);
variables.rotFixed = _fixedInt(int256(parameters.rotation) + 120);
variables.angFixed = _fixedInt(int256(parameters.angle) - 45);
variables.distFixed = _fixedInt(int256(parameters.distance) * 2 + 4);
variables.swingFixed = _mathDegreesSin(9 * _fixedInt(int256(parameters.swing)));
variables.thetaFixed = 30 * variables.swingFixed;
variables.updownFixed = _fixedMul(_fixedFloat(3, 10), variables.swingFixed < 0 ? -variables.swingFixed : variables.swingFixed);
// 胴体
_matIdentity(variables.matrix0);
balls[0][0] = 0;
balls[0][1] = 0;
balls[0][2] = 0;
balls[0][3] = variables.r0Fixed;
balls[0][4] = 0;
// 両足
for (uint i = 0; i < 2; i++) {
uint index = 1 + i;
int256 sign = (i == 0 ? int256(1) : int256(-1));
_matCopy(variables.matrix1, variables.matrix0);
_matMulDegreesRotZ(variables.matrix1, _fixedInt(30) * sign);
_matMulDegreesRotX(variables.matrix1, -variables.thetaFixed * sign);
_matMulTranslate(variables.matrix1, 0, -(variables.r0Fixed + variables.r1Fixed * 7 / 10), 0);
balls[index][0] = variables.matrix1[12];
balls[index][1] = variables.matrix1[13];
balls[index][2] = variables.matrix1[14];
balls[index][3] = variables.r1Fixed;
balls[index][4] = int256(index);
}
// 両手
for (uint i = 0; i < 2; i++) {
uint index = 3 + i;
int256 sign = (i == 0 ? int256(1) : int256(-1));
_matCopy(variables.matrix1, variables.matrix0);
_matMulDegreesRotY(variables.matrix1, variables.thetaFixed);
_matMulTranslate(variables.matrix1, (variables.r0Fixed + variables.r2Fixed * 5 / 10) * sign, 0, 0);
balls[index][0] = variables.matrix1[12];
balls[index][1] = variables.matrix1[13];
balls[index][2] = variables.matrix1[14];
balls[index][3] = variables.r2Fixed;
balls[index][4] = int256(index);
}
// 頭
_matCopy(variables.matrix1, variables.matrix0);
_matMulDegreesRotX(variables.matrix1, _fixedInt(-30));
_matMulTranslate(variables.matrix1, 0, (variables.r0Fixed + variables.r3Fixed * 7 / 10), 0);
_matMulDegreesRotX(variables.matrix1, _fixedInt(30));
_matCopy(variables.matrix2, variables.matrix1);
_matMulDegreesRotX(variables.matrix2, _fixedInt(150));
for (uint i = 0; i < variables.n2; i++) {
uint index = variables.n1 + i;
int256 numerator = int256(i);
int256 denominator = int256(variables.n2 - 1);
int256 t = _fixedFloat(numerator, denominator);
int256 r = variables.r3Fixed;
_matCopy(variables.matrix3, variables.matrix2);
_matMulTranslate(variables.matrix3, 0, 0, _fixedMulMul(_fixedFloat(-1333, 1000), r, t));
balls[index][0] = variables.matrix3[12];
balls[index][1] = variables.matrix3[13];
balls[index][2] = variables.matrix3[14];
balls[index][3] = _fixedMul(variables.r3Fixed, (_fixedInt(3) - 2 * t) / 3);
balls[index][4] = 5;
}
// 両目
for (uint i = 0; i < 2; i++) {
int256 sign = (i == 0 ? int256(1) : int256(-1));
_matCopy(variables.matrix2, variables.matrix1);
_matMulDegreesRotY(variables.matrix2, _fixedInt(-15) * sign);
_matMulTranslate(variables.matrix2, 0, 0, variables.r3Fixed * - 8 / 10);
for (uint j = 0; j < variables.n3; j++) {
uint index = variables.n1 + variables.n2 + variables.n3 * i + j;
int256 numerator = int256(j);
int256 denominator = int256(variables.n3 - 1);
int256 t = _fixedFloat(numerator, denominator) - _fixedFloat(5, 10);
_matCopy(variables.matrix3, variables.matrix2);
_matMulTranslate(variables.matrix3, 0, _fixedMulMul(variables.r3Fixed, _fixedFloat(6, 10), t), 0);
balls[index][0] = variables.matrix3[12];
balls[index][1] = variables.matrix3[13];
balls[index][2] = variables.matrix3[14];
balls[index][3] = variables.r3Fixed / 6;
balls[index][4] = 6 + int256(i);
}
}
// 高さ調整
int256 offsetFixed = 0;
for (uint i = 0; i < balls.length; i++) {
int256 value = balls[i][1] - balls[i][3];
if (offsetFixed > value) { offsetFixed = value; }
}
for (uint i = 0; i < balls.length; i++) { balls[i][1] = balls[i][1] + variables.updownFixed - offsetFixed; }
// 位置計算
_matFrustum(variables.matrix0);
_matMulTranslate(variables.matrix0, 0, 0, -variables.distFixed);
_matMulDegreesRotX(variables.matrix0, variables.angFixed);
_matMulDegreesRotY(variables.matrix0, variables.rotFixed);
_matMulTranslate(variables.matrix0, 0, _fixedFloat(-14, 10), 0);
for (uint i = 0; i < balls.length; i++) {
_matCopy(variables.matrix1, variables.matrix0);
_matMulTranslate(variables.matrix1, balls[i][0], balls[i][1], balls[i][2]);
balls[i][0] = _fixedDiv(variables.matrix1[12], variables.matrix1[15]);
balls[i][1] = _fixedDiv(variables.matrix1[13], variables.matrix1[15]);
balls[i][2] = _fixedDiv(variables.matrix1[14], variables.matrix1[15]);
balls[i][3] = _fixedDiv(balls[i][3], variables.matrix1[15]);
}
// バブルソートで並べ替え
uint[] memory sortedIndexes = new uint[](balls.length);
for (uint i = 0; i < sortedIndexes.length; i++) { sortedIndexes[i] = i; }
for (uint i = 0; i < sortedIndexes.length; i++) {
for (uint j = 0; j < sortedIndexes.length - i - 1; j++) {
uint temp0 = sortedIndexes[j + 0];
uint temp1 = sortedIndexes[j + 1];
int256 z0 = balls[temp0][2];
int256 z1 = balls[temp1][2];
if (z1 > z0) {
sortedIndexes[j + 0] = temp1;
sortedIndexes[j + 1] = temp0;
}
}
}
// svg作成
bytes memory temporary = '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 350 350">';
temporary = abi.encodePacked(temporary, _svgBackground(parameters));
temporary = abi.encodePacked(temporary, '<g id="balls">');
for (uint i = 0; i < 2; i++) {
for (uint j = 0; j < sortedIndexes.length; j++) {
int256 x = (2 * balls[sortedIndexes[j]][0] + _fixedFloat(5, 10)) * 350;
int256 y = (2 * balls[sortedIndexes[j]][1] + _fixedFloat(5, 10)) * 350;
int256 r = (2 * balls[sortedIndexes[j]][3] * 350) + _fixedInt(i == 0 ? int256(16) : int256(0));
uint color = i == 0 ? 8 : uint(balls[sortedIndexes[j]][4]);
temporary = abi.encodePacked(temporary,
"<circle",
' cx="', _fixedString(x), '"',
' cy="', _fixedString(y), '"',
' r="', _fixedString(r), '"',
' fill="', variables.color[color], '"',
"></circle>"
);
}
}
temporary = abi.encodePacked(temporary, "</g>");
temporary = abi.encodePacked(temporary, _svgForeground(parameters));
temporary = abi.encodePacked(temporary, _svgScript(parameters));
return abi.encodePacked(temporary, "</svg>");
}
function _svgBackground(BallcellLiquidBoyaParameters.Parameters memory parameters) private pure returns (bytes memory) {
string memory color = string(abi.encodePacked("hsl(", Strings.toString(parameters.backgroundColor), ", 100%, 50%)"));
if (parameters.backgroundType == BallcellLiquidBoyaParameters.BackgroundType.Single) {
return abi.encodePacked('<rect x="25" y="25" width="300" height="300" fill="', color, '"></rect>');
} else if (parameters.backgroundType == BallcellLiquidBoyaParameters.BackgroundType.Circle) {
string memory width = Strings.toString(160 + parameters.backgroundRandom % 50);
bytes memory temporary = '<defs><mask id="mask">';
temporary = abi.encodePacked(temporary, '<circle cx="175" cy="175" r="', width, '" fill="white"></circle>');
temporary = abi.encodePacked(temporary, '<circle cx="175" cy="175" r="150" fill="black"></circle>');
temporary = abi.encodePacked(temporary, "</mask></defs>");
return abi.encodePacked(temporary, '<rect x="25" y="25" width="300" height="300" fill="', color, '" mask="url(#mask)" />');
} else if (parameters.backgroundType == BallcellLiquidBoyaParameters.BackgroundType.PolkaDot) {
uint typePolkaDot = parameters.backgroundRandom % 3;
uint8[4] memory radius;
if (typePolkaDot == 0) { radius = [20, 20, 20, 20]; }
if (typePolkaDot == 1) { radius = [30, 10, 10, 20]; }
if (typePolkaDot == 2) { radius = [40, 5, 5, 20]; }
bytes memory temporary = '<defs><mask id="mask">';
temporary = abi.encodePacked(temporary, '<rect x="25" y="25" width="300" height="300" fill="white" />');
temporary = abi.encodePacked(temporary, "</mask></defs>");
temporary = abi.encodePacked(temporary, '<g mask="url(#mask)">');
for (uint i = 0; i < 5; i++) {
for (uint j = 0; j < 5; j++) {
uint index = (j % 2) + ((i % 2) << 1);
string memory x = Strings.toString(25 + 75 * j);
string memory y = Strings.toString(25 + 75 * i);
string memory r = Strings.toString(radius[index]);
temporary = abi.encodePacked(temporary, '<circle cx="', x, '" cy="', y, '" r="', r, '" fill="', color, '"></circle>');
}
}
return abi.encodePacked(temporary, "</g>");
}
return "";
}
function _svgForeground(BallcellLiquidBoyaParameters.Parameters memory parameters) private pure returns (bytes memory) {
if (parameters.revealed) { return ""; }
bytes memory temporary = '<text';
temporary = abi.encodePacked(temporary, ' x="175"');
temporary = abi.encodePacked(temporary, ' y="175"');
temporary = abi.encodePacked(temporary, ' fill="black"');
temporary = abi.encodePacked(temporary, ' stroke="white"');
temporary = abi.encodePacked(temporary, ' text-anchor="middle"');
temporary = abi.encodePacked(temporary, ' dominant-baseline="central"');
temporary = abi.encodePacked(temporary, ' font-size="128"');
return abi.encodePacked(temporary, ">?</text>");
}
function _svgScript(BallcellLiquidBoyaParameters.Parameters memory parameters) private pure returns (bytes memory) {
if (!parameters.revealed) { return ""; }
uint16[18] memory array = BallcellLiquidBoyaParameters.createArray(parameters);
bytes memory temporary = "<script><![CDATA[";
temporary = abi.encodePacked(temporary, BallcellLiquidBoyaImageScript.code);
temporary = abi.encodePacked(temporary, "window.setTimeout(() => startPuppet(");
temporary = abi.encodePacked(temporary, 'document.getElementById("balls").getElementsByTagName("circle")');
temporary = abi.encodePacked(temporary, ",[");
for (uint i = 0; i < array.length; i++) { temporary = abi.encodePacked(temporary, Strings.toString(array[i]), ","); }
temporary = abi.encodePacked(temporary, "]), 1000);");
return abi.encodePacked(temporary, "]]></script>");
}
}
// ----------------------------------------------------------------
// ----------------------------------------------------------------
// ----------------------------------------------------------------
// 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;
// 🤛 👁👄👁 🤜 < Let's enjoy Solidity!!
// ----------------------------------------------------------------
// ----------------------------------------------------------------
// ----------------------------------------------------------------
library BallcellLiquidBoyaParameters {
struct Parameters {
bool revealed;
uint256 tokenId;
uint256 passcode;
uint256 rotation;
uint256 angle;
uint256 distance;
uint256 swing;
uint256 radiusBody;
uint256 radiusFoot;
uint256 radiusHand;
uint256 radiusHead;
uint256 colorHueBody;
uint256 colorHueRFoot;
uint256 colorHueLFoot;
uint256 colorHueRHand;
uint256 colorHueLHand;
uint256 colorHueHead;
uint256 colorHueREye;
uint256 colorHueLEye;
uint256 colorLightnessBody;
uint256 colorLightnessEye;
bool colorFlagOne;
ColorTypeBody colorTypeBody;
ColorTypeEye colorTypeEye;
BackgroundType backgroundType;
uint256 backgroundColor;
uint256 backgroundRandom;
}
enum ColorTypeBody { Neutral, Bright, Dark }
enum ColorTypeEye { Monotone, Single, Double }
enum BackgroundType { None, Single, Circle, PolkaDot, GradationLinear, Lgbt }
uint constant _keyRotation = 0;
uint constant _keyAngle = 1;
uint constant _keyDistance = 2;
uint constant _keySwing = 3;
uint constant _keyRadiusBody = 4;
uint constant _keyRadiusFoot = 5;
uint constant _keyRadiusHand = 6;
uint constant _keyRadiusHead = 7;
uint constant _keyColorHueBody = 8;
uint constant _keyColorHueRFoot = 9;
uint constant _keyColorHueLFoot = 10;
uint constant _keyColorHueRHand = 11;
uint constant _keyColorHueLHand = 12;
uint constant _keyColorHueHead = 13;
uint constant _keyColorHueREye = 14;
uint constant _keyColorHueLEye = 15;
uint constant _keyColorLightnessBody = 16;
uint constant _keyColorLightnessEye = 17;
function createArray(Parameters memory parameters) internal pure returns (uint16[18] memory) {
uint16[18] memory array;
array[_keyRotation] = uint16(parameters.rotation);
array[_keyAngle] = uint16(parameters.angle);
array[_keyDistance] = uint16(parameters.distance);
array[_keySwing] = uint16(parameters.swing);
array[_keyRadiusBody] = uint16(parameters.radiusBody);
array[_keyRadiusFoot] = uint16(parameters.radiusFoot);
array[_keyRadiusHand] = uint16(parameters.radiusHand);
array[_keyRadiusHead] = uint16(parameters.radiusHead);
array[_keyColorHueBody] = uint16(parameters.colorHueBody);
array[_keyColorHueRFoot] = uint16(parameters.colorHueRFoot);
array[_keyColorHueLFoot] = uint16(parameters.colorHueLFoot);
array[_keyColorHueRHand] = uint16(parameters.colorHueRHand);
array[_keyColorHueLHand] = uint16(parameters.colorHueLHand);
array[_keyColorHueHead] = uint16(parameters.colorHueHead);
array[_keyColorHueREye] = uint16(parameters.colorHueREye);
array[_keyColorHueLEye] = uint16(parameters.colorHueLEye);
array[_keyColorLightnessBody] = uint16(parameters.colorLightnessBody);
array[_keyColorLightnessEye] = uint16(parameters.colorLightnessEye);
return array;
}
}
// ----------------------------------------------------------------
// ----------------------------------------------------------------
// ----------------------------------------------------------------
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// ----------------------------------------------------------------
// ----------------------------------------------------------------
// ----------------------------------------------------------------
library BallcellLiquidBoyaImageScript {
string constant code = '"use strict";window.startPuppet=(()=>{let t=(t,e)=>e.forEach(((e,l)=>t[l]=e)),e=(t,e,l,r)=>Array(4).fill(0).map(((o,h)=>t[12+h]=t[0+h]*e+t[4+h]*l+t[8+h]*r+t[12+h])),l=(t,e)=>h(t,e,[4,5,6,7,8,9,10,11]),r=(t,e)=>h(t,e,[8,9,10,11,0,1,2,3]),o=(t,e)=>h(t,e,[0,1,2,3,4,5,6,7]),h=(t,e,l)=>{let r=Math.cos(e*Math.PI/180),o=Math.sin(e*Math.PI/180),h=l.map((e=>t[e]));for(let e=0;e<4;e++)t[l[e+0]]=o*h[e+4]+r*h[e+0],t[l[e+4]]=r*h[e+4]-o*h[e+0]};const a=16;return(h,s)=>{const f=(t,e)=>s[t]>=0?s[t]:e;let i=f(4,5)/10,$=f(5,3)/10,c=f(6,2)/10,n=f(7,6)/10,M=[];M[0]=`hsl(${f(8,0)},100%,${f(a,50)}%)`,M[1]=`hsl(${f(9,0)},100%,${f(a,50)}%)`,M[2]=`hsl(${f(10,0)},100%,${f(a,50)}%)`,M[3]=`hsl(${f(11,0)},100%,${f(a,50)}%)`,M[4]=`hsl(${f(12,0)},100%,${f(a,50)}%)`,M[5]=`hsl(${f(13,0)},100%,${f(a,50)}%)`,M[6]=`hsl(${f(14,0)},100%,${f(17,0)}%)`,M[7]=`hsl(${f(15,0)},100%,${f(17,0)}%)`,M[8]="black";let u=0,m=[],A=[],b=[],w=[],p=Array(29).fill(0).map((()=>[0,0,0,0,0]));if(h.length!==2*p.length)throw new Error("circles num error");let E=()=>{let a=f(0,60)+120+u,s=f(1,45)-45,P=2*f(2,2)+4,d=Math.sin(9*(f(3,0)+u)*Math.PI/180),y=30*d,I=.3*Math.abs(d);u++,t(m,[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),p[0]=[0,0,0,i,0];for(let r=0;r<2;r++){let h=1+r,a=0===r?1:-1;t(A,m),o(A,30*a),l(A,-y*a),e(A,0,-(i+.7*$),0),p[h]=[A[12],A[13],A[14],$,h]}for(let l=0;l<2;l++){let o=3+l,h=0===l?1:-1;t(A,m),r(A,+y),e(A,(i+.5*c)*h,0,0),p[o]=[A[12],A[13],A[14],c,o]}t(A,m),l(A,-30),e(A,0,+(i+.7*n),0),l(A,30),t(b,A),l(b,150);for(let l=0;l<8;l++){let r=l/7;t(w,b),e(w,0,0,-1.333*n*r),p[5+l]=[w[12],w[13],w[14],n*(3-2*r)/3,5]}for(let l=0;l<2;l++){let o=0===l?1:-1;t(b,A),r(b,-15*o),e(b,0,0,-.8*n);for(let r=0;r<8;r++){let o=r/7-.5;t(w,b),e(w,0,.6*n*o,0),p[13+8*l+r]=[w[12],w[13],w[14],n/6,6+l]}}let g=p.reduce(((t,e)=>Math.min(t,e[1]-e[3])),0);p.forEach((t=>{t[1]+=I-g})),(e=>{t(e,[1,0,0,0,0,-1,0,0,0,0,-1.2,-1,0,0,-2.2,0])})(m),e(m,0,0,-P),l(m,s),r(m,a),e(m,0,-1.4,0),p.forEach((l=>{t(A,m),e(A,l[0],l[1],l[2]),l[0]=A[12]/A[15],l[1]=A[13]/A[15],l[2]=A[14]/A[15],l[3]=l[3]/A[15]})),p.sort(((t,e)=>e[2]-t[2]));let k=0;for(let t=0;t<2;t++)p.forEach((e=>{let l=h.item(k++);l.setAttribute("cx",Math.floor(350*(2*e[0]+.5))),l.setAttribute("cy",Math.floor(350*(2*e[1]+.5))),l.setAttribute("r",Math.floor(2*e[3]*350+(0===t?16:0))),l.setAttribute("fill",M[0===t?8:e[4]])}));window.requestAnimationFrame(E)};E()}})();';
}
// ----------------------------------------------------------------
// ----------------------------------------------------------------
// ----------------------------------------------------------------
|
a[0] = _fixedInt(1); a[1] = 0; a[2] = 0; a[3] = 0; a[4] = 0; a[5] = _fixedInt(1); a[6] = 0; a[7] = 0; a[8] = 0; a[9] = 0; a[10] = _fixedInt(1); a[11] = 0; a[12] = 0; a[13] = 0; a[14] = 0; a[15] = _fixedInt(1);
|
function _matIdentity(int256[16] memory a) private pure {
a[0] = _fixedInt(1);
a[5] = _fixedInt(1);
a[10] = _fixedInt(1);
a[15] = _fixedInt(1);
}
| 6,094,337
|
./full_match/4/0xB238314f8918A1bE89E082b97002f5A9BC6610EE/sources/SKETCH.sol
|
Shows the price./
|
function getPrice() public view returns (uint256){
return PRICE_PER_TOKEN;
}
| 680,356
|
./full_match/80001/0x5A32Ce161a151bE7E2a76978b5B1d9836E0572bC/sources/contracts/hackerpass.sol
|
questioning life choices
|
function batchMint(address to, uint256 count) public onlyOwner {
for (uint256 i = 0; i < count; i++) {
safeMint(to);
}
}
| 5,603,209
|
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import '@openzeppelin/contracts/token/ERC20/ERC20.sol';
import '@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol';
import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
import '@openzeppelin/contracts/security/Pausable.sol';
import '@openzeppelin/contracts/access/AccessControl.sol';
import './interfaces/IStrategy.sol';
/**
*
* @title Zunami Protocol
*
* @notice Contract for Convex&Curve protocols optimize.
* Users can use this contract for optimize yield and gas.
*
*
* @dev Zunami is main contract.
* Contract does not store user funds.
* All user funds goes to Convex&Curve pools.
*
*/
contract Zunami is ERC20, Pausable, AccessControl {
using SafeERC20 for IERC20Metadata;
bytes32 public constant OPERATOR_ROLE = keccak256('OPERATOR_ROLE');
struct PendingWithdrawal {
uint256 lpShares;
uint256[3] tokenAmounts;
}
struct PoolInfo {
IStrategy strategy;
uint256 startTime;
uint256 lpShares;
}
uint8 public constant POOL_ASSETS = 3;
uint256 public constant LP_RATIO_MULTIPLIER = 1e18;
uint256 public constant FEE_DENOMINATOR = 1000;
uint256 public constant MIN_LOCK_TIME = 1 days;
uint256 public constant FUNDS_DENOMINATOR = 10_000;
uint8 public constant ALL_WITHDRAWAL_TYPES_MASK = uint8(3); // Binary 11 = 2^0 + 2^1;
PoolInfo[] internal _poolInfo;
uint256 public defaultDepositPid;
uint256 public defaultWithdrawPid;
uint8 public availableWithdrawalTypes;
address[POOL_ASSETS] public tokens;
uint256[POOL_ASSETS] public decimalsMultipliers;
mapping(address => uint256[POOL_ASSETS]) internal _pendingDeposits;
mapping(address => PendingWithdrawal) internal _pendingWithdrawals;
uint256 public totalDeposited = 0;
uint256 public managementFee = 100; // 10%
bool public launched = false;
event CreatedPendingDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts);
event CreatedPendingWithdrawal(
address indexed withdrawer,
uint256 lpShares,
uint256[POOL_ASSETS] tokenAmounts
);
event Deposited(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares);
event RemovedDeposit(address indexed depositor);
event Withdrawn(
address indexed withdrawer,
IStrategy.WithdrawalType withdrawalType,
uint256[POOL_ASSETS] tokenAmounts,
uint256 lpShares,
uint128 tokenIndex
);
event AddedPool(uint256 pid, address strategyAddr, uint256 startTime);
event FailedWithdrawal(
address indexed withdrawer,
uint256[POOL_ASSETS] amounts,
uint256 lpShares
);
event SetDefaultDepositPid(uint256 pid);
event SetDefaultWithdrawPid(uint256 pid);
event ClaimedAllManagementFee(uint256 feeValue);
event AutoCompoundAll();
modifier startedPool() {
require(_poolInfo.length != 0, 'Zunami: pool not existed!');
require(
block.timestamp >= _poolInfo[defaultDepositPid].startTime,
'Zunami: default deposit pool not started yet!'
);
require(
block.timestamp >= _poolInfo[defaultWithdrawPid].startTime,
'Zunami: default withdraw pool not started yet!'
);
_;
}
constructor(address[POOL_ASSETS] memory _tokens) ERC20('ZunamiLP', 'ZLP') {
tokens = _tokens;
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(OPERATOR_ROLE, msg.sender);
for (uint256 i; i < POOL_ASSETS; i++) {
uint256 decimals = IERC20Metadata(tokens[i]).decimals();
if (decimals < 18) {
decimalsMultipliers[i] = 10**(18 - decimals);
} else {
decimalsMultipliers[i] = 1;
}
}
availableWithdrawalTypes = ALL_WITHDRAWAL_TYPES_MASK;
}
function poolInfo(uint256 pid) external view returns (PoolInfo memory) {
return _poolInfo[pid];
}
function pendingDeposits(address user) external view returns (uint256[POOL_ASSETS] memory) {
return _pendingDeposits[user];
}
function pendingDepositsToken(address user, uint256 tokenIndex)
external
view
returns (uint256)
{
return _pendingDeposits[user][tokenIndex];
}
function pendingWithdrawals(address user) external view returns (PendingWithdrawal memory) {
return _pendingWithdrawals[user];
}
function pause() external onlyRole(DEFAULT_ADMIN_ROLE) {
_pause();
}
function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) {
_unpause();
}
function setAvailableWithdrawalTypes(uint8 newAvailableWithdrawalTypes)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(
newAvailableWithdrawalTypes <= ALL_WITHDRAWAL_TYPES_MASK,
'Zunami: wrong available withdrawal types'
);
availableWithdrawalTypes = newAvailableWithdrawalTypes;
}
/**
* @dev update managementFee, this is a Zunami commission from protocol profit
* @param newManagementFee - minAmount 0, maxAmount FEE_DENOMINATOR - 1
*/
function setManagementFee(uint256 newManagementFee) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(newManagementFee < FEE_DENOMINATOR, 'Zunami: wrong fee');
managementFee = newManagementFee;
}
/**
* @dev Returns managementFee for strategy's when contract sell rewards
* @return Returns commission on the amount of profit in the transaction
* @param amount - amount of profit for calculate managementFee
*/
function calcManagementFee(uint256 amount) external view returns (uint256) {
return (amount * managementFee) / FEE_DENOMINATOR;
}
/**
* @dev Claims managementFee from all active strategies
*/
function claimAllManagementFee() external {
uint256 feeTotalValue;
for (uint256 i = 0; i < _poolInfo.length; i++) {
feeTotalValue += _poolInfo[i].strategy.claimManagementFees();
}
emit ClaimedAllManagementFee(feeTotalValue);
}
function autoCompoundAll() external {
for (uint256 i = 0; i < _poolInfo.length; i++) {
_poolInfo[i].strategy.autoCompound();
}
emit AutoCompoundAll();
}
/**
* @dev Returns total holdings for all pools (strategy's)
* @return Returns sum holdings (USD) for all pools
*/
function totalHoldings() public view returns (uint256) {
uint256 length = _poolInfo.length;
uint256 totalHold = 0;
for (uint256 pid = 0; pid < length; pid++) {
totalHold += _poolInfo[pid].strategy.totalHoldings();
}
return totalHold;
}
/**
* @dev Returns price depends on the income of users
* @return Returns currently price of ZLP (1e18 = 1$)
*/
function lpPrice() external view returns (uint256) {
return (totalHoldings() * 1e18) / totalSupply();
}
/**
* @dev Returns number of pools
* @return number of pools
*/
function poolCount() external view returns (uint256) {
return _poolInfo.length;
}
/**
* @dev in this func user sends funds to the contract and then waits for the completion
* of the transaction for all users
* @param amounts - array of deposit amounts by user
*/
function delegateDeposit(uint256[3] memory amounts) external whenNotPaused {
for (uint256 i = 0; i < amounts.length; i++) {
if (amounts[i] > 0) {
IERC20Metadata(tokens[i]).safeTransferFrom(_msgSender(), address(this), amounts[i]);
_pendingDeposits[_msgSender()][i] += amounts[i];
}
}
emit CreatedPendingDeposit(_msgSender(), amounts);
}
/**
* @dev in this func user sends pending withdraw to the contract and then waits
* for the completion of the transaction for all users
* @param lpShares - amount of ZLP for withdraw
* @param tokenAmounts - array of amounts stablecoins that user want minimum receive
*/
function delegateWithdrawal(uint256 lpShares, uint256[POOL_ASSETS] memory tokenAmounts)
external
whenNotPaused
{
require(lpShares > 0, 'Zunami: lpAmount must be higher 0');
PendingWithdrawal memory withdrawal;
address userAddr = _msgSender();
withdrawal.lpShares = lpShares;
withdrawal.tokenAmounts = tokenAmounts;
_pendingWithdrawals[userAddr] = withdrawal;
emit CreatedPendingWithdrawal(userAddr, lpShares, tokenAmounts);
}
/**
* @dev Zunami protocol owner complete all active pending deposits of users
* @param userList - dev send array of users from pending to complete
*/
function completeDeposits(address[] memory userList)
external
onlyRole(OPERATOR_ROLE)
startedPool
{
IStrategy strategy = _poolInfo[defaultDepositPid].strategy;
uint256 currentTotalHoldings = totalHoldings();
uint256 newHoldings = 0;
uint256[3] memory totalAmounts;
uint256[] memory userCompleteHoldings = new uint256[](userList.length);
for (uint256 i = 0; i < userList.length; i++) {
newHoldings = 0;
for (uint256 x = 0; x < totalAmounts.length; x++) {
uint256 userTokenDeposit = _pendingDeposits[userList[i]][x];
totalAmounts[x] += userTokenDeposit;
newHoldings += userTokenDeposit * decimalsMultipliers[x];
}
userCompleteHoldings[i] = newHoldings;
}
newHoldings = 0;
for (uint256 y = 0; y < POOL_ASSETS; y++) {
uint256 totalTokenAmount = totalAmounts[y];
if (totalTokenAmount > 0) {
newHoldings += totalTokenAmount * decimalsMultipliers[y];
IERC20Metadata(tokens[y]).safeTransfer(address(strategy), totalTokenAmount);
}
}
uint256 totalDepositedNow = strategy.deposit(totalAmounts);
require(totalDepositedNow > 0, 'Zunami: too low deposit!');
uint256 lpShares = 0;
uint256 addedHoldings = 0;
uint256 userDeposited = 0;
for (uint256 z = 0; z < userList.length; z++) {
userDeposited = (totalDepositedNow * userCompleteHoldings[z]) / newHoldings;
address userAddr = userList[z];
if (totalSupply() == 0) {
lpShares = userDeposited;
} else {
lpShares = (totalSupply() * userDeposited) / (currentTotalHoldings + addedHoldings);
}
addedHoldings += userDeposited;
_mint(userAddr, lpShares);
_poolInfo[defaultDepositPid].lpShares += lpShares;
emit Deposited(userAddr, _pendingDeposits[userAddr], lpShares);
// remove deposit from list
delete _pendingDeposits[userAddr];
}
totalDeposited += addedHoldings;
}
/**
* @dev Zunami protocol owner complete all active pending withdrawals of users
* @param userList - array of users from pending withdraw to complete
*/
function completeWithdrawals(address[] memory userList)
external
onlyRole(OPERATOR_ROLE)
startedPool
{
require(userList.length > 0, 'Zunami: there are no pending withdrawals requests');
IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy;
address user;
PendingWithdrawal memory withdrawal;
for (uint256 i = 0; i < userList.length; i++) {
user = userList[i];
withdrawal = _pendingWithdrawals[user];
if (balanceOf(user) < withdrawal.lpShares) {
emit FailedWithdrawal(user, withdrawal.tokenAmounts, withdrawal.lpShares);
delete _pendingWithdrawals[user];
continue;
}
if (
!(
strategy.withdraw(
user,
calcLpRatioSafe(
withdrawal.lpShares,
_poolInfo[defaultWithdrawPid].lpShares
),
withdrawal.tokenAmounts,
IStrategy.WithdrawalType.Base,
0
)
)
) {
emit FailedWithdrawal(user, withdrawal.tokenAmounts, withdrawal.lpShares);
delete _pendingWithdrawals[user];
continue;
}
uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply();
_burn(user, withdrawal.lpShares);
_poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares;
totalDeposited -= userDeposit;
emit Withdrawn(
user,
IStrategy.WithdrawalType.Base,
withdrawal.tokenAmounts,
withdrawal.lpShares,
0
);
delete _pendingWithdrawals[user];
}
}
function calcLpRatioSafe(uint256 outLpShares, uint256 strategyLpShares)
internal
pure
returns (uint256 lpShareRatio)
{
lpShareRatio = (outLpShares * LP_RATIO_MULTIPLIER) / strategyLpShares;
require(
lpShareRatio > 0 && lpShareRatio <= LP_RATIO_MULTIPLIER,
'Zunami: Wrong out lp Ratio'
);
}
function completeWithdrawalsOptimized(address[] memory userList)
external
onlyRole(OPERATOR_ROLE)
startedPool
{
require(userList.length > 0, 'Zunami: there are no pending withdrawals requests');
IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy;
uint256 lpSharesTotal;
uint256[POOL_ASSETS] memory minAmountsTotal;
uint256 i;
address user;
PendingWithdrawal memory withdrawal;
for (i = 0; i < userList.length; i++) {
user = userList[i];
withdrawal = _pendingWithdrawals[user];
if (balanceOf(user) < withdrawal.lpShares) {
emit FailedWithdrawal(user, withdrawal.tokenAmounts, withdrawal.lpShares);
delete _pendingWithdrawals[user];
continue;
}
lpSharesTotal += withdrawal.lpShares;
minAmountsTotal[0] += withdrawal.tokenAmounts[0];
minAmountsTotal[1] += withdrawal.tokenAmounts[1];
minAmountsTotal[2] += withdrawal.tokenAmounts[2];
emit Withdrawn(
user,
IStrategy.WithdrawalType.Base,
withdrawal.tokenAmounts,
withdrawal.lpShares,
0
);
}
require(
lpSharesTotal <= _poolInfo[defaultWithdrawPid].lpShares,
'Zunami: Insufficient pool LP shares'
);
uint256[POOL_ASSETS] memory prevBalances;
for (i = 0; i < 3; i++) {
prevBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this));
}
if (
!strategy.withdraw(
address(this),
calcLpRatioSafe(lpSharesTotal, _poolInfo[defaultWithdrawPid].lpShares),
minAmountsTotal,
IStrategy.WithdrawalType.Base,
0
)
) {
for (i = 0; i < userList.length; i++) {
user = userList[i];
withdrawal = _pendingWithdrawals[user];
emit FailedWithdrawal(user, withdrawal.tokenAmounts, withdrawal.lpShares);
delete _pendingWithdrawals[user];
}
return;
}
uint256[POOL_ASSETS] memory diffBalances;
for (i = 0; i < 3; i++) {
diffBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)) - prevBalances[i];
}
for (i = 0; i < userList.length; i++) {
user = userList[i];
withdrawal = _pendingWithdrawals[user];
uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply();
_burn(user, withdrawal.lpShares);
_poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares;
totalDeposited -= userDeposit;
uint256 transferAmount;
for (uint256 j = 0; j < 3; j++) {
transferAmount = (diffBalances[j] * withdrawal.lpShares) / lpSharesTotal;
if (transferAmount > 0) {
IERC20Metadata(tokens[j]).safeTransfer(user, transferAmount);
}
}
delete _pendingWithdrawals[user];
}
}
/**
* @dev deposit in one tx, without waiting complete by dev
* @return Returns amount of lpShares minted for user
* @param amounts - user send amounts of stablecoins to deposit
*/
function deposit(uint256[POOL_ASSETS] memory amounts)
external
whenNotPaused
startedPool
returns (uint256)
{
IStrategy strategy = _poolInfo[defaultDepositPid].strategy;
uint256 holdings = totalHoldings();
for (uint256 i = 0; i < amounts.length; i++) {
if (amounts[i] > 0) {
IERC20Metadata(tokens[i]).safeTransferFrom(
_msgSender(),
address(strategy),
amounts[i]
);
}
}
uint256 newDeposited = strategy.deposit(amounts);
require(newDeposited > 0, 'Zunami: too low deposit!');
uint256 lpShares = 0;
if (totalSupply() == 0) {
lpShares = newDeposited;
} else {
lpShares = (totalSupply() * newDeposited) / holdings;
}
_mint(_msgSender(), lpShares);
_poolInfo[defaultDepositPid].lpShares += lpShares;
totalDeposited += newDeposited;
emit Deposited(_msgSender(), amounts, lpShares);
return lpShares;
}
/**
* @dev withdraw in one tx, without waiting complete by dev
* @param lpShares - amount of ZLP for withdraw
* @param tokenAmounts - array of amounts stablecoins that user want minimum receive
*/
function withdraw(
uint256 lpShares,
uint256[POOL_ASSETS] memory tokenAmounts,
IStrategy.WithdrawalType withdrawalType,
uint128 tokenIndex
) external whenNotPaused startedPool {
require(
checkBit(availableWithdrawalTypes, uint8(withdrawalType)),
'Zunami: withdrawal type not available'
);
IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy;
address userAddr = _msgSender();
require(balanceOf(userAddr) >= lpShares, 'Zunami: not enough LP balance');
require(
strategy.withdraw(
userAddr,
calcLpRatioSafe(lpShares, _poolInfo[defaultWithdrawPid].lpShares),
tokenAmounts,
withdrawalType,
tokenIndex
),
'Zunami: incorrect withdraw params'
);
uint256 userDeposit = (totalDeposited * lpShares) / totalSupply();
_burn(userAddr, lpShares);
_poolInfo[defaultWithdrawPid].lpShares -= lpShares;
totalDeposited -= userDeposit;
emit Withdrawn(userAddr, withdrawalType, tokenAmounts, lpShares, tokenIndex);
}
function calcWithdrawOneCoin(uint256 lpShares, uint128 tokenIndex)
external
view
returns (uint256 tokenAmount)
{
require(lpShares <= balanceOf(_msgSender()), 'Zunami: not enough LP balance');
uint256 lpShareRatio = calcLpRatioSafe(lpShares, _poolInfo[defaultWithdrawPid].lpShares);
return _poolInfo[defaultWithdrawPid].strategy.calcWithdrawOneCoin(lpShareRatio, tokenIndex);
}
function calcSharesAmount(uint256[3] memory tokenAmounts, bool isDeposit)
external
view
returns (uint256 lpShares)
{
return _poolInfo[defaultWithdrawPid].strategy.calcSharesAmount(tokenAmounts, isDeposit);
}
/**
* @dev add a new pool, deposits in the new pool are blocked for one day for safety
* @param _strategyAddr - the new pool strategy address
*/
function addPool(address _strategyAddr) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(_strategyAddr != address(0), 'Zunami: zero strategy addr');
uint256 startTime = block.timestamp + (launched ? MIN_LOCK_TIME : 0);
_poolInfo.push(
PoolInfo({ strategy: IStrategy(_strategyAddr), startTime: startTime, lpShares: 0 })
);
emit AddedPool(_poolInfo.length - 1, _strategyAddr, startTime);
}
/**
* @dev set a default pool for deposit funds
* @param _newPoolId - new pool id
*/
function setDefaultDepositPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default deposit pool id');
defaultDepositPid = _newPoolId;
emit SetDefaultDepositPid(_newPoolId);
}
/**
* @dev set a default pool for withdraw funds
* @param _newPoolId - new pool id
*/
function setDefaultWithdrawPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default withdraw pool id');
defaultWithdrawPid = _newPoolId;
emit SetDefaultWithdrawPid(_newPoolId);
}
function launch() external onlyRole(DEFAULT_ADMIN_ROLE) {
launched = true;
}
/**
* @dev dev can transfer funds from few strategy's to one strategy for better APY
* @param _strategies - array of strategy's, from which funds are withdrawn
* @param withdrawalsPercents - A percentage of the funds that should be transfered
* @param _receiverStrategyId - number strategy, to which funds are deposited
*/
function moveFundsBatch(
uint256[] memory _strategies,
uint256[] memory withdrawalsPercents,
uint256 _receiverStrategyId
) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(
_strategies.length == withdrawalsPercents.length,
'Zunami: incorrect arguments for the moveFundsBatch'
);
require(_receiverStrategyId < _poolInfo.length, 'Zunami: incorrect a reciver strategy ID');
uint256[POOL_ASSETS] memory tokenBalance;
for (uint256 y = 0; y < POOL_ASSETS; y++) {
tokenBalance[y] = IERC20Metadata(tokens[y]).balanceOf(address(this));
}
uint256 pid;
uint256 zunamiLp;
for (uint256 i = 0; i < _strategies.length; i++) {
pid = _strategies[i];
zunamiLp += _moveFunds(pid, withdrawalsPercents[i]);
}
uint256[POOL_ASSETS] memory tokensRemainder;
for (uint256 y = 0; y < POOL_ASSETS; y++) {
tokensRemainder[y] =
IERC20Metadata(tokens[y]).balanceOf(address(this)) -
tokenBalance[y];
if (tokensRemainder[y] > 0) {
IERC20Metadata(tokens[y]).safeTransfer(
address(_poolInfo[_receiverStrategyId].strategy),
tokensRemainder[y]
);
}
}
_poolInfo[_receiverStrategyId].lpShares += zunamiLp;
require(
_poolInfo[_receiverStrategyId].strategy.deposit(tokensRemainder) > 0,
'Zunami: Too low amount!'
);
}
function _moveFunds(uint256 pid, uint256 withdrawAmount) private returns (uint256) {
uint256 currentLpAmount;
if (withdrawAmount == FUNDS_DENOMINATOR) {
_poolInfo[pid].strategy.withdrawAll();
currentLpAmount = _poolInfo[pid].lpShares;
_poolInfo[pid].lpShares = 0;
} else {
currentLpAmount = (_poolInfo[pid].lpShares * withdrawAmount) / FUNDS_DENOMINATOR;
uint256[POOL_ASSETS] memory minAmounts;
_poolInfo[pid].strategy.withdraw(
address(this),
calcLpRatioSafe(currentLpAmount, _poolInfo[pid].lpShares),
minAmounts,
IStrategy.WithdrawalType.Base,
0
);
_poolInfo[pid].lpShares = _poolInfo[pid].lpShares - currentLpAmount;
}
return currentLpAmount;
}
/**
* @dev user remove his active pending deposit
*/
function removePendingDeposit() external {
for (uint256 i = 0; i < POOL_ASSETS; i++) {
if (_pendingDeposits[_msgSender()][i] > 0) {
IERC20Metadata(tokens[i]).safeTransfer(
_msgSender(),
_pendingDeposits[_msgSender()][i]
);
}
}
delete _pendingDeposits[_msgSender()];
emit RemovedDeposit(_msgSender());
}
function removePendingWithdrawal() external {
delete _pendingWithdrawals[_msgSender()];
}
/**
* @dev governance can withdraw all stuck funds in emergency case
* @param _token - IERC20Metadata token that should be fully withdraw from Zunami
*/
function withdrawStuckToken(IERC20Metadata _token) external onlyRole(DEFAULT_ADMIN_ROLE) {
uint256 tokenBalance = _token.balanceOf(address(this));
if (tokenBalance > 0) {
_token.safeTransfer(_msgSender(), tokenBalance);
}
}
/**
* @dev governance can add new operator for complete pending deposits and withdrawals
* @param _newOperator - address that governance add in list of operators
*/
function updateOperator(address _newOperator) external onlyRole(DEFAULT_ADMIN_ROLE) {
_grantRole(OPERATOR_ROLE, _newOperator);
}
// Get bit value at position
function checkBit(uint8 mask, uint8 bit) internal pure returns (bool) {
return mask & (0x01 << bit) != 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.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:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, _allowances[owner][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = _allowances[owner][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, 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:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_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 Spend `amount` form the allowance of `owner` toward `spender`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts 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 (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 (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
pragma solidity ^0.8.0;
interface IStrategy {
enum WithdrawalType {
Base,
OneCoin
}
function deposit(uint256[3] memory amounts) external returns (uint256);
function withdraw(
address withdrawer,
uint256 userRatioOfCrvLps, // multiplied by 1e18
uint256[3] memory tokenAmounts,
WithdrawalType withdrawalType,
uint128 tokenIndex
) external returns (bool);
function withdrawAll() external;
function totalHoldings() external view returns (uint256);
function claimManagementFees() external returns (uint256);
function autoCompound() external;
function calcWithdrawOneCoin(uint256 userRatioOfCrvLps, uint128 tokenIndex)
external
view
returns (uint256 tokenAmount);
function calcSharesAmount(uint256[3] memory tokenAmounts, bool isDeposit)
external
view
returns (uint256 sharesAmount);
}
// 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 (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) (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 (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/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 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);
}
|
user remove his active pending deposit/
|
function removePendingDeposit() external {
for (uint256 i = 0; i < POOL_ASSETS; i++) {
if (_pendingDeposits[_msgSender()][i] > 0) {
IERC20Metadata(tokens[i]).safeTransfer(
_msgSender(),
_pendingDeposits[_msgSender()][i]
);
}
}
delete _pendingDeposits[_msgSender()];
emit RemovedDeposit(_msgSender());
}
| 13,597,064
|
// Copyright (C) 2020 Zerion Inc. <https://zerion.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 <https://www.gnu.org/licenses/>.
pragma solidity 0.6.5;
pragma experimental ABIEncoderV2;
abstract contract Ownable {
modifier onlyOwner {
require(msg.sender == owner, "O: onlyOwner function!");
_;
}
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @notice Initializes owner variable with msg.sender address.
*/
constructor() internal {
owner = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
}
/**
* @notice Transfers ownership to the desired address.
* The function is callable only by the owner.
*/
function transferOwnership(address _owner) external onlyOwner {
require(_owner != address(0), "O: new owner is the zero address!");
emit OwnershipTransferred(owner, _owner);
owner = _owner;
}
}
|
Transfers ownership to the desired address. The function is callable only by the owner./
|
function transferOwnership(address _owner) external onlyOwner {
require(_owner != address(0), "O: new owner is the zero address!");
emit OwnershipTransferred(owner, _owner);
owner = _owner;
}
| 977,742
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
import "Initiative_Legislative_lib.sol";
import "Register.sol";
import "Citizens_Register.sol";
import "IVote.sol";
import "IDelegation.sol";
*/
import "contracts/Initiative_Legislative_lib.sol";
import "contracts/Register.sol";
import "contracts/Citizens_Register.sol";
import "contracts/IVote.sol";
import "contracts/IDelegation.sol";
/**
* @notice Delegation_Uils library is used to reduce the size of Delegation contract in order to avoid to exceed contract limit size. It contains heavy functions and data structures.
*/
library Delegation_Uils{
using EnumerableSet for EnumerableSet.AddressSet;
/**
* @dev Parameters related to the democratic process of registers governance.
* - Member_Max_Token_Usage: The maximum amount of token a member is allowed to use for a specific law project elaboration
* - Law_Initialisation_Price: The price in token for creating a law project
* - FunctionCall_Price: The price in token for one FunctionCall.
* - Proposition_Duration: The duration of the stage in which members are allowed to submit propositions
* - Vote_Duration: The duration of the stage in which members are allowed to vote for the proposition they want
* - Law_Censor_Period_Duration: The duration of the stage in which all citizens are allowed to sign a etition against the law project proposed by the Delegation
* - Censor_Proposition_Petition_Rate The minimum ratio of citizens required to cancel a law project
* - Censor_Penalty_Rate The amount of token the delegation will lost if their law project is rejected by citizens
* - Ivote_address Address of the IVote contract that will be used during voting stage
*/
struct Law_Project_Parameters{
uint Member_Max_Token_Usage;
uint Law_Initialisation_Price;
uint FunctionCall_Price;
uint Proposition_Duration;
uint Vote_Duration;
uint Law_Censor_Period_Duration;
uint16 Censor_Proposition_Petition_Rate;
uint16 Censor_Penalty_Rate;
address Ivote_address;
}
/**
* @dev Structure reresenting parameters related to the democratic process of registers governance.
* - Election_Duration Duration of the stage in which citizens are allowed to vote for Candidats they prefer
* - Validation_Duration Duration of the stage in which citizens can validate their hased vote by revealing their choice and the salt that has been used for hasing
* - Mandate_Duration Duration of a delegation mandate
* - Immunity_Duration Amount of time after the beginning of a new mandate during which delegation's members can't be revoked
* - Next_Mandate_Max_Members Maximum number of members in the delegation.
* - New_Election_Petition_Rate The minimum ratio of citizens required to revoke the current delegation's members and start a new election
* - Ivote_address Address of the IVote contract that will be used during election stage
*/
struct Mandate_Parameter{
uint Election_Duration;
uint Validation_Duration;
uint Mandate_Duration;
uint Immunity_Duration;
uint16 Next_Mandate_Max_Members;
uint16 New_Election_Petition_Rate;
address Ivote_address;
}
/**
* @dev Structure representing a mandate.
* - Members Duration : List of members of the delegation
* - New_Election_Petitions: List of citizens who have signed petition for revoking the current delegation's members.
* - Next_Mandate_Candidats: List of accounts that are candidates for the next election
* - Inauguration_Timestamps: Beginning of current mandate
* - Election_Timestamps: Beginning of election
* - Version: Version of parameters (Id of {Mandate_Parameter} object) used by this mandate
*/
struct Mandate{
EnumerableSet.AddressSet Members;
EnumerableSet.AddressSet New_Election_Petitions;
EnumerableSet.AddressSet Next_Mandate_Candidats;
uint Inauguration_Timestamps;
uint Election_Timestamps;
uint Version;
}
event Governance_Parameters_Updated();
event Legislatif_Parameters_Updated();
event New_Candidat(address Candidat);
event Remove_Candidat(address Candidat);
event Sign();
event New_election(bytes32 Vote_key);
event New_Mandate();
///@dev Function used for updating parameters related to the democratic process of rmembers election. See {Update_Internal_Governance] function of {Delegation} or {IDelegation} contract
function Update_Mandate_Parameter(Mandate_Parameter storage mandate_param, uint Election_Duration, uint Validation_Duration, uint Mandate_Duration, uint Immunity_Duration,
uint16 Next_Mandate_Max_Members, uint16 New_Election_Petition_Rate, address Ivote_address) external {
mandate_param.Election_Duration = Election_Duration;
mandate_param.Validation_Duration = Validation_Duration;
mandate_param.Mandate_Duration = Mandate_Duration;
mandate_param.Immunity_Duration = Immunity_Duration;
mandate_param.Next_Mandate_Max_Members = Next_Mandate_Max_Members;
mandate_param.New_Election_Petition_Rate = New_Election_Petition_Rate;
mandate_param.Ivote_address = Ivote_address;
emit Governance_Parameters_Updated();
}
///@dev Function used for updating parameters related to the democratic process of registers governance. See {Update_Legislatif_Process] function of {Delegation} or {IDelegation} contract
function Update_Law_Parameters(Law_Project_Parameters storage projet_param, uint[6] calldata Uint256_Legislatifs_Arg, uint16 Censor_Proposition_Petition_Rate,
uint16 Censor_Penalty_Rate, address Ivote_address) external {
projet_param.Member_Max_Token_Usage = Uint256_Legislatifs_Arg[0];
projet_param.Law_Initialisation_Price = Uint256_Legislatifs_Arg[1];
projet_param.FunctionCall_Price = Uint256_Legislatifs_Arg[2];
projet_param.Proposition_Duration = Uint256_Legislatifs_Arg[3];
projet_param.Vote_Duration = Uint256_Legislatifs_Arg[4];
projet_param.Law_Censor_Period_Duration = Uint256_Legislatifs_Arg[5];
projet_param.Censor_Proposition_Petition_Rate = Censor_Proposition_Petition_Rate;
projet_param.Censor_Penalty_Rate = Censor_Penalty_Rate;
projet_param.Ivote_address = Ivote_address;
emit Legislatif_Parameters_Updated();
}
/**
* @dev Function called by {End_Election} function of {Delegation} Contract to end the current contract and start a new one.
* @param Mandates mapping of Mandate structure idexed by uint corresponding to their order of apparition
* @param ivote_address Address of IVote contract used by citizens to vote during election.
* @param last_mandate_num Index in {Mandates} mapping of the last mandate
* @param Internal_Governance_Version Version of Parameters ({Mandate_Parameter} structur) u.sed by the current mandate
* */
function Transition_Mandate(mapping (uint=>Mandate) storage Mandates, address ivote_address, uint last_mandate_num, uint Internal_Governance_Version) external{
uint new_mandate_num=last_mandate_num+1;
uint[] memory results;
IVote Vote_Instance = IVote(ivote_address);
results = Vote_Instance.Get_Winning_Propositions(keccak256(abi.encodePacked(address(this),Mandates[last_mandate_num].Election_Timestamps)));
if(results[0]==0){
uint actual_member_length = Mandates[last_mandate_num].Members.length();
for(uint i =0; i<actual_member_length; i++){
Mandates[new_mandate_num].Members.add(Mandates[last_mandate_num].Members.at(i));
}
}else{
for(uint i =0; i<results.length; i++){
Mandates[new_mandate_num].Members.add(Mandates[last_mandate_num].Next_Mandate_Candidats.at(results[i]-1));
}
}
Mandates[new_mandate_num].Inauguration_Timestamps = block.timestamp;
Mandates[new_mandate_num].Version = Internal_Governance_Version;
emit New_Mandate();
}
/**
* @dev Function called by {Candidate_Election} function of {Delegation} contract to add a new account to the list of candidats for next election
* @param mandate Current Mandate object
* @param new_candidat Account to add to the list of candidats
*/
function Add_Candidats(Mandate storage mandate, address new_candidat)external{
require(!mandate.Next_Mandate_Candidats.contains(new_candidat), "Already Candidate");
mandate.Next_Mandate_Candidats.add(new_candidat);
emit New_Candidat(new_candidat);
}
/**
* @dev Function called by {Remove_Candidature} function of {Delegation} contract to remove an account from the list of candidats for next election
* @param mandate Current Mandate object
* @param remove_candidat Account to remove from the list of candidats
*/
function Remove_Candidats(Mandate storage mandate, address remove_candidat)external{
require(mandate.Next_Mandate_Candidats.contains(remove_candidat), "Not Candidate");
mandate.Next_Mandate_Candidats.remove(remove_candidat);
emit Remove_Candidat(remove_candidat);
}
/**
* @dev Function called by {Sign_New_Election_Petition} function of {Delegation} contract to add an account to list petition for revoking current delegation members
* @param mandate Current Mandate object
* @param Immunity_Duration Amount of time after the beginning of a new mandate during which delegation's members can't be revoked
* @param signer Address of account who want to sign the petition
*/
function Sign_Petition(Mandate storage mandate, uint Immunity_Duration, address signer)external{
require(block.timestamp - mandate.Inauguration_Timestamps > Immunity_Duration, "Immunity Period");
require(!mandate.New_Election_Petitions.contains(signer), "Already signed petition");
mandate.New_Election_Petitions.add(signer);
emit Sign();
}
/**
* @dev Function called by {New_Election} function of {Delegation} contract to start a new election
* @param Mandates mapping of Mandate structure idexed by uint corresponding to their order of apparition
* @param mandate_version Mandate_Parameter object corresponding to parameters that are used by current mandate
* @param num_mandate Index of the current mandate in the {Mandates} mapping
* @param citizen_register_address Address of {Citizens_Register} contract used in the current project to handle citizens registration
*/
function New_Election(mapping(uint=>Mandate) storage Mandates, Mandate_Parameter storage mandate_version, uint num_mandate, address citizen_register_address)external returns(bool new_election){
uint candidats_number = Mandates[num_mandate].Next_Mandate_Candidats.length();
Citizens_Register citizen = Citizens_Register(citizen_register_address);
require(candidats_number>0, "No Candidats");
require(Mandates[num_mandate].New_Election_Petitions.length() >= Percentage(mandate_version.New_Election_Petition_Rate, citizen.Get_Citizen_Number()) || (block.timestamp - Mandates[num_mandate].Inauguration_Timestamps) > mandate_version.Mandate_Duration, "New election impossible for now");
if(candidats_number <= mandate_version.Next_Mandate_Max_Members){
uint new_mandate_num = num_mandate+1;
for(uint i =0; i<candidats_number; i++){
Mandates[new_mandate_num].Members.add(Mandates[num_mandate].Next_Mandate_Candidats.at(i));
}
Mandates[new_mandate_num].Inauguration_Timestamps = block.timestamp;
emit New_Mandate();
return false;
}else{
Mandates[num_mandate].Election_Timestamps = block.timestamp;
IVote Vote_Instance = IVote(mandate_version.Ivote_address);
bytes32 key = keccak256(abi.encodePacked(address(this),block.timestamp));
emit New_election(key);
Vote_Instance.Create_Ballot(key, citizen_register_address, Citizens_Register(citizen_register_address).Contains_Function_Selector(), mandate_version.Election_Duration, mandate_version.Validation_Duration, candidats_number, mandate_version.Next_Mandate_Max_Members);
return true;
}
}
/**
* @dev Function called by the constructor function of {Delegation} contract to start the first mandate.
* @param mandate Current Mandate object
* @param Initial_members Members of the first Delegation
*/
function Set_First_Mandate(Mandate storage mandate, address[] memory Initial_members)external{
mandate.Inauguration_Timestamps = block.timestamp;
for(uint i=0; i<Initial_members.length; i++){
mandate.Members.add(Initial_members[i]);
}
mandate.Version= 1;
}
/**
* @dev Utility function for computing Percentage.
* @param ratio The ratio is represented with 2 decimals
* @param base The base's number of decimal is arbitrary
* @return Return the {ratio}% of {base}. The result is represented with the number of decimals of {base}
*/
function Percentage(uint16 ratio, uint base) internal pure returns(uint){
return (ratio*base)/10000 ;// ((ratio*base)/100) * 10^(-ratio_decimals)
}
}
/**
* @notice Delegation contract is an implementation of IDelegation and thus aims at implementing a governance system in which a group of elected accounts is allowed to rule one or more controled registers contract.
*/
contract Delegation is Institution, IDelegation{// Initiative_Legislative{
using EnumerableSet for EnumerableSet.AddressSet;
using SafeMath for uint;
using Initiative_Legislative_Lib for Initiative_Legislative_Lib.Law_Project;
using Delegation_Uils for Delegation_Uils.Mandate_Parameter;
using Delegation_Uils for Delegation_Uils.Mandate;
using Delegation_Uils for Delegation_Uils.Law_Project_Parameters;
/**
* @dev status of a law project
*/
enum Status{
PROPOSITION,
VOTE,
CENSOR_LAW_PERIOD,
ADOPTED,
EXECUTED,
ABORTED
}
/**
* @dev Structure representing parameters related to the democratic process of registers governance.
*
* - Member_Max_Token_Usage: The maximum amount of token a member is allowed to use for a law project elaboration
* - Law_Initialisation_Price: The price in token for creating a law project
* - FunctionCall_Price: The price in token for one FunctionCall.
* - Proposition_Duration: The duration of the stage in which members are allowed to submit propositions
* - Vote_Duration: The duration of the stage in which members are allowed to vote for the proposition they want
* - Law_Censor_Period_Duration: The duration of the stage in which all citizens are allowed to sign a etition against the law project proposed by the Delegation
* - Censor_Proposition_Petition_Rate The minimum ratio of citizens required to cancel a law project
* - Censor_Penalty_Rate Ratio of total amount of token belonged by the delegation that will be lost if a law project is rejected by citizens
* - Ivote_address Address of the IVote contract that will be used during voting stage
*/
struct Law_Project_Parameters{
//uint Revert_Penalty_Limit;
uint Member_Max_Token_Usage;
uint Law_Initialisation_Price;
uint FunctionCall_Price;
uint Proposition_Duration;
uint Vote_Duration;
uint Law_Censor_Period_Duration;
uint16 Censor_Proposition_Petition_Rate;
uint16 Censor_Penalty_Rate;
address Ivote_address;
}
/**
* @dev Structure representing {Register} contract that are controled by the Delegation
* - Active: Whether the register is still under the actual Delegation control in the Constitution.
* - Law_Project_Counter: Number of pending law project related to this register
* The Register can't be removed from delegation's control if there are pending law project related to it. However if {Active} field is false, then we can't start a new law project whose controled register is the current one.
*/
struct Controlable_Register{
bool Active;
uint Law_Project_Counter;
}
/**
* @dev Structure representing a law project
* - Institution_Address: Address of register being concerned by this law project
* - Law_Project_Status: Status ({Status} structure) of the law project
* - Version: Version of Parameters ({Law_Project_Parameters} structure) used by the current law project
* - Creation_Timestamp: Beginning of current law project
* - Start_Vote_Timestamps: Beginning of voting stage
* - Start_Censor_Law_Period_Timestamps: Beginning of law project censorable stage
* - Law_Total_Potentialy_Lost: Amount of token that could be lost in penalty fee if all pending law project were to be censored by citizens petition
* - Censor_Law_Petition_Counter: Number of citizens that have signed the petition to censor the current law project
* - Censor_Law_Petitions: List of citizens that have signed the petition to censor the current law project
* - Members_Token_Consumption: Mapping of the amount of token consummed by each member of the delegation
*/
struct Delegation_Law_Project{
address Institution_Address;
Status Law_Project_Status;
uint Version;
uint Creation_Timestamp;
uint Start_Vote_Timestamps;
uint Start_Censor_Law_Period_Timestamps;
uint Law_Total_Potentialy_Lost;
uint Censor_Law_Petition_Counter;
mapping(address=>bool) Censor_Law_Petitions;
mapping(address=>uint) Members_Token_Consumption;
}
modifier Citizen_Only{
require(Citizens.Contains(msg.sender),"Citizen Only");
_;
}
modifier Delegation_Only{
require(Mandates[Actual_Mandate].Members.contains(msg.sender), "Delegation Only");
_;
}
event Governance_Parameters_Updated();
event Legislatif_Parameters_Updated();
event New_Candidat(address Candidat);
event Remove_Candidat(address Candidat);
event Sign();
event New_election(bytes32 Vote_key);
event New_Mandate();
event Controled_Register_Added(address register);
event Controled_Register_Canceled(address register);
event Controled_Register_Removed(address register);
event New_Law(bytes32 key);
event New_Proposal(bytes32 key, uint proposal_index);
event Proposal_Modified(bytes32 key, uint proposal_index);
event Voting_Stage_Started(bytes32 law_project, bytes32 key);
event Voting_Stage_Achieved(bytes32 key);
event Law_Aborted(bytes32 key);
event Law_Adopted(bytes32 key);
event Law_executed(bytes32 key);
event Function_Call_Executed( bytes32 key, uint num_function_call_ToExecute);
//event New_Proposal(bytes32 key, uint num);
/// @dev function selector of {Contains} function used to check Whether an account is member of the delegation
bytes4 constant Contains_Function_Selector = 0x57f98d32;
///@dev Instance of the {DemoCoin} token used by the Project
DemoCoin Democoin;
///@dev Instance of the {Citizens_Register} contract used by the Project
Citizens_Register Citizens;
//dev Address of the {Agora} contract used by the Project
address Agora_address;
///@dev Total amount of token potentially lost via penalty fee.
uint Potentialy_Lost_Amount;
/*Legislatif Process*/
/** @dev Mapping of {Law_Project} structure ({Initiative_Legislative_Lib} library)
*
* */
mapping(bytes32 => Initiative_Legislative_Lib.Law_Project) public List_Law_Project;
///@dev Mapping of Registers ({Controlable_Register} structure) that can receive orders from the actual Delegation
mapping(address=>Controlable_Register) public Controled_Registers;
/// @dev List of Controled Registers
EnumerableSet.AddressSet List_Controled_Registers;
///@dev Mapping of {Delegation_Law_Project} structure corresponding to law project of delegation (pending, aborted and passed)
mapping(bytes32=>Delegation_Law_Project) public Delegation_Law_Projects;
///@dev List of law projects
bytes32[] List_Delegation_Law_Projects;
///@dev Mapping of versions of Parameters ({Law_Project_Parameters} of {Delegation_Uils} library) used for law project process
mapping(uint=>Delegation_Uils.Law_Project_Parameters) public Law_Parameters_Versions;
/*Internal Governance*/
///@dev Mapping of {Mandate} structure ({Delegation_Uils} library) corresponding to mandates of delegation (pending and passed)
mapping(uint=>Delegation_Uils.Mandate) Mandates;
///@dev Mapping of versions of Parameters ({Mandate_Parameter} of {Delegation_Uils} library) used for delegation internal governance.
mapping(uint=>Delegation_Uils.Mandate_Parameter) public Mandates_Versions;
///@dev Current version of parameters related to law project process
uint Legislatif_Process_Version;
///@dev Current version of parameters related to delegation internal governance
uint Internal_Governance_Version;
/// @dev Id in {Mandate} mapping of the current mandate
uint Actual_Mandate;
/// @dev Boolean set whether we are in election stage or not.
bool In_election_stage;
/**
* @param Name name of the Institution
* @param Initial_members List of initial members of the delegation
* @param token_address Address of {DemoCoin} token that will be used to transfert initial token amount to new registered citizens
* @param citizen_address Address of the {Citizens_Register} contract used in the Project
* @param agora_address Address of the {Agora} contract used in the project.
*/
constructor(string memory Name, address[] memory Initial_members, address token_address, address citizen_address, address agora_address) Institution(Name) {
Type_Institution = Institution_Type.DELEGATION;
Democoin = DemoCoin(token_address);
Citizens = Citizens_Register(citizen_address);
Agora_address = agora_address;
Mandates[0].Set_First_Mandate( Initial_members);
}
/*Members Election related functions*/
/**
* @dev Function called by a citizen who wish to candidate to next mandate's elections.
*/
function Candidate_Election() external override Citizen_Only{
require(!In_election_stage, "Election Time");
Mandates[Actual_Mandate].Add_Candidats(msg.sender);
emit New_Candidat(msg.sender);
}
/**
* @dev Function called by a citizen who wish to remove his candidature from next mandate's elections.
*/
function Remove_Candidature()external override{
require(!In_election_stage, "Election Time");
Mandates[Actual_Mandate].Remove_Candidats(msg.sender);
emit Remove_Candidat(msg.sender);
}
/**
* @dev When the current mandate duration is over or if the {New_Election_Petition_Rate} (see {Mandate} struct of {Delegation_Uils} library) is reached, any citizen can call this function to start a new election
*/
function New_Election() external override Citizen_Only {
require(!In_election_stage, "An Election is Pending");
uint num_mandate = Actual_Mandate;
if(Delegation_Uils.New_Election(Mandates,Mandates_Versions[Mandates[num_mandate].Version], num_mandate, address(Citizens))){
In_election_stage= true;
emit New_election(keccak256(abi.encodePacked(address(this),block.timestamp)));
}else{
uint new_mandate_num = num_mandate+1;
Actual_Mandate = new_mandate_num;
Mandates[new_mandate_num].Version = Internal_Governance_Version;
emit New_Mandate();
}
}
/**
* @dev Function can be called by a citizen to sign petition for a new election
*/
function Sign_New_Election_Petition() external override Citizen_Only{
uint num_mandate = Actual_Mandate;
Mandates[num_mandate].Sign_Petition(Mandates_Versions[Mandates[num_mandate].Version].Immunity_Duration, msg.sender);
emit Sign();
}
/**
* @dev When voting stage is over, any citizen can call this function to end the election and start a new mandate.
*/
function End_Election()external override {
require(In_election_stage, "Not in Election time");
uint num_mandate = Actual_Mandate;
//uint new_num_mandate = num_mandate.add(1);
In_election_stage=false;
Actual_Mandate = num_mandate + 1;
emit New_Mandate();
Delegation_Uils.Transition_Mandate(Mandates, Mandates_Versions[Mandates[num_mandate].Version].Ivote_address, num_mandate, Internal_Governance_Version);
}
/*Legislatif Process related functions*/
/**
* @dev Function can be called by a delegation member to submit a new law project. This function put {Law_Initialisation_Price} (see {Law_Project_Parameters} struct of {Delegation_Uils library}) DemoCoin token of Delegation contract in Escrow.
* @param register_address Address of the register contract the law project is about. Must be contained in Controled_Registers mapping.
* @param Title Title of the law project. Can be an hash.
* @param Description Text explaining the spirit and generals goals of the law project. Can be an hash.
*/
function Add_Law_Project(address register_address, bytes calldata Title, bytes calldata Description)external override Delegation_Only{
//_Update_Law_Project();
require(Controled_Registers[register_address].Active, "Register Not Controled");
bytes32 key = keccak256(abi.encode(Title,Description));
require(Delegation_Law_Projects[key].Version==0,"Law project already created");
uint version =Legislatif_Process_Version;
Delegation_Law_Projects[key].Version = version;
Token_Consumption_Handler(msg.sender, Law_Parameters_Versions[version].Law_Initialisation_Price, key);
Delegation_Law_Projects[key].Institution_Address = register_address;
Delegation_Law_Projects[key].Creation_Timestamp = block.timestamp;
List_Delegation_Law_Projects.push(key);
List_Law_Project[key].Title = Title;
List_Law_Project[key].Description = Description;
Controled_Registers[register_address].Law_Project_Counter++;
emit New_Law(key);
}
/**
* @dev Function can be called by a delegation member to submit a corpus of function calls propositions to an existing pending law project. This function put in Escrow {FunctionCall_Price} (see {Law_Project_Parameters} struct of {Delegation_Uils library}) DemoCoin token
* multiplied by the number of function call contained in the proposition.
* @param law_project Id of the law project hte caller wants to add a proposition to. The Id is obtained by hashing the Title with the Description of the law project.
* @param Parent Proposition Id the caller wants to attach his proposition to. It's the parent proposition in the proposal tree. If there isn't any proposition in the tree we want to attach the new proposition to, we set Parent to 0
* @param Parent_Proposals_Reuse List of Parent's function calls index we want to reuse in the new proposition. Function calls are ordered in the order we want them to be executed. 0 elements correspond to new function calls that have to be added by the caller in {New_Function_Call} argument.
* @param New_Function_Call List of new function calls added by the caller. For each element of the New_Function_Call array, caller must set a 0 element in {Parent_Proposals_Reuse} array at the index he want the custom function call to be positioned
* @param Description Text to justify the new proposal. Can be an hash.
*/
function Add_Proposal(bytes32 law_project, uint Parent, uint[] calldata Parent_Proposals_Reuse, bytes[] calldata New_Function_Call, bytes calldata Description) external override Delegation_Only{
require(Delegation_Law_Projects[law_project].Law_Project_Status == Status.PROPOSITION, "Not at PROPOSITION status");
uint version = Delegation_Law_Projects[law_project].Version;
require( version != 0, "No existing Law Project");
Token_Consumption_Handler(msg.sender, Law_Parameters_Versions[version].FunctionCall_Price.mul(New_Function_Call.length), law_project);
uint proposal_index = List_Law_Project[law_project].Proposal_Count.add(1);
List_Law_Project[law_project].Proposals_Tree[proposal_index].Author = msg.sender;
List_Law_Project[law_project].Add_Corpus_Proposal(Parent, Parent_Proposals_Reuse, New_Function_Call, Description);
emit New_Proposal( law_project, proposal_index);
}
/**
* @dev Function can be called by a delegation member to add function calls to a proposition that he has already created (He have to be the author of the proposition).
* Caller must approve {FunctionCall_Price} (see {Law_Project_Parameters} struct of {Delegation_Uils library})
* multiplied by the number of function call he wants to add to the proposition, token for Delegation contract.
* @param law_project Id of the law project the caller wants to add a proposition to. The Id is obtained by hashing the Title with the Description of the law project.
* @param Proposal Proposition Id to modify.
* @param New_Items Array of new function calls to add to the Proposition.
* @param Indexs array of Proposition's function call list indexs to inser new function call (contained in {New_Items}) to. {New_Items} and {Indexs} have the same length.
*/
function Add_Item(bytes32 law_project, uint Proposal, bytes[] calldata New_Items, uint[] calldata Indexs) external override Delegation_Only{
require(Delegation_Law_Projects[law_project].Law_Project_Status == Status.PROPOSITION, "Law Not at PROPOSITION status");
uint version = Delegation_Law_Projects[law_project].Version;
require( version != 0, "No existing Law Project");
Token_Consumption_Handler(msg.sender, Law_Parameters_Versions[version].FunctionCall_Price.mul(New_Items.length), law_project);
List_Law_Project[law_project].Add_Item_Proposal( Proposal, New_Items, Indexs, msg.sender);
emit Proposal_Modified(law_project, Proposal);
}
/**
* @dev When the period of proposition submiting is over, any citizen can call this function to start the voting stage. The Id of the ballot corresponding to current law project the IVote contract is computed by hashing {law_project} Id with current block timestamps.
* @param law_project Id of the law project the caller wants to add a proposition to. The Id is obtained by hashing the Title with the Description of the law project.
*/
function Start_Vote(bytes32 law_project)external override Delegation_Only{
uint version = Delegation_Law_Projects[law_project].Version;
require( version != 0, "No existing Law Project");
require(Delegation_Law_Projects[law_project].Law_Project_Status == Status.PROPOSITION, "Law Not at PROPOSITION status");
require(block.timestamp.sub(Delegation_Law_Projects[law_project].Creation_Timestamp) > Law_Parameters_Versions[version].Proposition_Duration, "PROPOSITION stage not finished");
bytes32 key=keccak256(abi.encodePacked(law_project,block.timestamp));
Delegation_Law_Projects[law_project].Start_Vote_Timestamps = block.timestamp;
Delegation_Law_Projects[law_project].Law_Project_Status = Status.VOTE;
emit Voting_Stage_Started(law_project, key);
IVote Vote_Instance = IVote(Law_Parameters_Versions[version].Ivote_address);
Vote_Instance.Create_Ballot(key, address(this), Contains_Function_Selector, Law_Parameters_Versions[version].Vote_Duration,0, List_Law_Project[law_project].Proposal_Count, 1);
}
/**
* @dev When the voting period is over, any citizen can call this function to end the voting stage. If the winning proposition is the default proposition is the default one (Proposition 0) the law proejct is aborted. Otherwise, the Law Censoring stage is started.
* @param law_project Id of the law project the caller wants to add a proposition to. The Id is obtained by hashing the Title with the Description of the law project.
*/
function Achiev_Vote(bytes32 law_project) external override Delegation_Only{
IVote Vote_Instance = IVote(Law_Parameters_Versions[Delegation_Law_Projects[law_project].Version].Ivote_address);
bytes32 key = keccak256(abi.encodePacked(law_project,Delegation_Law_Projects[law_project].Start_Vote_Timestamps));
uint winning_proposal= Vote_Instance.Get_Winning_Proposition_byId(key,0);
List_Law_Project[law_project].Winning_Proposal = winning_proposal;
if(winning_proposal==0){
Delegation_Law_Projects[law_project].Law_Project_Status = Status.ABORTED;
emit Law_Aborted(law_project);
}else{
Delegation_Law_Projects[law_project].Start_Censor_Law_Period_Timestamps = block.timestamp;
Delegation_Law_Projects[law_project].Law_Project_Status = Status.CENSOR_LAW_PERIOD;
emit Voting_Stage_Achieved(law_project);
}
}
/**
* @dev If we are at the Law censor stage, any citizen can call this function to sign the petition for canceling the law project. If the {Censor_Proposition_Petition_Rate} (see {Law_Project_Parameters} structure) is reached, the law project is aborted.
* @param law_project Id of the law project the caller wants to add a proposition to. The Id is obtained by hashing the Title with the Description of the law project.
*/
function Censor_Law(bytes32 law_project)external override Citizen_Only{
require(Delegation_Law_Projects[law_project].Law_Project_Status == Status.CENSOR_LAW_PERIOD, "Law Not at CENSOR LAW status");
require(!Delegation_Law_Projects[law_project].Censor_Law_Petitions[msg.sender], "Already Signed");
uint counter =Delegation_Law_Projects[law_project].Censor_Law_Petition_Counter.add(1);
Delegation_Law_Projects[law_project].Censor_Law_Petitions[msg.sender]=true;
if(counter>= Percentage(Law_Parameters_Versions[Delegation_Law_Projects[law_project].Version].Censor_Proposition_Petition_Rate, Citizens.Get_Citizen_Number())){ //If the number of censure petitions signatures reach the minimum ratio.
uint law_total_potentialy_lost = Delegation_Law_Projects[law_project].Law_Total_Potentialy_Lost;
Delegation_Law_Projects[law_project].Law_Project_Status = Status.ABORTED;
Potentialy_Lost_Amount = Potentialy_Lost_Amount.sub(law_total_potentialy_lost);
Update_Controled_Registers(Delegation_Law_Projects[law_project].Institution_Address);
Democoin.transfer(Agora_address,law_total_potentialy_lost);
emit Law_Aborted(law_project);
}
Delegation_Law_Projects[law_project].Censor_Law_Petition_Counter = counter;
}
/**
* @dev If the Law censor period is over and the law project hasn't been rejected by citizens, then any delegation member can call this function to set the law project as ADOPTED (see {Status} enumeration).
* @param law_project Id of the law project the caller wants to add a proposition to. The Id is obtained by hashing the Title with the Description of the law project.
*/
function Adopt_Law(bytes32 law_project)external override Delegation_Only{
require(Delegation_Law_Projects[law_project].Law_Project_Status == Status.CENSOR_LAW_PERIOD, "Law Not at CENSOR LAW status");
require(block.timestamp.sub(Delegation_Law_Projects[law_project].Start_Censor_Law_Period_Timestamps) > Law_Parameters_Versions[Delegation_Law_Projects[law_project].Version].Law_Censor_Period_Duration, "CENSOR LAW PERIOD not over");
Delegation_Law_Projects[law_project].Law_Project_Status = Status.ADOPTED;
emit Law_Adopted(law_project);
}
/**
* @dev Once the law project has been adopted (ADOPTED value of {Status} enum) then any delegation member can call this function to execute all or some of the remaining function call of the winning proposition.
* For the law project to be fully executed all function call have to be executed.
* @param law_project Id of the law project the caller wants to add a proposition to. The Id is obtained by hashing the Title with the Description of the law project.
* @param num_function_call_ToExecute Number of function calls to execute.
*/
function Execute_Law(bytes32 law_project, uint num_function_call_ToExecute)external override Delegation_Only nonReentrant{
require(Delegation_Law_Projects[law_project].Law_Project_Status == Status.ADOPTED, "Law Not ADOPTED");
emit Function_Call_Executed( law_project, num_function_call_ToExecute);
if(List_Law_Project[law_project].Execute_Winning_Proposal(num_function_call_ToExecute, Delegation_Law_Projects[law_project].Institution_Address)){
Delegation_Law_Projects[law_project].Law_Project_Status = Status.EXECUTED;
Potentialy_Lost_Amount = Potentialy_Lost_Amount.sub(Delegation_Law_Projects[law_project].Law_Total_Potentialy_Lost);
Update_Controled_Registers(Delegation_Law_Projects[law_project].Institution_Address);
emit Law_executed(law_project);
}
}
/*Constitution_Only Delegation parameters initialisation*/
/**
* @dev See {IDelegation} interface
*/
function Update_Legislatif_Process(uint[6] calldata Uint256_Legislatifs_Arg, uint16 Censor_Proposition_Petition_Rate,
uint16 Censor_Penalty_Rate, address Ivote_address)external override Constitution_Only{
uint version = Legislatif_Process_Version.add(1);
Law_Parameters_Versions[version].Update_Law_Parameters(Uint256_Legislatifs_Arg, Censor_Proposition_Petition_Rate,
Censor_Penalty_Rate, Ivote_address);
/*Law_Parameters_Versions[version].Member_Max_Token_Usage = Uint256_Legislatifs_Arg[0];
Law_Parameters_Versions[version].Law_Initialisation_Price = Uint256_Legislatifs_Arg[1];
Law_Parameters_Versions[version].FunctionCall_Price = Uint256_Legislatifs_Arg[2];
Law_Parameters_Versions[version].Proposition_Duration = Uint256_Legislatifs_Arg[3];
Law_Parameters_Versions[version].Vote_Duration = Uint256_Legislatifs_Arg[4];
Law_Parameters_Versions[version].Law_Censor_Period_Duration = Uint256_Legislatifs_Arg[5];
Law_Parameters_Versions[version].Censor_Proposition_Petition_Rate = Censor_Proposition_Petition_Rate;
Law_Parameters_Versions[version].Censor_Penalty_Rate = Censor_Penalty_Rate;
Law_Parameters_Versions[version].Ivote_address = Ivote_address;*/
Legislatif_Process_Version = version;
emit Legislatif_Parameters_Updated();
}
/**
* @dev See {IDelegation} interface
*/
function Update_Internal_Governance( uint Election_Duration, uint Validation_Duration, uint Mandate_Duration, uint Immunity_Duration,
uint16 Num_Max_Members, uint16 New_Election_Petition_Rate, address Ivote_address)external override Constitution_Only{
uint version = Internal_Governance_Version.add(1);
Mandates_Versions[version].Update_Mandate_Parameter(Election_Duration, Validation_Duration, Mandate_Duration, Immunity_Duration,
Num_Max_Members, New_Election_Petition_Rate, Ivote_address);
/*Mandates_Versions[version].Election_Duration = Election_Duration;
Mandates_Versions[version].Validation_Duration = Validation_Duration;
Mandates_Versions[version].Mandate_Duration = Mandate_Duration;
Mandates_Versions[version].Immunity_Duration = Immunity_Duration;
Mandates_Versions[version].Num_Max_Members = Num_Max_Members;
Mandates_Versions[version].New_Election_Petition_Rate = New_Election_Petition_Rate;
Mandates_Versions[version].Ivote_address = Ivote_address;*/
Internal_Governance_Version = version;
emit Governance_Parameters_Updated();
}
/**
* @dev See {IDelegation} interface
* */
function Add_Controled_Register(address register_address) external override Constitution_Only {
require(!Controled_Registers[register_address].Active, "Register already Controled");
Controled_Registers[register_address].Active = true;
List_Controled_Registers.add(register_address);
emit Controled_Register_Added(register_address);
}
/**
* @dev See {IDelegation} interface
* */
function Remove_Controled_Register(address register_address) external override Constitution_Only {
require(Controled_Registers[register_address].Active, "Register Not Controled");
Controled_Registers[register_address].Active = false;
if(Controled_Registers[register_address].Law_Project_Counter ==0){
Register(register_address).Remove_Authority(address(this));
List_Controled_Registers.remove(register_address);
emit Controled_Register_Removed(register_address);
}else{
emit Controled_Register_Canceled(register_address);
}
}
/*Utils*/
/**
* @notice Handle token consumption in the context of law project elaboration
* @dev The function: check that:
* - check that the member's max token consumption limit for the current law project isn't exceeded by the sender
* - check that the Delegation has enough funds to afford penalties if current pending were to be reverted by citizens.
* - Update the value of the amount of token consumed by the sender for the law project identified by "key".
* - Update the "Law_Total_Potentialy_Lost" field of the corresponding "Delegation_Law_Project" struct.
* - Update the "Potentialy_Lost_Amount" state variable
*
* @param sender Address of the sender of the transaction
* @param amount Amount of DemoCoin sent in the transaction
* @param key Id of the law project
* */
function Token_Consumption_Handler(address sender, uint amount, bytes32 key) internal{
uint version = Delegation_Law_Projects[key].Version;
require(Delegation_Law_Projects[key].Members_Token_Consumption[sender] +amount <= Law_Parameters_Versions[version].Member_Max_Token_Usage, "Member consumption exceeded");
uint amount_potentialy_lost = Percentage(Law_Parameters_Versions[version].Censor_Penalty_Rate, amount);
uint new_potentialy_lost_amount = Potentialy_Lost_Amount.add(amount_potentialy_lost);
require(new_potentialy_lost_amount <= Democoin.balanceOf(address(this)), "No enough colaterals funds");
Delegation_Law_Projects[key].Members_Token_Consumption[sender] += amount;
Delegation_Law_Projects[key].Law_Total_Potentialy_Lost = Delegation_Law_Projects[key].Law_Total_Potentialy_Lost.add(amount_potentialy_lost);
Potentialy_Lost_Amount = new_potentialy_lost_amount;
}
/**
* @dev Decrease the counter ("Law_Project_Counter" field of Controlable_Register struct) of pending law project related to the register of address "institution_address". If the counter becomes null and the "Actual" field of Controlable_Registers struct is false,
* then the corresponding register is removed from List_Controled_Registers and the delegation removes it self from the register's Authorithies list ("Register_Authorities" state variable)
* @param institution_address Address of the controled register to be updated.
*/
function Update_Controled_Registers(address institution_address) internal{
uint counter = Controled_Registers[institution_address].Law_Project_Counter.sub(1);
Controled_Registers[institution_address].Law_Project_Counter = counter;
if(counter==0 && !Controled_Registers[institution_address].Active){
Register(institution_address).Remove_Authority(address(this));
List_Controled_Registers.remove(institution_address);
}
}
/*Getters*/
/**
* @dev See {IDelegation} interface
*
*/
function Contains(address member_address) external view override returns(bool contain){
return Mandates[Actual_Mandate].Members.contains(member_address);
}
/**
* @dev Get 2 arrays:
* - The list of law project Id
* - The list of controled Register
* @return Law_Project_List List of law project (pending, executed and aborted)
* @return Controled_Register List of register address (represented in bytes32) whose contract is under Delegation control
*/
function Get_List_Law_Register()external view returns(bytes32[] memory Law_Project_List, bytes32[] memory Controled_Register ){
return (List_Delegation_Law_Projects, List_Controled_Registers._inner._values);
}
/**
* @dev Get informations about a mandate
* @param Id Id of the mandate
* @return version Parameter Version used for this mandate
* @return Inauguration_Timestamps Inauguration_Timestamps: Beginning of current mandate
* @return Election_Timestamps Beginning of election
* @return New_Election_Petition_Number Number of signatures obtained for revoking the delegation members related to {Id} Mandate
* @return Members Array of {Id} mandate delegation member's address (represented in bytes32)
* @return Candidats Array candidats address (represented in bytes32)
*/
function Get_Mandate(uint Id)external view returns(uint version, uint Inauguration_Timestamps, uint Election_Timestamps, uint New_Election_Petition_Number, bytes32[] memory Members, bytes32[] memory Candidats){
version = Mandates[Id].Version;
Inauguration_Timestamps = Mandates[Id].Inauguration_Timestamps;
Election_Timestamps= Mandates[Id].Election_Timestamps;
New_Election_Petition_Number=Mandates[Id].New_Election_Petitions.length();
Members = Mandates[Id].Members._inner._values;
Candidats = Mandates[Id].Next_Mandate_Candidats._inner._values;
}
/**
* @dev Get the amount of DemoCoin token owned by the Delegation and used by a Delegation member for a specific delegation law project.
* @param key Id of law project
* @param member Address of delegation member
* @return amount Amount of token used by {member} address for {key} law project
*
*/
function Get_Member_Amount_Consumed(bytes32 key, address member)external view returns(uint amount){
return Delegation_Law_Projects[key].Members_Token_Consumption[member];
}
/**
* @dev Get various Delegation state variables values.
* @return legislatif_process_version Current version of parameters related to delegation law project process.
* @return internal_governance_version Current version of parameters related to delegation internal governance.
* @return actual_mandate Id number of the current mandate
* @return potentialy_lost_amount Total amount of token potentially lost via penalty fee.
* @return in_election_stage Boolean assesing whether we are in election stage or not.
*/
function Get_Delegation_Infos()external view returns (uint legislatif_process_version, uint internal_governance_version, uint actual_mandate, uint potentialy_lost_amount, bool in_election_stage){
return (Legislatif_Process_Version, Internal_Governance_Version, Actual_Mandate, Potentialy_Lost_Amount, In_election_stage);
}
/**
* @dev Get informations about a law project proposition
* @param key Id of the law project
* @param id Id of the proposition
* @return description Description of the proposition
* @return childrens Proposition node's children in the Proposal Tree. (See {Add_Corpus_Proposal} function of {Initiative_Legislative_Lib} library)
* @return function_calls List of function calls proposed by the proposition
* @return func_call_counter Number of function calls proposed by the proposition.
* @return parent Id of the proposition's parent in the Proposal Tree
* @return author Address of the author of the proposition.
*/
function Get_Proposal(bytes32 key, uint id)external view returns(bytes memory description, uint[] memory childrens, bytes[] memory function_calls, uint func_call_counter, uint parent, address author){
function_calls = List_Law_Project[key].Get_Proposal_FunctionCall_List(id);
(description, childrens,func_call_counter, parent, author) = List_Law_Project[key].Get_Proposal_Infos(id);
}
/**
* @dev Get Results of a law project
* @return Winning_Proposal Id of the proposition that has been voted.
* @return Receipts List of receipts of {Winning_Proposal} function call's execution.
*/
function Get_Law_Results(bytes32 key)external view returns(uint Winning_Proposal, Initiative_Legislative_Lib.Function_Call_Result[] memory Receipts){
return(List_Law_Project[key].Winning_Proposal, List_Law_Project[key].Function_Call_Receipts);
}
}
|
Function used for updating parameters related to the democratic process of rmembers election. See {Update_Internal_Governance] function of {Delegation} or {IDelegation} contract
|
function Update_Mandate_Parameter(Mandate_Parameter storage mandate_param, uint Election_Duration, uint Validation_Duration, uint Mandate_Duration, uint Immunity_Duration,
uint16 Next_Mandate_Max_Members, uint16 New_Election_Petition_Rate, address Ivote_address) external {
mandate_param.Election_Duration = Election_Duration;
mandate_param.Validation_Duration = Validation_Duration;
mandate_param.Mandate_Duration = Mandate_Duration;
mandate_param.Immunity_Duration = Immunity_Duration;
mandate_param.Next_Mandate_Max_Members = Next_Mandate_Max_Members;
mandate_param.New_Election_Petition_Rate = New_Election_Petition_Rate;
mandate_param.Ivote_address = Ivote_address;
emit Governance_Parameters_Updated();
}
| 12,618,253
|
pragma solidity ^0.4.11;
/**
* @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) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @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() {
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) onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/*
* Haltable
* emergency stop mechanism. Differs from Pausable by causing a throw when in halt mode.
* Originally envisioned in FirstBlood ICO contract.
*/
contract Haltable is Ownable {
bool public halted;
modifier stopInEmergency {
require(!halted);
_;
}
modifier stopNonOwnersInEmergency {
require(!halted && msg.sender == owner);
_;
}
modifier onlyInEmergency {
require(halted);
_;
}
// called by the owner on emergency, triggers stopped state
function halt() external onlyOwner {
halted = true;
}
// called by the owner on end of emergency, returns to normal state
function unhalt() external onlyOwner onlyInEmergency {
halted = false;
}
}
/**
* @title RefundVault
* @dev This contract is used for storing funds while a crowdsale
* is in progress. Supports refunding the money if crowdsale fails,
* and forwarding it if crowdsale is successful.
*/
contract RefundVault is Ownable {
using SafeMath for uint256;
enum State { Active, Refunding, Closed }
mapping (address => uint256) public deposited;
address public wallet;
State public state;
event Closed();
event RefundsEnabled();
event Refunded(address indexed beneficiary, uint256 weiAmount);
function RefundVault(address _wallet) {
require(_wallet != 0x0);
wallet = _wallet;
state = State.Active;
}
function deposit(address investor) onlyOwner payable {
require(state == State.Active);
deposited[investor] = deposited[investor].add(msg.value);
}
function close() onlyOwner payable {
require(state == State.Active);
state = State.Closed;
Closed();
wallet.transfer(this.balance);
}
function enableRefunds() onlyOwner {
require(state == State.Active);
state = State.Refunding;
RefundsEnabled();
}
function refund(address investor) payable {
require(state == State.Refunding);
uint256 depositedValue = deposited[investor];
deposited[investor] = 0;
investor.transfer(depositedValue);
Refunded(investor, depositedValue);
}
}
/**
* @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) returns (bool) {
require(_to != address(0));
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
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) constant returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @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 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 amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
require(_to != address(0));
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve 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) 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;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_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
*/
function increaseApproval (address _spender, uint _addedValue)
returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue)
returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Harbor 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 HarborToken is StandardToken, Ownable {
//define HarborToken
string public constant name = "HarborToken";
string public constant symbol = "HBR";
uint8 public constant decimals = 18;
/** List of agents that are allowed to create new tokens */
mapping (address => bool) public mintAgents;
event Mint(address indexed to, uint256 amount);
event MintOpened();
event MintFinished();
event MintingAgentChanged(address addr, bool state );
event BurnToken(address addr,uint256 amount);
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier onlyMintAgent() {
// Only crowdsale contracts are allowed to mint new tokens
require(mintAgents[msg.sender]);
_;
}
/**
* Owner can allow a crowdsale contract to mint new tokens.
*/
function setMintAgent(address addr, bool state) onlyOwner canMint public {
mintAgents[addr] = state;
MintingAgentChanged(addr, state);
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyMintAgent canMint returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(0x0, _to, _amount);
return true;
}
/**
* @dev Function to burn down tokens
* @param _addr The address that will burn the tokens.
* @param _amount The amount of tokens to burn.
* @return A boolean that indicates if the burn up was successful.
*/
function burn(address _addr,uint256 _amount) onlyMintAgent canMint returns (bool) {
require(_amount > 0);
totalSupply = totalSupply.sub(_amount);
balances[_addr] = balances[_addr].sub(_amount);
BurnToken(_addr,_amount);
return true;
}
/**
* @dev Function to resume minting new tokens.
* @return True if the operation was successful.
*/
function openMinting() onlyOwner returns (bool) {
mintingFinished = false;
MintOpened();
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
/**
* @title HarborPresale
*/
contract HarborPresale is Haltable {
using SafeMath for uint256;
// The token being sold
HarborToken public token;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
// address where funds are excutionFunds
address public wallet;
// how many token units a buyer gets per wei
uint256 public rate;
// amount of raised money in wei
uint256 public weiRaised;
//max amount of funds raised
uint256 public cap;
//is crowdsale end
bool public isFinalized = false;
// minimum amount of funds to be raised in weis
uint256 public minimumFundingGoal;
// minimum amount of funds for once
uint256 public minSend;
// refund vault used to hold funds while crowdsale is running
RefundVault public vault;
//How many tokens were Minted
uint public tokensMinted;
//presale buyers
mapping (address => uint256) public tokenDeposited;
//event for crowdsale end
event Finalized();
//event for presale mint
event TokenMinted(uint count);
// We distributed tokens to an investor
event Distributed(address investor, uint tokenAmount);
//presale period is Changed
event PeriodChanged(uint256 starttm,uint256 endtm);
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param investor who participate presale
* @param value weis paid for purchase
*/
event TokenPurchase(address indexed purchaser, address indexed investor, uint256 value);
function HarborPresale(address _token, uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, uint256 _cap, uint256 _minimumFundingGoal, uint256 _minSend) {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_rate > 0);
require(_wallet != 0x0);
require(_cap > 0);
require(_minimumFundingGoal > 0);
token = HarborToken(_token);
startTime = _startTime;
endTime = _endTime;
rate = _rate;
wallet = _wallet;
cap = _cap;
vault = new RefundVault(_wallet);
minimumFundingGoal = _minimumFundingGoal;
minSend = _minSend;
}
// fallback function can be used to buy tokens
function () payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address investor) payable stopInEmergency {
require(investor != 0x0);
require(validPurchase());
require(minSend <= msg.value);
uint256 weiAmount = msg.value;
// update state
weiRaised = weiRaised.add(weiAmount);
//save for distribution HBR
tokenDeposited[investor] = tokenDeposited[investor].add(weiAmount);
//valut save for refund
vault.deposit.value(msg.value)(msg.sender);
TokenPurchase(msg.sender, investor, weiAmount);
}
/**
* Load funds to the crowdsale for all investors.
*/
function mintForEverybody() onlyOwner public {
uint256 allTokenAmount = weiRaised.mul(rate);
//for project amount (investor token *2/3)
uint256 projectAmount = allTokenAmount.mul(2);
projectAmount = projectAmount.div(3);
//mint for investor;
token.mint(address(this),allTokenAmount);
//mint for project share
token.mint(wallet,projectAmount);
// Record how many tokens we got
tokensMinted = allTokenAmount.add(projectAmount);
TokenMinted(tokensMinted);
}
//get claim of token byself
function claimToken() payable stopInEmergency{
claimTokenAddress(msg.sender);
}
//get claim of token by address
function claimTokenAddress(address investor) payable stopInEmergency returns(uint256){
require(isFinalized);
require(tokenDeposited[investor] != 0);
uint256 depositedValue = tokenDeposited[investor];
tokenDeposited[investor] = 0;
uint256 tokenAmount = depositedValue * rate;
//send token to investor
token.transfer(investor,tokenAmount);
Distributed(investor, tokenAmount);
return tokenAmount;
}
// @return true if the transaction can buy tokens
function validPurchase() internal constant returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
bool withinCap = weiRaised <= cap;
return withinPeriod && nonZeroPurchase && withinCap;
}
// @return true if HarborPresale event has ended
function hasEnded() public constant returns (bool) {
bool capReached = weiRaised >= cap;
return (now > endTime) || capReached ;
}
/**
* called after Presale ends
*/
function finalize() onlyOwner stopInEmergency{
require(!isFinalized);
require(hasEnded());
finalization();
Finalized();
isFinalized = true;
}
/**
* finalization refund or excute funds.
*/
function finalization() internal {
if (minFundingGoalReached()) {
vault.close();
} else {
vault.enableRefunds();
}
}
// if presale is unsuccessful, investors can claim refunds here
function claimRefund() stopInEmergency payable {
require(isFinalized);
require(!minFundingGoalReached());
vault.refund(msg.sender);
}
function minFundingGoalReached() public constant returns (bool) {
return weiRaised >= minimumFundingGoal;
}
//change presale preiod
function setPeriod(uint256 _startTime,uint256 _endTime) onlyOwner {
require(now <= _endTime);
startTime = _startTime;
endTime = _endTime;
PeriodChanged(startTime,endTime);
}
//withdrow for manual distribution
function withdrawFund() onlyOwner payable{
require(isFinalized);
require(minFundingGoalReached());
uint256 tokenAmount = token.balanceOf(address(this));
token.transfer(wallet, tokenAmount);
}
}
|
transfer token for a specified address _to The address to transfer to. _value The amount to be transferred./ SafeMath.sub will throw if there is not enough balance.
|
function transfer(address _to, uint256 _value) returns (bool) {
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
| 10,673,654
|
./full_match/137/0x2a8ecE1F5Ab7EC2e4a1963e3Ba36D7e6F3Bdc6D1/sources/src/NFTNameGenDrop.sol
|
,-. `-' /|\ | ,----------. / \ |ERC721Drop| Caller `----+-----' | purchasePresale() | | ----------------------------------> | | | | _________________________________________________________________ ! ALT / drop has no tokens left for caller to mint? ! !_____/ | | ! ! | revert Mint_SoldOut() | ! ! | <---------------------------------- ! !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! !~[noop]~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! | | | | _________________________________________________________________ ! ALT / presale sale isn't active? | ! !_____/ | | ! ! | revert Presale_Inactive() | ! ! | <---------------------------------- ! !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! !~[noop]~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! | | | | _________________________________________________________________ ! ALT / merkle proof unapproved for caller? | ! !_____/ | | ! ! | revert Presale_MerkleNotApproved()| ! ! | <---------------------------------- ! !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! !~[noop]~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! | | | | _________________________________________________________________ ! ALT / inadequate funds sent? | ! !_____/ | | ! ! | revert Purchase_WrongPrice() | ! ! | <---------------------------------- ! !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! !~[noop]~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! | | | |----. | | | mint tokens | |<---' | | | |----. | | | emit INFTNameGenDrop.Sale() | |<---' | | | return first minted token ID | | <---------------------------------- Caller ,----+-----. ,-. |ERC721Drop| `-' `----------' /|\ | / \ Merkle-tree based presale purchase function quantity quantity to purchase maxQuantity max quantity that can be purchased via merkle proof pricePerToken price that each token is purchased at merkleProof proof for presale mint address, uint256, uint256
|
function purchasePresale(
uint256 quantity,
uint256 maxQuantity,
uint256 pricePerToken,
bytes32[] calldata merkleProof
)
external
payable
nonReentrant
canMintTokens(quantity)
onlyPresaleActive
returns (uint256)
{
if (
!MerkleProofUpgradeable.verify(
merkleProof,
salesConfig.presaleMerkleRoot,
keccak256(
abi.encode(_msgSender(), maxQuantity, pricePerToken)
)
)
) {
revert Presale_MerkleNotApproved();
}
if (msg.value != pricePerToken * quantity) {
revert Purchase_WrongPrice(pricePerToken * quantity);
}
presaleMintsByAddress[_msgSender()] += quantity;
if (presaleMintsByAddress[_msgSender()] > maxQuantity) {
revert Presale_TooManyForAddress();
}
_mintNFTs(_msgSender(), quantity);
uint256 firstMintedTokenId = _lastMintedTokenId() - quantity;
emit INFTNameGenDrop.Sale({
to: _msgSender(),
quantity: quantity,
pricePerToken: pricePerToken,
firstPurchasedTokenId: firstMintedTokenId
});
return firstMintedTokenId;
}
| 4,684,379
|
pragma solidity 0.4.15;
import '../../Snapshot/Snapshot.sol';
import '../../Standards/ISnapshotToken.sol';
import './MMint.sol';
contract BasicSnapshotToken is
ISnapshotToken,
MMint,
Snapshot
{
////////////////////////
// Immutable state
////////////////////////
// `parentToken` is the Token address that was cloned to produce this token;
// it will be 0x0 for a token that was not cloned
ISnapshotTokenParent private PARENT_TOKEN;
// `parentSnapShotBlock` is the block number from the Parent Token that was
// used to determine the initial distribution of the Clone Token
uint256 private PARENT_SNAPSHOT;
////////////////////////
// Mutable state
////////////////////////
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes the block number that the change
// occurred is also included in the map
mapping (address => Values[]) private _balances;
// Tracks the history of the `totalSupply` of the token
Values[] private _totalSupplyValues;
////////////////////////
// Constructor
////////////////////////
/// @notice Constructor to create a MiniMeToken
/// @param parentToken Address of the parent token, set to 0x0 if it is a
/// new token
function BasicSnapshotToken(
ISnapshotTokenParent parentToken,
uint256 parentSnapshot
)
public
Snapshot()
{
PARENT_TOKEN = parentToken;
PARENT_SNAPSHOT = parentSnapshot;
}
////////////////////////
// Public functions
////////////////////////
//
// Implements IBasicToken
//
/// @dev This function makes it easy to get the total number of tokens
/// @return The total number of tokens
function totalSupply()
public
constant
returns (uint256)
{
return getValue(_totalSupplyValues, 0);
}
/// @param owner The address that's balance is being requested
/// @return The balance of `owner` at the current block
function balanceOf(address owner)
public
constant
returns (uint256 balance)
{
return getValue(_balances[owner], 0);
}
/// @notice Send `amount` tokens to `to` from `msg.sender`
/// @param to The address of the recipient
/// @param amount The amount of tokens to be transferred
/// @return True if the transfer was successful, reverts in any other case
function transfer(address to, uint256 amount)
public
returns (bool success)
{
mTransfer(msg.sender, to, amount);
return true;
}
//
// Implements ISnapshotTokenParent
//
/// @notice Total amount of tokens at a specific `snapshot`.
/// @param snapshot The block number when the totalSupply is queried
/// @return The total amount of tokens at `snapshot`
function totalSupplyAt(uint256 snapshot)
public
constant
returns(uint256)
{
Values[] storage values = _totalSupplyValues;
// If there is a value, return it
if (hasValueAt(values, snapshot)) {
return getValueAt(values, snapshot, 0);
}
// Try parent contract at or before the fork
if (address(PARENT_TOKEN) != 0) {
return PARENT_TOKEN.totalSupplyAt(PARENT_SNAPSHOT);
}
// Default to an empty balance
return 0;
}
/// @dev Queries the balance of `owner` at a specific `snapshot`
/// @param owner The address from which the balance will be retrieved
/// @param snapshot The block number when the balance is queried
/// @return The balance at `snapshot`
function balanceOfAt(address owner, uint256 snapshot)
public
constant
returns (uint256)
{
Values[] storage values = _balances[owner];
// If there is a value, return it
if (hasValueAt(values, snapshot)) {
return getValueAt(values, snapshot, 0);
}
// Try parent contract at or before the fork
if (address(PARENT_TOKEN) != 0) {
return PARENT_TOKEN.balanceOfAt(owner, PARENT_SNAPSHOT);
}
// Default to an empty balance
return 0;
}
////////////////////////
// Internal functions
////////////////////////
//
// Implements MMint
//
/// @dev This is the actual transfer function in the token contract, it can
/// only be called by other functions in this contract.
/// @param from The address holding the tokens being transferred
/// @param to The address of the recipient
/// @param amount The amount of tokens to be transferred
/// @return True if the transfer was successful, reverts in any other case
function mTransfer(
address from,
address to,
uint256 amount
)
internal
{
require(to != address(0));
// If the amount being transfered is more than the balance of the
// account the transfer reverts
var previousBalanceFrom = balanceOf(from);
require(previousBalanceFrom >= amount);
// First update the balance array with the new value for the address
// sending the tokens
uint256 newBalanceFrom = previousBalanceFrom - amount;
setValue(_balances[from], newBalanceFrom);
// Then update the balance array with the new value for the address
// receiving the tokens
uint256 previousBalanceTo = balanceOf(to);
uint256 newBalanceTo = previousBalanceTo + amount;
assert(newBalanceTo >= previousBalanceTo); // Check for overflow
setValue(_balances[to], newBalanceTo);
// An event to make the transfer easy to find on the blockchain
Transfer(from, to, amount);
}
/// @notice Generates `amount` tokens that are assigned to `owner`
/// @param owner The address that will be assigned the new tokens
/// @param amount The quantity of tokens generated
/// @return True if the tokens are generated correctly
function mGenerateTokens(address owner, uint256 amount)
internal
{
require(owner != address(0));
uint256 curTotalSupply = totalSupply();
uint256 newTotalSupply = curTotalSupply + amount;
require(newTotalSupply >= curTotalSupply); // Check for overflow
uint256 previousBalanceTo = balanceOf(owner);
uint256 newBalanceTo = previousBalanceTo + amount;
assert(newBalanceTo >= previousBalanceTo); // Check for overflow
setValue(_totalSupplyValues, newTotalSupply);
setValue(_balances[owner], newBalanceTo);
Transfer(0, owner, amount);
}
/// @notice Burns `amount` tokens from `owner`
/// @param owner The address that will lose the tokens
/// @param amount The quantity of tokens to burn
/// @return True if the tokens are burned correctly
function mDestroyTokens(address owner, uint256 amount)
internal
{
uint256 curTotalSupply = totalSupply();
require(curTotalSupply >= amount);
uint256 previousBalanceFrom = balanceOf(owner);
require(previousBalanceFrom >= amount);
uint256 newTotalSupply = curTotalSupply - amount;
uint256 newBalanceFrom = previousBalanceFrom - amount;
setValue(_totalSupplyValues, newTotalSupply);
setValue(_balances[owner], newBalanceFrom);
Transfer(owner, 0, amount);
}
}
|
Immutable state `parentToken` is the Token address that was cloned to produce this token; it will be 0x0 for a token that was not cloned `parentSnapShotBlock` is the block number from the Parent Token that was used to determine the initial distribution of the Clone Token Mutable state `balances` is the map that tracks the balance of each address, in this contract when the balance changes the block number that the change occurred is also included in the map Tracks the history of the `totalSupply` of the token Constructor
|
{
ISnapshotTokenParent private PARENT_TOKEN;
uint256 private PARENT_SNAPSHOT;
mapping (address => Values[]) private _balances;
Values[] private _totalSupplyValues;
function BasicSnapshotToken(
ISnapshotTokenParent parentToken,
uint256 parentSnapshot
)
public
Snapshot()
{
PARENT_TOKEN = parentToken;
PARENT_SNAPSHOT = parentSnapshot;
}
function totalSupply()
public
constant
returns (uint256)
{
return getValue(_totalSupplyValues, 0);
}
function balanceOf(address owner)
public
constant
returns (uint256 balance)
{
return getValue(_balances[owner], 0);
}
function transfer(address to, uint256 amount)
public
returns (bool success)
{
mTransfer(msg.sender, to, amount);
return true;
}
function totalSupplyAt(uint256 snapshot)
public
constant
returns(uint256)
{
Values[] storage values = _totalSupplyValues;
if (hasValueAt(values, snapshot)) {
return getValueAt(values, snapshot, 0);
}
if (address(PARENT_TOKEN) != 0) {
return PARENT_TOKEN.totalSupplyAt(PARENT_SNAPSHOT);
}
}
function totalSupplyAt(uint256 snapshot)
public
constant
returns(uint256)
{
Values[] storage values = _totalSupplyValues;
if (hasValueAt(values, snapshot)) {
return getValueAt(values, snapshot, 0);
}
if (address(PARENT_TOKEN) != 0) {
return PARENT_TOKEN.totalSupplyAt(PARENT_SNAPSHOT);
}
}
function totalSupplyAt(uint256 snapshot)
public
constant
returns(uint256)
{
Values[] storage values = _totalSupplyValues;
if (hasValueAt(values, snapshot)) {
return getValueAt(values, snapshot, 0);
}
if (address(PARENT_TOKEN) != 0) {
return PARENT_TOKEN.totalSupplyAt(PARENT_SNAPSHOT);
}
}
return 0;
function balanceOfAt(address owner, uint256 snapshot)
public
constant
returns (uint256)
{
Values[] storage values = _balances[owner];
if (hasValueAt(values, snapshot)) {
return getValueAt(values, snapshot, 0);
}
if (address(PARENT_TOKEN) != 0) {
return PARENT_TOKEN.balanceOfAt(owner, PARENT_SNAPSHOT);
}
}
function balanceOfAt(address owner, uint256 snapshot)
public
constant
returns (uint256)
{
Values[] storage values = _balances[owner];
if (hasValueAt(values, snapshot)) {
return getValueAt(values, snapshot, 0);
}
if (address(PARENT_TOKEN) != 0) {
return PARENT_TOKEN.balanceOfAt(owner, PARENT_SNAPSHOT);
}
}
function balanceOfAt(address owner, uint256 snapshot)
public
constant
returns (uint256)
{
Values[] storage values = _balances[owner];
if (hasValueAt(values, snapshot)) {
return getValueAt(values, snapshot, 0);
}
if (address(PARENT_TOKEN) != 0) {
return PARENT_TOKEN.balanceOfAt(owner, PARENT_SNAPSHOT);
}
}
return 0;
function mTransfer(
address from,
address to,
uint256 amount
)
internal
{
require(to != address(0));
var previousBalanceFrom = balanceOf(from);
require(previousBalanceFrom >= amount);
uint256 newBalanceFrom = previousBalanceFrom - amount;
setValue(_balances[from], newBalanceFrom);
uint256 previousBalanceTo = balanceOf(to);
uint256 newBalanceTo = previousBalanceTo + amount;
setValue(_balances[to], newBalanceTo);
Transfer(from, to, amount);
}
function mGenerateTokens(address owner, uint256 amount)
internal
{
require(owner != address(0));
uint256 curTotalSupply = totalSupply();
uint256 newTotalSupply = curTotalSupply + amount;
uint256 previousBalanceTo = balanceOf(owner);
uint256 newBalanceTo = previousBalanceTo + amount;
setValue(_totalSupplyValues, newTotalSupply);
setValue(_balances[owner], newBalanceTo);
Transfer(0, owner, amount);
}
function mDestroyTokens(address owner, uint256 amount)
internal
{
uint256 curTotalSupply = totalSupply();
require(curTotalSupply >= amount);
uint256 previousBalanceFrom = balanceOf(owner);
require(previousBalanceFrom >= amount);
uint256 newTotalSupply = curTotalSupply - amount;
uint256 newBalanceFrom = previousBalanceFrom - amount;
setValue(_totalSupplyValues, newTotalSupply);
setValue(_balances[owner], newBalanceFrom);
Transfer(owner, 0, amount);
}
}
| 5,515,034
|
./full_match/83/0x43dd7C74b4799F502B6fae3D18f44068FF8298e8/sources/contracts/OFT-upgradable/lzApp/LzAppUpgradeable.sol
|
generic config for LayerZero user Application
|
function setConfig(
uint16 _version,
uint16 _chainId,
uint256 _configType,
bytes calldata _config
) external override onlyAdmin {
lzEndpoint.setConfig(_version, _chainId, _configType, _config);
}
| 9,556,141
|
./full_match/1/0x2BB8de958134AFd7543d4063CaFAD0b7c6de08BC/sources/contracts/AllPairVault.sol
|
Set optional performance fee for Vault Only available before deposits are open _vaultId Vault to work on _performanceFee Percent fee, denominator is 10000/ emit PerformanceFeeSet(_vaultId, _performanceFee);
|
function setPerformanceFee(uint256 _vaultId, uint256 _performanceFee)
external
onlyStrategist(_vaultId)
atState(_vaultId, OLib.State.Inactive)
{
require(_performanceFee <= denominator, "Too high");
Vault storage vault_ = Vaults[_vaultId];
vault_.performanceFee = _performanceFee;
}
| 16,505,632
|
pragma solidity ^0.4.24;
/*
* -PlayerBook - v0.3.14
* ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐
* │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐
* ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘
* _____ _____
* (, / /) /) /) (, / /) /)
* ┌─┐ / _ (/_ // // / _ // _ __ _(/
* ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_
* ┴ ┴ / / .-/ _____ (__ /
* (__ / (_/ (, / /)™
* / __ __ __ __ _ __ __ _ _/_ _ _(/
* ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_
* ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ © Jekyll Island Inc. 2018
* ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/
* ______ _ ______ _
*====(_____ \=| |===============================(____ \===============| |=============*
* _____) )| | _____ _ _ _____ ____ ____) ) ___ ___ | | _
* | ____/ | | (____ || | | || ___ | / ___) | __ ( / _ \ / _ \ | |_/ )
* | | | | / ___ || |_| || ____|| | | |__) )| |_| || |_| || _ (
*====|_|=======\_)\_____|=\__ ||_____)|_|======|______/==\___/==\___/=|_|=\_)=========*
* (____/
* ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐
* ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ Inventor │
* ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘
*/
interface PlayerBookReceiverInterface {
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external;
function receivePlayerNameList(uint256 _pID, bytes32 _name) external;
}
contract PlayerBook {
using NameFilter for string;
using SafeMath for uint256;
address private admin = msg.sender;
//==============================================================================
// _| _ _|_ _ _ _ _|_ _ .
// (_|(_| | (_| _\(/_ | |_||_) .
//=============================|================================================
uint256 public registrationFee_ = 10 finney; // price to register a name
mapping(uint256 => PlayerBookReceiverInterface) public games_; // mapping of our game interfaces for sending your account info to games
mapping(address => bytes32) public gameNames_; // lookup a games name
mapping(address => uint256) public gameIDs_; // lokup a games ID
uint256 public gID_; // total number of games
uint256 public pID_; // total number of players
mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address
mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name
mapping (uint256 => Player) public plyr_; // (pID => data) player data
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amoungst any name you own)
mapping (uint256 => mapping (uint256 => bytes32)) public plyrNameList_; // (pID => nameNum => name) list of names a player owns
struct Player {
address addr;
bytes32 name;
uint256 laff;
uint256 names;
}
//==============================================================================
// _ _ _ __|_ _ __|_ _ _ .
// (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy)
//==============================================================================
constructor()
public
{
// premine the dev names (sorry not sorry)
// No keys are purchased with this method, it's simply locking our addresses,
// PID's and names for referral codes.
plyr_[1].addr = 0x33971deF18AC906cda3d7865b80c5C235Bf27E60;
plyr_[1].name = "justo";
plyr_[1].names = 1;
pIDxAddr_[0x33971deF18AC906cda3d7865b80c5C235Bf27E60] = 1;
pIDxName_["justo"] = 1;
plyrNames_[1]["justo"] = true;
plyrNameList_[1][1] = "justo";
pID_ = 1;
}
//==============================================================================
// _ _ _ _|. |`. _ _ _ .
// | | |(_)(_||~|~|(/_| _\ . (these are safety checks)
//==============================================================================
/**
* @dev prevents contracts from interacting with fomo3d
*/
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
modifier isRegisteredGame()
{
require(gameIDs_[msg.sender] != 0);
_;
}
//==============================================================================
// _ _ _ _|_ _ .
// (/_\/(/_| | | _\ .
//==============================================================================
// fired whenever a player registers a name
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
//==============================================================================
// _ _ _|__|_ _ _ _ .
// (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan)
//=====_|=======================================================================
function checkIfNameValid(string _nameStr)
public
view
returns(bool)
{
bytes32 _name = _nameStr.nameFilter();
if (pIDxName_[_name] == 0)
return (true);
else
return (false);
}
//==============================================================================
// _ |_ |. _ |` _ __|_. _ _ _ .
// |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract)
//====|=========================================================================
/**
* @dev registers a name. UI will always display the last name you registered.
* but you will still own all previously registered names to use as affiliate
* links.
* - must pay a registration fee.
* - name must be unique
* - names will be converted to lowercase
* - name cannot start or end with a space
* - cannot have more than 1 space in a row
* - cannot be only numbers
* - cannot start with 0x
* - name must be at least 1 char
* - max length of 32 characters long
* - allowed characters: a-z, 0-9, and space
* -functionhash- 0x921dec21 (using ID for affiliate)
* -functionhash- 0x3ddd4698 (using address for affiliate)
* -functionhash- 0x685ffd83 (using name for affiliate)
* @param _nameString players desired name
* @param _affCode affiliate ID, address, or name of who refered you
* @param _all set to true if you want this to push your info to all games
* (this might cost a lot of gas)
*/
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// filter name + condition checks
bytes32 _name = NameFilter.nameFilter(_nameString);
// set up address
address _addr = msg.sender;
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given, no new affiliate code was given, or the
// player tried to use their own pID as an affiliate code, lolz
if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID)
{
// update last affiliate
plyr_[_pID].laff = _affCode;
} else if (_affCode == _pID) {
_affCode = 0;
}
// register name
registerNameCore(_pID, _addr, _affCode, _name, _isNewPlayer, _all);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// filter name + condition checks
bytes32 _name = NameFilter.nameFilter(_nameString);
// set up address
address _addr = msg.sender;
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
uint256 _affID;
if (_affCode != address(0) && _affCode != _addr)
{
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// register name
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// filter name + condition checks
bytes32 _name = NameFilter.nameFilter(_nameString);
// set up address
address _addr = msg.sender;
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
uint256 _affID;
if (_affCode != "" && _affCode != _name)
{
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// register name
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
}
/**
* @dev players, if you registered a profile, before a game was released, or
* set the all bool to false when you registered, use this function to push
* your profile to a single game. also, if you've updated your name, you
* can use this to push your name to games of your choosing.
* -functionhash- 0x81c5b206
* @param _gameID game id
*/
function addMeToGame(uint256 _gameID)
isHuman()
public
{
require(_gameID <= gID_, "silly player, that game doesn't exist yet");
address _addr = msg.sender;
uint256 _pID = pIDxAddr_[_addr];
require(_pID != 0, "hey there buddy, you dont even have an account");
uint256 _totalNames = plyr_[_pID].names;
// add players profile and most recent name
games_[_gameID].receivePlayerInfo(_pID, _addr, plyr_[_pID].name, plyr_[_pID].laff);
// add list of all names
if (_totalNames > 1)
for (uint256 ii = 1; ii <= _totalNames; ii++)
games_[_gameID].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]);
}
/**
* @dev players, use this to push your player profile to all registered games.
* -functionhash- 0x0c6940ea
*/
function addMeToAllGames()
isHuman()
public
{
address _addr = msg.sender;
uint256 _pID = pIDxAddr_[_addr];
require(_pID != 0, "hey there buddy, you dont even have an account");
uint256 _laff = plyr_[_pID].laff;
uint256 _totalNames = plyr_[_pID].names;
bytes32 _name = plyr_[_pID].name;
for (uint256 i = 1; i <= gID_; i++)
{
games_[i].receivePlayerInfo(_pID, _addr, _name, _laff);
if (_totalNames > 1)
for (uint256 ii = 1; ii <= _totalNames; ii++)
games_[i].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]);
}
}
/**
* @dev players use this to change back to one of your old names. tip, you'll
* still need to push that info to existing games.
* -functionhash- 0xb9291296
* @param _nameString the name you want to use
*/
function useMyOldName(string _nameString)
isHuman()
public
{
// filter name, and get pID
bytes32 _name = _nameString.nameFilter();
uint256 _pID = pIDxAddr_[msg.sender];
// make sure they own the name
require(plyrNames_[_pID][_name] == true, "umm... thats not a name you own");
// update their current name
plyr_[_pID].name = _name;
}
//==============================================================================
// _ _ _ _ | _ _ . _ .
// (_(_)| (/_ |(_)(_||(_ .
//=====================_|=======================================================
function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer, bool _all)
private
{
// if names already has been used, require that current msg sender owns the name
if (pIDxName_[_name] != 0)
require(plyrNames_[_pID][_name] == true, "sorry that names already taken");
// add name to player profile, registry, and name book
plyr_[_pID].name = _name;
pIDxName_[_name] = _pID;
if (plyrNames_[_pID][_name] == false)
{
plyrNames_[_pID][_name] = true;
plyr_[_pID].names++;
plyrNameList_[_pID][plyr_[_pID].names] = _name;
}
// registration fee goes directly to community rewards
admin.transfer(address(this).balance);
// push player info to games
if (_all == true)
for (uint256 i = 1; i <= gID_; i++)
games_[i].receivePlayerInfo(_pID, _addr, _name, _affID);
// fire event
emit onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, msg.value, now);
}
//==============================================================================
// _|_ _ _ | _ .
// | (_)(_)|_\ .
//==============================================================================
function determinePID(address _addr)
private
returns (bool)
{
if (pIDxAddr_[_addr] == 0)
{
pID_++;
pIDxAddr_[_addr] = pID_;
plyr_[pID_].addr = _addr;
// set the new player bool to true
return (true);
} else {
return (false);
}
}
//==============================================================================
// _ _|_ _ _ _ _ | _ _ || _ .
// (/_>< | (/_| | |(_|| (_(_|||_\ .
//==============================================================================
function getPlayerID(address _addr)
isRegisteredGame()
external
returns (uint256)
{
determinePID(_addr);
return (pIDxAddr_[_addr]);
}
function getPlayerName(uint256 _pID)
external
view
returns (bytes32)
{
return (plyr_[_pID].name);
}
function getPlayerLAff(uint256 _pID)
external
view
returns (uint256)
{
return (plyr_[_pID].laff);
}
function getPlayerAddr(uint256 _pID)
external
view
returns (address)
{
return (plyr_[_pID].addr);
}
function getNameFee()
external
view
returns (uint256)
{
return(registrationFee_);
}
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given, no new affiliate code was given, or the
// player tried to use their own pID as an affiliate code, lolz
uint256 _affID = _affCode;
if (_affID != 0 && _affID != plyr_[_pID].laff && _affID != _pID)
{
// update last affiliate
plyr_[_pID].laff = _affID;
} else if (_affID == _pID) {
_affID = 0;
}
// register name
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
uint256 _affID;
if (_affCode != address(0) && _affCode != _addr)
{
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// register name
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
uint256 _affID;
if (_affCode != "" && _affCode != _name)
{
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// register name
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
//==============================================================================
// _ _ _|_ _ .
// _\(/_ | |_||_) .
//=============|================================================================
function addGame(address _gameAddress, string _gameNameStr)
public
{
require(gameIDs_[_gameAddress] == 0, "derp, that games already been registered");
gID_++;
bytes32 _name = _gameNameStr.nameFilter();
gameIDs_[_gameAddress] = gID_;
gameNames_[_gameAddress] = _name;
games_[gID_] = PlayerBookReceiverInterface(_gameAddress);
games_[gID_].receivePlayerInfo(1, plyr_[1].addr, plyr_[1].name, 0);
games_[gID_].receivePlayerInfo(2, plyr_[2].addr, plyr_[2].name, 0);
games_[gID_].receivePlayerInfo(3, plyr_[3].addr, plyr_[3].name, 0);
games_[gID_].receivePlayerInfo(4, plyr_[4].addr, plyr_[4].name, 0);
}
function setRegistrationFee(uint256 _fee)
public
{
registrationFee_ = _fee;
}
}
/**
* @title -Name Filter- v0.1.9
* ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐
* │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐
* ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘
* _____ _____
* (, / /) /) /) (, / /) /)
* ┌─┐ / _ (/_ // // / _ // _ __ _(/
* ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_
* ┴ ┴ / / .-/ _____ (__ /
* (__ / (_/ (, / /)™
* / __ __ __ __ _ __ __ _ _/_ _ _(/
* ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_
* ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ © Jekyll Island Inc. 2018
* ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/
* _ __ _ ____ ____ _ _ _____ ____ ___
*=============| |\ | / /\ | |\/| | |_ =====| |_ | | | | | | | |_ | |_)==============*
*=============|_| \| /_/--\ |_| | |_|__=====|_| |_| |_|__ |_| |_|__ |_| \==============*
*
* ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐
* ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ Inventor │
* ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘
*/
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);
}
}
/**
* @title SafeMath v0.1.9
* @dev Math operations with safety checks that throw on error
* change notes: original SafeMath library from OpenZeppelin modified by Inventor
* - added sqrt
* - added sq
* - added pwr
* - changed asserts to requires with error log outputs
* - removed div, its useless
*/
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;
require(c / a == b, "SafeMath mul failed");
return c;
}
/**
* @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, "SafeMath sub failed");
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, "SafeMath add failed");
return c;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
}
|
============================================================================== _ _ _ _ | _ _ . _ . (_(_)| (/_ |(_)(_||(_ .=====================_|======================================================= if names already has been used, require that current msg sender owns the name add name to player profile, registry, and name book
|
function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer, bool _all)
private
{
if (pIDxName_[_name] != 0)
require(plyrNames_[_pID][_name] == true, "sorry that names already taken");
plyr_[_pID].name = _name;
pIDxName_[_name] = _pID;
if (plyrNames_[_pID][_name] == false)
{
plyrNames_[_pID][_name] = true;
plyr_[_pID].names++;
plyrNameList_[_pID][plyr_[_pID].names] = _name;
}
for (uint256 i = 1; i <= gID_; i++)
games_[i].receivePlayerInfo(_pID, _addr, _name, _affID);
}
| 13,789,881
|
./full_match/5/0x559385E8728b7d8C98B3910e5531D8C49F861c31/sources/project:/contracts/main/MentaportVerify.sol
|
Throws if the sender is not a minter./
|
function _checkSigner() internal view {
require(hasRole(SIGNER_ROLE, msg.sender), "Caller is not signer");
}
| 1,916,272
|
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
pragma experimental ABIEncoderV2;
// ============ Internal Imports ============
import {Home} from "../Home.sol";
import {Version0} from "../Version0.sol";
import {XAppConnectionManager, TypeCasts} from "../XAppConnectionManager.sol";
import {IMessageRecipient} from "../../interfaces/IMessageRecipient.sol";
import {GovernanceMessage} from "./GovernanceMessage.sol";
// ============ External Imports ============
import {Initializable} from "@openzeppelin/contracts/proxy/Initializable.sol";
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {TypedMemView} from "@summa-tx/memview-sol/contracts/TypedMemView.sol";
contract GovernanceRouter is Version0, Initializable, IMessageRecipient {
// ============ Libraries ============
using SafeMath for uint256;
using TypedMemView for bytes;
using TypedMemView for bytes29;
using GovernanceMessage for bytes29;
// ============ Immutables ============
uint32 public immutable localDomain;
// number of seconds before recovery can be activated
uint256 public immutable recoveryTimelock;
// ============ Public Storage ============
// timestamp when recovery timelock expires; 0 if timelock has not been initiated
uint256 public recoveryActiveAt;
// the address of the recovery manager multisig
address public recoveryManager;
// the local entity empowered to call governance functions, set to 0x0 on non-Governor chains
address public governor;
// domain of Governor chain -- for accepting incoming messages from Governor
uint32 public governorDomain;
// xAppConnectionManager contract which stores Replica addresses
XAppConnectionManager public xAppConnectionManager;
// domain -> remote GovernanceRouter contract address
mapping(uint32 => bytes32) public routers;
// array of all domains with registered GovernanceRouter
uint32[] public domains;
// ============ Upgrade Gap ============
// gap for upgrade safety
uint256[43] private __GAP;
// ============ Events ============
/**
* @notice Emitted a remote GovernanceRouter address is added, removed, or changed
* @param domain the domain of the remote Router
* @param previousRouter the previously registered router; 0 if router is being added
* @param newRouter the new registered router; 0 if router is being removed
*/
event SetRouter(
uint32 indexed domain,
bytes32 previousRouter,
bytes32 newRouter
);
/**
* @notice Emitted when the Governor role is transferred
* @param previousGovernorDomain the domain of the previous Governor
* @param newGovernorDomain the domain of the new Governor
* @param previousGovernor the address of the previous Governor; 0 if the governor was remote
* @param newGovernor the address of the new Governor; 0 if the governor is remote
*/
event TransferGovernor(
uint32 previousGovernorDomain,
uint32 newGovernorDomain,
address indexed previousGovernor,
address indexed newGovernor
);
/**
* @notice Emitted when the RecoveryManager role is transferred
* @param previousRecoveryManager the address of the previous RecoveryManager
* @param newRecoveryManager the address of the new RecoveryManager
*/
event TransferRecoveryManager(
address indexed previousRecoveryManager,
address indexed newRecoveryManager
);
/**
* @notice Emitted when recovery state is initiated by the RecoveryManager
* @param recoveryManager the address of the current RecoveryManager who initiated the transition
* @param recoveryActiveAt the block at which recovery state will be active
*/
event InitiateRecovery(
address indexed recoveryManager,
uint256 recoveryActiveAt
);
/**
* @notice Emitted when recovery state is exited by the RecoveryManager
* @param recoveryManager the address of the current RecoveryManager who initiated the transition
*/
event ExitRecovery(address recoveryManager);
modifier typeAssert(bytes29 _view, GovernanceMessage.Types _type) {
_view.assertType(uint40(_type));
_;
}
// ============ Modifiers ============
modifier onlyReplica() {
require(xAppConnectionManager.isReplica(msg.sender), "!replica");
_;
}
modifier onlyGovernorRouter(uint32 _domain, bytes32 _address) {
require(_isGovernorRouter(_domain, _address), "!governorRouter");
_;
}
modifier onlyGovernor() {
require(msg.sender == governor, "! called by governor");
_;
}
modifier onlyRecoveryManager() {
require(msg.sender == recoveryManager, "! called by recovery manager");
_;
}
modifier onlyInRecovery() {
require(inRecovery(), "! in recovery");
_;
}
modifier onlyNotInRecovery() {
require(!inRecovery(), "in recovery");
_;
}
modifier onlyGovernorOrRecoveryManager() {
if (!inRecovery()) {
require(msg.sender == governor, "! called by governor");
} else {
require(
msg.sender == recoveryManager,
"! called by recovery manager"
);
}
_;
}
// ============ Constructor ============
constructor(uint32 _localDomain, uint256 _recoveryTimelock) {
localDomain = _localDomain;
recoveryTimelock = _recoveryTimelock;
}
// ============ Initializer ============
function initialize(
address _xAppConnectionManager,
address _recoveryManager
) public initializer {
// initialize governor
address _governorAddr = msg.sender;
bool _isLocalGovernor = true;
_transferGovernor(localDomain, _governorAddr, _isLocalGovernor);
// initialize recovery manager
recoveryManager = _recoveryManager;
// initialize XAppConnectionManager
setXAppConnectionManager(_xAppConnectionManager);
require(
xAppConnectionManager.localDomain() == localDomain,
"XAppConnectionManager bad domain"
);
}
// ============ External Functions ============
/**
* @notice Handle Optics messages
* For all non-Governor chains to handle messages
* sent from the Governor chain via Optics.
* Governor chain should never receive messages,
* because non-Governor chains are not able to send them
* @param _origin The domain (of the Governor Router)
* @param _sender The message sender (must be the Governor Router)
* @param _message The message
*/
function handle(
uint32 _origin,
bytes32 _sender,
bytes memory _message
) external override onlyReplica onlyGovernorRouter(_origin, _sender) {
bytes29 _msg = _message.ref(0);
if (_msg.isValidCall()) {
_handleCall(_msg.tryAsCall());
} else if (_msg.isValidTransferGovernor()) {
_handleTransferGovernor(_msg.tryAsTransferGovernor());
} else if (_msg.isValidSetRouter()) {
_handleSetRouter(_msg.tryAsSetRouter());
} else {
require(false, "!valid message type");
}
}
/**
* @notice Dispatch calls locally
* @param _calls The calls
*/
function callLocal(GovernanceMessage.Call[] calldata _calls)
external
onlyGovernorOrRecoveryManager
{
for (uint256 i = 0; i < _calls.length; i++) {
_dispatchCall(_calls[i]);
}
}
/**
* @notice Dispatch calls on a remote chain via the remote GovernanceRouter
* @param _destination The domain of the remote chain
* @param _calls The calls
*/
function callRemote(
uint32 _destination,
GovernanceMessage.Call[] calldata _calls
) external onlyGovernor onlyNotInRecovery {
// ensure that destination chain has enrolled router
bytes32 _router = _mustHaveRouter(_destination);
// format call message
bytes memory _msg = GovernanceMessage.formatCalls(_calls);
// dispatch call message using Optics
Home(xAppConnectionManager.home()).dispatch(
_destination,
_router,
_msg
);
}
/**
* @notice Transfer governorship
* @param _newDomain The domain of the new governor
* @param _newGovernor The address of the new governor
*/
function transferGovernor(uint32 _newDomain, address _newGovernor)
external
onlyGovernor
onlyNotInRecovery
{
bool _isLocalGovernor = _isLocalDomain(_newDomain);
// transfer the governor locally
_transferGovernor(_newDomain, _newGovernor, _isLocalGovernor);
// if the governor domain is local, we only need to change the governor address locally
// no need to message remote routers; they should already have the same domain set and governor = bytes32(0)
if (_isLocalGovernor) {
return;
}
// format transfer governor message
bytes memory _transferGovernorMessage = GovernanceMessage
.formatTransferGovernor(
_newDomain,
TypeCasts.addressToBytes32(_newGovernor)
);
// send transfer governor message to all remote routers
// note: this assumes that the Router is on the global GovernorDomain;
// this causes a process error when relinquishing governorship
// on a newly deployed domain which is not the GovernorDomain
_sendToAllRemoteRouters(_transferGovernorMessage);
}
/**
* @notice Transfer recovery manager role
* @dev callable by the recoveryManager at any time to transfer the role
* @param _newRecoveryManager The address of the new recovery manager
*/
function transferRecoveryManager(address _newRecoveryManager)
external
onlyRecoveryManager
{
emit TransferRecoveryManager(recoveryManager, _newRecoveryManager);
recoveryManager = _newRecoveryManager;
}
/**
* @notice Set the router address for a given domain and
* dispatch the change to all remote routers
* @param _domain The domain
* @param _router The address of the new router
*/
function setRouter(uint32 _domain, bytes32 _router)
external
onlyGovernor
onlyNotInRecovery
{
// set the router locally
_setRouter(_domain, _router);
// format message to set the router on all remote routers
bytes memory _setRouterMessage = GovernanceMessage.formatSetRouter(
_domain,
_router
);
_sendToAllRemoteRouters(_setRouterMessage);
}
/**
* @notice Set the router address *locally only*
* for the deployer to setup the router mapping locally
* before transferring governorship to the "true" governor
* @dev External helper for contract setup
* @param _domain The domain
* @param _router The new router
*/
function setRouterLocal(uint32 _domain, bytes32 _router)
external
onlyGovernorOrRecoveryManager
{
// set the router locally
_setRouter(_domain, _router);
}
/**
* @notice Set the address of the XAppConnectionManager
* @dev Domain/address validation helper
* @param _xAppConnectionManager The address of the new xAppConnectionManager
*/
function setXAppConnectionManager(address _xAppConnectionManager)
public
onlyGovernorOrRecoveryManager
{
xAppConnectionManager = XAppConnectionManager(_xAppConnectionManager);
}
/**
* @notice Initiate the recovery timelock
* @dev callable by the recovery manager
*/
function initiateRecoveryTimelock()
external
onlyNotInRecovery
onlyRecoveryManager
{
require(recoveryActiveAt == 0, "recovery already initiated");
// set the time that recovery will be active
recoveryActiveAt = block.timestamp.add(recoveryTimelock);
emit InitiateRecovery(recoveryManager, recoveryActiveAt);
}
/**
* @notice Exit recovery mode
* @dev callable by the recovery manager to end recovery mode
*/
function exitRecovery() external onlyRecoveryManager {
require(recoveryActiveAt != 0, "recovery not initiated");
delete recoveryActiveAt;
emit ExitRecovery(recoveryManager);
}
// ============ Public Functions ============
/**
* @notice Check if the contract is in recovery mode currently
* @return TRUE iff the contract is actively in recovery mode currently
*/
function inRecovery() public view returns (bool) {
uint256 _recoveryActiveAt = recoveryActiveAt;
bool _recoveryInitiated = _recoveryActiveAt != 0;
bool _recoveryActive = _recoveryActiveAt <= block.timestamp;
return _recoveryInitiated && _recoveryActive;
}
// ============ Internal Functions ============
/**
* @notice Handle message dispatching calls locally
* @param _msg The message
*/
function _handleCall(bytes29 _msg)
internal
typeAssert(_msg, GovernanceMessage.Types.Call)
{
GovernanceMessage.Call[] memory _calls = _msg.getCalls();
for (uint256 i = 0; i < _calls.length; i++) {
_dispatchCall(_calls[i]);
}
}
/**
* @notice Handle message transferring governorship to a new Governor
* @param _msg The message
*/
function _handleTransferGovernor(bytes29 _msg)
internal
typeAssert(_msg, GovernanceMessage.Types.TransferGovernor)
{
uint32 _newDomain = _msg.domain();
address _newGovernor = TypeCasts.bytes32ToAddress(_msg.governor());
bool _isLocalGovernor = _isLocalDomain(_newDomain);
_transferGovernor(_newDomain, _newGovernor, _isLocalGovernor);
}
/**
* @notice Handle message setting the router address for a given domain
* @param _msg The message
*/
function _handleSetRouter(bytes29 _msg)
internal
typeAssert(_msg, GovernanceMessage.Types.SetRouter)
{
uint32 _domain = _msg.domain();
bytes32 _router = _msg.router();
_setRouter(_domain, _router);
}
/**
* @notice Dispatch message to all remote routers
* @param _msg The message
*/
function _sendToAllRemoteRouters(bytes memory _msg) internal {
Home _home = Home(xAppConnectionManager.home());
for (uint256 i = 0; i < domains.length; i++) {
if (domains[i] != uint32(0)) {
_home.dispatch(domains[i], routers[domains[i]], _msg);
}
}
}
/**
* @notice Dispatch call locally
* @param _call The call
* @return _ret
*/
function _dispatchCall(GovernanceMessage.Call memory _call)
internal
returns (bytes memory _ret)
{
address _toContract = TypeCasts.bytes32ToAddress(_call.to);
// attempt to dispatch using low-level call
bool _success;
(_success, _ret) = _toContract.call(_call.data);
// revert if the call failed
require(_success, "call failed");
}
/**
* @notice Transfer governorship within this contract's state
* @param _newDomain The domain of the new governor
* @param _newGovernor The address of the new governor
* @param _isLocalGovernor True if the newDomain is the localDomain
*/
function _transferGovernor(
uint32 _newDomain,
address _newGovernor,
bool _isLocalGovernor
) internal {
// require that the governor domain has a valid router
if (!_isLocalGovernor) {
_mustHaveRouter(_newDomain);
}
// Governor is 0x0 unless the governor is local
address _newGov = _isLocalGovernor ? _newGovernor : address(0);
// emit event before updating state variables
emit TransferGovernor(governorDomain, _newDomain, governor, _newGov);
// update state
governorDomain = _newDomain;
governor = _newGov;
}
/**
* @notice Set the router for a given domain
* @param _domain The domain
* @param _newRouter The new router
*/
function _setRouter(uint32 _domain, bytes32 _newRouter) internal {
bytes32 _previousRouter = routers[_domain];
// emit event at beginning in case return after remove
emit SetRouter(_domain, _previousRouter, _newRouter);
// if the router is being removed, remove the domain
if (_newRouter == bytes32(0)) {
_removeDomain(_domain);
return;
}
// if the router is being added, add the domain
if (_previousRouter == bytes32(0)) {
_addDomain(_domain);
}
// update state with new router
routers[_domain] = _newRouter;
}
/**
* @notice Add a domain that has a router
* @param _domain The domain
*/
function _addDomain(uint32 _domain) internal {
domains.push(_domain);
}
/**
* @notice Remove a domain and its associated router
* @param _domain The domain
*/
function _removeDomain(uint32 _domain) internal {
delete routers[_domain];
// find the index of the domain to remove & delete it from domains[]
for (uint256 i = 0; i < domains.length; i++) {
if (domains[i] == _domain) {
delete domains[i];
return;
}
}
}
/**
* @notice Determine if a given domain and address is the Governor Router
* @param _domain The domain
* @param _address The address of the domain's router
* @return _ret True if the given domain/address is the
* Governor Router.
*/
function _isGovernorRouter(uint32 _domain, bytes32 _address)
internal
view
returns (bool)
{
return _domain == governorDomain && _address == routers[_domain];
}
/**
* @notice Determine if a given domain is the local domain
* @param _domain The domain
* @return _ret - True if the given domain is the local domain
*/
function _isLocalDomain(uint32 _domain) internal view returns (bool) {
return _domain == localDomain;
}
/**
* @notice Require that a domain has a router and returns the router
* @param _domain The domain
* @return _router - The domain's router
*/
function _mustHaveRouter(uint32 _domain)
internal
view
returns (bytes32 _router)
{
_router = routers[_domain];
require(_router != bytes32(0), "!router");
}
}
// 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.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;
interface IMessageRecipient {
function handle(
uint32 _origin,
bytes32 _sender,
bytes memory _message
) external;
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
pragma experimental ABIEncoderV2;
// ============ External Imports ============
import {TypedMemView} from "@summa-tx/memview-sol/contracts/TypedMemView.sol";
library GovernanceMessage {
using TypedMemView for bytes;
using TypedMemView for bytes29;
uint256 private constant CALL_PREFIX_LEN = 64;
uint256 private constant MSG_PREFIX_NUM_ITEMS = 2;
uint256 private constant MSG_PREFIX_LEN = 2;
uint256 private constant GOV_ACTION_LEN = 37;
enum Types {
Invalid, // 0
Call, // 1
TransferGovernor, // 2
SetRouter, // 3
Data // 4
}
struct Call {
bytes32 to;
bytes data;
}
modifier typeAssert(bytes29 _view, Types _t) {
_view.assertType(uint40(_t));
_;
}
// Types.Call
function data(bytes29 _view) internal view returns (bytes memory _data) {
_data = TypedMemView.clone(
_view.slice(CALL_PREFIX_LEN, dataLen(_view), uint40(Types.Data))
);
}
function formatCalls(Call[] memory _calls)
internal
view
returns (bytes memory _msg)
{
uint256 _numCalls = _calls.length;
bytes29[] memory _encodedCalls = new bytes29[](
_numCalls + MSG_PREFIX_NUM_ITEMS
);
// Add Types.Call identifier
_encodedCalls[0] = abi.encodePacked(Types.Call).ref(0);
// Add number of calls
_encodedCalls[1] = abi.encodePacked(uint8(_numCalls)).ref(0);
for (uint256 i = 0; i < _numCalls; i++) {
Call memory _call = _calls[i];
bytes29 _callMsg = abi
.encodePacked(_call.to, _call.data.length, _call.data)
.ref(0);
_encodedCalls[i + MSG_PREFIX_NUM_ITEMS] = _callMsg;
}
_msg = TypedMemView.join(_encodedCalls);
}
function formatTransferGovernor(uint32 _domain, bytes32 _governor)
internal
view
returns (bytes memory _msg)
{
_msg = TypedMemView.clone(
mustBeTransferGovernor(
abi
.encodePacked(Types.TransferGovernor, _domain, _governor)
.ref(0)
)
);
}
function formatSetRouter(uint32 _domain, bytes32 _router)
internal
view
returns (bytes memory _msg)
{
_msg = TypedMemView.clone(
mustBeSetRouter(
abi.encodePacked(Types.SetRouter, _domain, _router).ref(0)
)
);
}
function getCalls(bytes29 _msg) internal view returns (Call[] memory) {
uint8 _numCalls = uint8(_msg.indexUint(1, 1));
// Skip message prefix
bytes29 _msgPtr = _msg.slice(
MSG_PREFIX_LEN,
_msg.len() - MSG_PREFIX_LEN,
uint40(Types.Call)
);
Call[] memory _calls = new Call[](_numCalls);
uint256 counter = 0;
while (_msgPtr.len() > 0) {
_calls[counter].to = to(_msgPtr);
_calls[counter].data = data(_msgPtr);
_msgPtr = nextCall(_msgPtr);
counter++;
}
return _calls;
}
function nextCall(bytes29 _view)
internal
pure
typeAssert(_view, Types.Call)
returns (bytes29)
{
uint256 lastCallLen = CALL_PREFIX_LEN + dataLen(_view);
return
_view.slice(
lastCallLen,
_view.len() - lastCallLen,
uint40(Types.Call)
);
}
function messageType(bytes29 _view) internal pure returns (Types) {
return Types(uint8(_view.typeOf()));
}
/*
Message fields
*/
// All Types
function identifier(bytes29 _view) internal pure returns (uint8) {
return uint8(_view.indexUint(0, 1));
}
// Types.Call
function to(bytes29 _view) internal pure returns (bytes32) {
return _view.index(0, 32);
}
// Types.Call
function dataLen(bytes29 _view) internal pure returns (uint256) {
return uint256(_view.index(32, 32));
}
// Types.TransferGovernor & Types.EnrollRemote
function domain(bytes29 _view) internal pure returns (uint32) {
return uint32(_view.indexUint(1, 4));
}
// Types.EnrollRemote
function router(bytes29 _view) internal pure returns (bytes32) {
return _view.index(5, 32);
}
// Types.TransferGovernor
function governor(bytes29 _view) internal pure returns (bytes32) {
return _view.index(5, 32);
}
/*
Message Type: CALL
struct Call {
identifier, // message ID -- 1 byte
numCalls, // number of calls -- 1 byte
calls[], {
to, // address to call -- 32 bytes
dataLen, // call data length -- 32 bytes,
data // call data -- 0+ bytes (length unknown)
}
}
*/
function isValidCall(bytes29 _view) internal pure returns (bool) {
return
identifier(_view) == uint8(Types.Call) &&
_view.len() >= CALL_PREFIX_LEN;
}
function isCall(bytes29 _view) internal pure returns (bool) {
return isValidCall(_view) && messageType(_view) == Types.Call;
}
function tryAsCall(bytes29 _view) internal pure returns (bytes29) {
if (isValidCall(_view)) {
return _view.castTo(uint40(Types.Call));
}
return TypedMemView.nullView();
}
function mustBeCalls(bytes29 _view) internal pure returns (bytes29) {
return tryAsCall(_view).assertValid();
}
/*
Message Type: TRANSFER GOVERNOR
struct TransferGovernor {
identifier, // message ID -- 1 byte
domain, // domain of new governor -- 4 bytes
addr // address of new governor -- 32 bytes
}
*/
function isValidTransferGovernor(bytes29 _view)
internal
pure
returns (bool)
{
return
identifier(_view) == uint8(Types.TransferGovernor) &&
_view.len() == GOV_ACTION_LEN;
}
function isTransferGovernor(bytes29 _view) internal pure returns (bool) {
return
isValidTransferGovernor(_view) &&
messageType(_view) == Types.TransferGovernor;
}
function tryAsTransferGovernor(bytes29 _view)
internal
pure
returns (bytes29)
{
if (isValidTransferGovernor(_view)) {
return _view.castTo(uint40(Types.TransferGovernor));
}
return TypedMemView.nullView();
}
function mustBeTransferGovernor(bytes29 _view)
internal
pure
returns (bytes29)
{
return tryAsTransferGovernor(_view).assertValid();
}
/*
Message Type: ENROLL ROUTER
struct SetRouter {
identifier, // message ID -- 1 byte
domain, // domain of new router -- 4 bytes
addr // address of new router -- 32 bytes
}
*/
function isValidSetRouter(bytes29 _view) internal pure returns (bool) {
return
identifier(_view) == uint8(Types.SetRouter) &&
_view.len() == GOV_ACTION_LEN;
}
function isSetRouter(bytes29 _view) internal pure returns (bool) {
return isValidSetRouter(_view) && messageType(_view) == Types.SetRouter;
}
function tryAsSetRouter(bytes29 _view) internal pure returns (bytes29) {
if (isValidSetRouter(_view)) {
return _view.castTo(uint40(Types.SetRouter));
}
return TypedMemView.nullView();
}
function mustBeSetRouter(bytes29 _view) internal pure returns (bytes29) {
return tryAsSetRouter(_view).assertValid();
}
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/Address.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 !Address.isContract(address(this));
}
}
// 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: 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 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;
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
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
// 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 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.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.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
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;
}
}
|
Handle message dispatching calls locally _msg The message/
|
function _handleCall(bytes29 _msg)
internal
typeAssert(_msg, GovernanceMessage.Types.Call)
{
GovernanceMessage.Call[] memory _calls = _msg.getCalls();
for (uint256 i = 0; i < _calls.length; i++) {
_dispatchCall(_calls[i]);
}
}
| 9,926,139
|
// SPDX-License-Identifier: MIT
// File: contracts/utils/MultiOwnable.sol
pragma solidity 0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there are accounts that can be granted exclusive access to
* specific functions.
*/
abstract contract MultiOwnable {
mapping(address => bool) private _owners;
event OwnershipAdded(address indexed owner);
event OwnershipRemoved(address indexed owner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_owners[msg.sender] = true;
emit OwnershipAdded(msg.sender);
}
/**
* @dev Returns the address of the current owner.
*/
function isOwner(address addr) public view returns (bool) {
return _owners[addr];
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwners() {
require(
_owners[msg.sender],
"MultiOwnable: caller is not one of the owners"
);
_;
}
/**
* @dev Remove the sender from owners
*/
function renounceOwnership() public virtual onlyOwners {
removeOwnership(msg.sender);
}
/**
* @dev Adds ownership of the contract to a new account (`newOwner`).
* Can only be called by any current owner.
*/
function addOwnership(address newOwner) public virtual onlyOwners {
require(
newOwner != address(0),
"MultiOwnable: new owner is the zero address"
);
_owners[newOwner] = true;
emit OwnershipAdded(newOwner);
}
/**
* @dev Adds ownership of the contract to a new account (`newOwner`).
* Can only be called by any current owner.
*/
function removeOwnership(address owner) public virtual onlyOwners {
require(
owner != address(0),
"MultiOwnable: new owner is the zero address"
);
_owners[owner] = false;
emit OwnershipRemoved(owner);
}
}
|
Adds ownership of the contract to a new account (`newOwner`). Can only be called by any current owner./
|
function removeOwnership(address owner) public virtual onlyOwners {
require(
owner != address(0),
"MultiOwnable: new owner is the zero address"
);
_owners[owner] = false;
emit OwnershipRemoved(owner);
}
| 13,018,458
|
pragma solidity ^0.5.8;
/**
* @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.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev 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;
}
}
/**
* @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;
}
}
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-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);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* 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'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 A 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 to 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'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) {
_approve(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) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][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) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][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) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
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 Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender'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 {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
/**
* @title Math
* @dev Assorted math operations
*/
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 Calculates the average of two numbers. Since these are integers,
* averages of an even and odd number cannot be represented, and will be
* rounded down.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
/**
* Utility library of inline functions on addresses
*/
library Address {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
/// @notice Implements safeTransfer, safeTransferFrom and
/// safeApprove for CompatibleERC20.
///
/// See https://github.com/ethereum/solidity/issues/4116
///
/// This library allows interacting with ERC20 tokens that implement any of
/// these interfaces:
///
/// (1) transfer returns true on success, false on failure
/// (2) transfer returns true on success, reverts on failure
/// (3) transfer returns nothing on success, reverts on failure
///
/// Additionally, safeTransferFromWithFees will return the final token
/// value received after accounting for token fees.
library CompatibleERC20Functions {
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));
}
/// @notice Calls transferFrom on the token, reverts if the call fails and
/// returns the value transferred after fees.
function safeTransferFromWithFees(IERC20 token, address from, address to, uint256 value) internal returns (uint256) {
uint256 balancesBefore = token.balanceOf(to);
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
require(previousReturnValue(), "transferFrom failed");
uint256 balancesAfter = token.balanceOf(to);
return Math.min(value, balancesAfter.sub(balancesBefore));
}
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));
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);
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 equal true).
* @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.
require(address(token).isContract());
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success);
if (returndata.length > 0) { // Return data is optional
require(abi.decode(returndata, (bool)));
}
}
/// @notice Checks the return value of the previous function. Returns true
/// if the previous function returned 32 non-zero bytes or returned zero
/// bytes.
function previousReturnValue() private pure returns (bool)
{
uint256 returnData = 0;
assembly { /* solium-disable-line security/no-inline-assembly */
// Switch on the number of bytes returned by the previous call
switch returndatasize
// 0 bytes: ERC20 of type (3), did not throw
case 0 {
returnData := 1
}
// 32 bytes: ERC20 of types (1) or (2)
case 32 {
// Copy the return data into scratch space
returndatacopy(0, 0, 32)
// Load the return data into returnData
returnData := mload(0)
}
// Other return size: return false
default { }
}
return returnData != 0;
}
}
/**
* @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 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 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 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 Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract ERC20Burnable is ERC20 {
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) public {
_burn(msg.sender, value);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The account whose tokens will be burned.
* @param value uint256 The amount of token to be burned.
*/
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
contract RenToken is Ownable, ERC20Detailed, ERC20Pausable, ERC20Burnable {
string private constant _name = "Republic Token";
string private constant _symbol = "REN";
uint8 private constant _decimals = 18;
uint256 public constant INITIAL_SUPPLY = 1000000000 * 10**uint256(_decimals);
/// @notice The RenToken Constructor.
constructor() ERC20Burnable() ERC20Pausable() ERC20Detailed(_name, _symbol, _decimals) public {
_mint(msg.sender, INITIAL_SUPPLY);
}
function transferTokens(address beneficiary, uint256 amount) public onlyOwner returns (bool) {
/* solium-disable error-reason */
require(amount > 0);
_transfer(msg.sender, beneficiary, amount);
emit Transfer(msg.sender, beneficiary, amount);
return true;
}
}
/// @notice DarknodeSlasher will become a voting system for darknodes to
/// deregister other misbehaving darknodes.
/// Right now, it is a placeholder.
contract DarknodeSlasher is Ownable {
DarknodeRegistry public darknodeRegistry;
constructor(DarknodeRegistry _darknodeRegistry) public {
darknodeRegistry = _darknodeRegistry;
}
function slash(address _prover, address _challenger1, address _challenger2)
external
onlyOwner
{
darknodeRegistry.slash(_prover, _challenger1, _challenger2);
}
}
/**
* @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 Claimable {
address private _pendingOwner;
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());
_;
}
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == _pendingOwner);
_;
}
/**
* @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.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
_pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() onlyPendingOwner public {
emit OwnershipTransferred(_owner, _pendingOwner);
_owner = _pendingOwner;
_pendingOwner = address(0);
}
}
/**
* @notice LinkedList is a library for a circular double linked list.
*/
library LinkedList {
/*
* @notice A permanent NULL node (0x0) in the circular double linked list.
* NULL.next is the head, and NULL.previous is the tail.
*/
address public constant NULL = address(0);
/**
* @notice A node points to the node before it, and the node after it. If
* node.previous = NULL, then the node is the head of the list. If
* node.next = NULL, then the node is the tail of the list.
*/
struct Node {
bool inList;
address previous;
address next;
}
/**
* @notice LinkedList uses a mapping from address to nodes. Each address
* uniquely identifies a node, and in this way they are used like pointers.
*/
struct List {
mapping (address => Node) list;
}
/**
* @notice Insert a new node before an existing node.
*
* @param self The list being used.
* @param target The existing node in the list.
* @param newNode The next node to insert before the target.
*/
function insertBefore(List storage self, address target, address newNode) internal {
require(!isInList(self, newNode), "already in list");
require(isInList(self, target) || target == NULL, "not in list");
// It is expected that this value is sometimes NULL.
address prev = self.list[target].previous;
self.list[newNode].next = target;
self.list[newNode].previous = prev;
self.list[target].previous = newNode;
self.list[prev].next = newNode;
self.list[newNode].inList = true;
}
/**
* @notice Insert a new node after an existing node.
*
* @param self The list being used.
* @param target The existing node in the list.
* @param newNode The next node to insert after the target.
*/
function insertAfter(List storage self, address target, address newNode) internal {
require(!isInList(self, newNode), "already in list");
require(isInList(self, target) || target == NULL, "not in list");
// It is expected that this value is sometimes NULL.
address n = self.list[target].next;
self.list[newNode].previous = target;
self.list[newNode].next = n;
self.list[target].next = newNode;
self.list[n].previous = newNode;
self.list[newNode].inList = true;
}
/**
* @notice Remove a node from the list, and fix the previous and next
* pointers that are pointing to the removed node. Removing anode that is not
* in the list will do nothing.
*
* @param self The list being using.
* @param node The node in the list to be removed.
*/
function remove(List storage self, address node) internal {
require(isInList(self, node), "not in list");
if (node == NULL) {
return;
}
address p = self.list[node].previous;
address n = self.list[node].next;
self.list[p].next = n;
self.list[n].previous = p;
// Deleting the node should set this value to false, but we set it here for
// explicitness.
self.list[node].inList = false;
delete self.list[node];
}
/**
* @notice Insert a node at the beginning of the list.
*
* @param self The list being used.
* @param node The node to insert at the beginning of the list.
*/
function prepend(List storage self, address node) internal {
// isInList(node) is checked in insertBefore
insertBefore(self, begin(self), node);
}
/**
* @notice Insert a node at the end of the list.
*
* @param self The list being used.
* @param node The node to insert at the end of the list.
*/
function append(List storage self, address node) internal {
// isInList(node) is checked in insertBefore
insertAfter(self, end(self), node);
}
function swap(List storage self, address left, address right) internal {
// isInList(left) and isInList(right) are checked in remove
address previousRight = self.list[right].previous;
remove(self, right);
insertAfter(self, left, right);
remove(self, left);
insertAfter(self, previousRight, left);
}
function isInList(List storage self, address node) internal view returns (bool) {
return self.list[node].inList;
}
/**
* @notice Get the node at the beginning of a double linked list.
*
* @param self The list being used.
*
* @return A address identifying the node at the beginning of the double
* linked list.
*/
function begin(List storage self) internal view returns (address) {
return self.list[NULL].next;
}
/**
* @notice Get the node at the end of a double linked list.
*
* @param self The list being used.
*
* @return A address identifying the node at the end of the double linked
* list.
*/
function end(List storage self) internal view returns (address) {
return self.list[NULL].previous;
}
function next(List storage self, address node) internal view returns (address) {
require(isInList(self, node), "not in list");
return self.list[node].next;
}
function previous(List storage self, address node) internal view returns (address) {
require(isInList(self, node), "not in list");
return self.list[node].previous;
}
}
/// @notice This contract stores data and funds for the DarknodeRegistry
/// contract. The data / fund logic and storage have been separated to improve
/// upgradability.
contract DarknodeRegistryStore is Claimable {
using SafeMath for uint256;
string public VERSION; // Passed in as a constructor parameter.
/// @notice Darknodes are stored in the darknode struct. The owner is the
/// address that registered the darknode, the bond is the amount of REN that
/// was transferred during registration, and the public key is the
/// encryption key that should be used when sending sensitive information to
/// the darknode.
struct Darknode {
// The owner of a Darknode is the address that called the register
// function. The owner is the only address that is allowed to
// deregister the Darknode, unless the Darknode is slashed for
// malicious behavior.
address payable owner;
// The bond is the amount of REN submitted as a bond by the Darknode.
// This amount is reduced when the Darknode is slashed for malicious
// behavior.
uint256 bond;
// The block number at which the Darknode is considered registered.
uint256 registeredAt;
// The block number at which the Darknode is considered deregistered.
uint256 deregisteredAt;
// The public key used by this Darknode for encrypting sensitive data
// off chain. It is assumed that the Darknode has access to the
// respective private key, and that there is an agreement on the format
// of the public key.
bytes publicKey;
}
/// Registry data.
mapping(address => Darknode) private darknodeRegistry;
LinkedList.List private darknodes;
// RenToken.
RenToken public ren;
/// @notice The contract constructor.
///
/// @param _VERSION A string defining the contract version.
/// @param _ren The address of the RenToken contract.
constructor(
string memory _VERSION,
RenToken _ren
) public {
VERSION = _VERSION;
ren = _ren;
}
/// @notice Instantiates a darknode and appends it to the darknodes
/// linked-list.
///
/// @param _darknodeID The darknode's ID.
/// @param _darknodeOwner The darknode's owner's address
/// @param _bond The darknode's bond value
/// @param _publicKey The darknode's public key
/// @param _registeredAt The time stamp when the darknode is registered.
/// @param _deregisteredAt The time stamp when the darknode is deregistered.
function appendDarknode(
address _darknodeID,
address payable _darknodeOwner,
uint256 _bond,
bytes calldata _publicKey,
uint256 _registeredAt,
uint256 _deregisteredAt
) external onlyOwner {
Darknode memory darknode = Darknode({
owner: _darknodeOwner,
bond: _bond,
publicKey: _publicKey,
registeredAt: _registeredAt,
deregisteredAt: _deregisteredAt
});
darknodeRegistry[_darknodeID] = darknode;
LinkedList.append(darknodes, _darknodeID);
}
/// @notice Returns the address of the first darknode in the store
function begin() external view onlyOwner returns(address) {
return LinkedList.begin(darknodes);
}
/// @notice Returns the address of the next darknode in the store after the
/// given address.
function next(address darknodeID) external view onlyOwner returns(address) {
return LinkedList.next(darknodes, darknodeID);
}
/// @notice Removes a darknode from the store and transfers its bond to the
/// owner of this contract.
function removeDarknode(address darknodeID) external onlyOwner {
uint256 bond = darknodeRegistry[darknodeID].bond;
delete darknodeRegistry[darknodeID];
LinkedList.remove(darknodes, darknodeID);
require(ren.transfer(owner(), bond), "bond transfer failed");
}
/// @notice Updates the bond of a darknode. The new bond must be smaller
/// than the previous bond of the darknode.
function updateDarknodeBond(address darknodeID, uint256 decreasedBond) external onlyOwner {
uint256 previousBond = darknodeRegistry[darknodeID].bond;
require(decreasedBond < previousBond, "bond not decreased");
darknodeRegistry[darknodeID].bond = decreasedBond;
require(ren.transfer(owner(), previousBond.sub(decreasedBond)), "bond transfer failed");
}
/// @notice Updates the deregistration timestamp of a darknode.
function updateDarknodeDeregisteredAt(address darknodeID, uint256 deregisteredAt) external onlyOwner {
darknodeRegistry[darknodeID].deregisteredAt = deregisteredAt;
}
/// @notice Returns the owner of a given darknode.
function darknodeOwner(address darknodeID) external view onlyOwner returns (address payable) {
return darknodeRegistry[darknodeID].owner;
}
/// @notice Returns the bond of a given darknode.
function darknodeBond(address darknodeID) external view onlyOwner returns (uint256) {
return darknodeRegistry[darknodeID].bond;
}
/// @notice Returns the registration time of a given darknode.
function darknodeRegisteredAt(address darknodeID) external view onlyOwner returns (uint256) {
return darknodeRegistry[darknodeID].registeredAt;
}
/// @notice Returns the deregistration time of a given darknode.
function darknodeDeregisteredAt(address darknodeID) external view onlyOwner returns (uint256) {
return darknodeRegistry[darknodeID].deregisteredAt;
}
/// @notice Returns the encryption public key of a given darknode.
function darknodePublicKey(address darknodeID) external view onlyOwner returns (bytes memory) {
return darknodeRegistry[darknodeID].publicKey;
}
}
/// @notice DarknodeRegistry is responsible for the registration and
/// deregistration of Darknodes.
contract DarknodeRegistry is Ownable {
using SafeMath for uint256;
string public VERSION; // Passed in as a constructor parameter.
/// @notice Darknode pods are shuffled after a fixed number of blocks.
/// An Epoch stores an epoch hash used as an (insecure) RNG seed, and the
/// blocknumber which restricts when the next epoch can be called.
struct Epoch {
uint256 epochhash;
uint256 blocknumber;
}
uint256 public numDarknodes;
uint256 public numDarknodesNextEpoch;
uint256 public numDarknodesPreviousEpoch;
/// Variables used to parameterize behavior.
uint256 public minimumBond;
uint256 public minimumPodSize;
uint256 public minimumEpochInterval;
/// When one of the above variables is modified, it is only updated when the
/// next epoch is called. These variables store the values for the next epoch.
uint256 public nextMinimumBond;
uint256 public nextMinimumPodSize;
uint256 public nextMinimumEpochInterval;
/// The current and previous epoch
Epoch public currentEpoch;
Epoch public previousEpoch;
/// Republic ERC20 token contract used to transfer bonds.
RenToken public ren;
/// Darknode Registry Store is the storage contract for darknodes.
DarknodeRegistryStore public store;
/// Darknode Slasher allows darknodes to vote on bond slashing.
DarknodeSlasher public slasher;
DarknodeSlasher public nextSlasher;
/// @notice Emitted when a darknode is registered.
/// @param _darknodeID The darknode ID that was registered.
/// @param _bond The amount of REN that was transferred as bond.
event LogDarknodeRegistered(address indexed _darknodeID, uint256 _bond);
/// @notice Emitted when a darknode is deregistered.
/// @param _darknodeID The darknode ID that was deregistered.
event LogDarknodeDeregistered(address indexed _darknodeID);
/// @notice Emitted when a refund has been made.
/// @param _owner The address that was refunded.
/// @param _amount The amount of REN that was refunded.
event LogDarknodeOwnerRefunded(address indexed _owner, uint256 _amount);
/// @notice Emitted when a new epoch has begun.
event LogNewEpoch(uint256 indexed epochhash);
/// @notice Emitted when a constructor parameter has been updated.
event LogMinimumBondUpdated(uint256 previousMinimumBond, uint256 nextMinimumBond);
event LogMinimumPodSizeUpdated(uint256 previousMinimumPodSize, uint256 nextMinimumPodSize);
event LogMinimumEpochIntervalUpdated(uint256 previousMinimumEpochInterval, uint256 nextMinimumEpochInterval);
event LogSlasherUpdated(address previousSlasher, address nextSlasher);
/// @notice Only allow the owner that registered the darknode to pass.
modifier onlyDarknodeOwner(address _darknodeID) {
require(store.darknodeOwner(_darknodeID) == msg.sender, "must be darknode owner");
_;
}
/// @notice Only allow unregistered darknodes.
modifier onlyRefunded(address _darknodeID) {
require(isRefunded(_darknodeID), "must be refunded or never registered");
_;
}
/// @notice Only allow refundable darknodes.
modifier onlyRefundable(address _darknodeID) {
require(isRefundable(_darknodeID), "must be deregistered for at least one epoch");
_;
}
/// @notice Only allowed registered nodes without a pending deregistration to
/// deregister
modifier onlyDeregisterable(address _darknodeID) {
require(isDeregisterable(_darknodeID), "must be deregisterable");
_;
}
/// @notice Only allow the Slasher contract.
modifier onlySlasher() {
require(address(slasher) == msg.sender, "must be slasher");
_;
}
/// @notice The contract constructor.
///
/// @param _VERSION A string defining the contract version.
/// @param _renAddress The address of the RenToken contract.
/// @param _storeAddress The address of the DarknodeRegistryStore contract.
/// @param _minimumBond The minimum bond amount that can be submitted by a
/// Darknode.
/// @param _minimumPodSize The minimum size of a Darknode pod.
/// @param _minimumEpochInterval The minimum number of blocks between
/// epochs.
constructor(
string memory _VERSION,
RenToken _renAddress,
DarknodeRegistryStore _storeAddress,
uint256 _minimumBond,
uint256 _minimumPodSize,
uint256 _minimumEpochInterval
) public {
VERSION = _VERSION;
store = _storeAddress;
ren = _renAddress;
minimumBond = _minimumBond;
nextMinimumBond = minimumBond;
minimumPodSize = _minimumPodSize;
nextMinimumPodSize = minimumPodSize;
minimumEpochInterval = _minimumEpochInterval;
nextMinimumEpochInterval = minimumEpochInterval;
currentEpoch = Epoch({
epochhash: uint256(blockhash(block.number - 1)),
blocknumber: block.number
});
numDarknodes = 0;
numDarknodesNextEpoch = 0;
numDarknodesPreviousEpoch = 0;
}
/// @notice Register a darknode and transfer the bond to this contract.
/// Before registering, the bond transfer must be approved in the REN
/// contract. The caller must provide a public encryption key for the
/// darknode. The darknode will remain pending registration until the next
/// epoch. Only after this period can the darknode be deregistered. The
/// caller of this method will be stored as the owner of the darknode.
///
/// @param _darknodeID The darknode ID that will be registered.
/// @param _publicKey The public key of the darknode. It is stored to allow
/// other darknodes and traders to encrypt messages to the trader.
function register(address _darknodeID, bytes calldata _publicKey) external onlyRefunded(_darknodeID) {
// Use the current minimum bond as the darknode's bond.
uint256 bond = minimumBond;
// Transfer bond to store
require(ren.transferFrom(msg.sender, address(store), bond), "bond transfer failed");
// Flag this darknode for registration
store.appendDarknode(
_darknodeID,
msg.sender,
bond,
_publicKey,
currentEpoch.blocknumber.add(minimumEpochInterval),
0
);
numDarknodesNextEpoch = numDarknodesNextEpoch.add(1);
// Emit an event.
emit LogDarknodeRegistered(_darknodeID, bond);
}
/// @notice Deregister a darknode. The darknode will not be deregistered
/// until the end of the epoch. After another epoch, the bond can be
/// refunded by calling the refund method.
/// @param _darknodeID The darknode ID that will be deregistered. The caller
/// of this method store.darknodeRegisteredAt(_darknodeID) must be
// the owner of this darknode.
function deregister(address _darknodeID) external onlyDeregisterable(_darknodeID) onlyDarknodeOwner(_darknodeID) {
deregisterDarknode(_darknodeID);
}
/// @notice Progress the epoch if it is possible to do so. This captures
/// the current timestamp and current blockhash and overrides the current
/// epoch.
function epoch() external {
if (previousEpoch.blocknumber == 0) {
// The first epoch must be called by the owner of the contract
require(msg.sender == owner(), "not authorized (first epochs)");
}
// Require that the epoch interval has passed
require(block.number >= currentEpoch.blocknumber.add(minimumEpochInterval), "epoch interval has not passed");
uint256 epochhash = uint256(blockhash(block.number - 1));
// Update the epoch hash and timestamp
previousEpoch = currentEpoch;
currentEpoch = Epoch({
epochhash: epochhash,
blocknumber: block.number
});
// Update the registry information
numDarknodesPreviousEpoch = numDarknodes;
numDarknodes = numDarknodesNextEpoch;
// If any update functions have been called, update the values now
if (nextMinimumBond != minimumBond) {
minimumBond = nextMinimumBond;
emit LogMinimumBondUpdated(minimumBond, nextMinimumBond);
}
if (nextMinimumPodSize != minimumPodSize) {
minimumPodSize = nextMinimumPodSize;
emit LogMinimumPodSizeUpdated(minimumPodSize, nextMinimumPodSize);
}
if (nextMinimumEpochInterval != minimumEpochInterval) {
minimumEpochInterval = nextMinimumEpochInterval;
emit LogMinimumEpochIntervalUpdated(minimumEpochInterval, nextMinimumEpochInterval);
}
if (nextSlasher != slasher) {
slasher = nextSlasher;
emit LogSlasherUpdated(address(slasher), address(nextSlasher));
}
// Emit an event
emit LogNewEpoch(epochhash);
}
/// @notice Allows the contract owner to initiate an ownership transfer of
/// the DarknodeRegistryStore.
/// @param _newOwner The address to transfer the ownership to.
function transferStoreOwnership(address _newOwner) external onlyOwner {
store.transferOwnership(_newOwner);
}
/// @notice Claims ownership of the store passed in to the constructor.
/// `transferStoreOwnership` must have previously been called when
/// transferring from another Darknode Registry.
function claimStoreOwnership() external onlyOwner {
store.claimOwnership();
}
/// @notice Allows the contract owner to update the minimum bond.
/// @param _nextMinimumBond The minimum bond amount that can be submitted by
/// a darknode.
function updateMinimumBond(uint256 _nextMinimumBond) external onlyOwner {
// Will be updated next epoch
nextMinimumBond = _nextMinimumBond;
}
/// @notice Allows the contract owner to update the minimum pod size.
/// @param _nextMinimumPodSize The minimum size of a pod.
function updateMinimumPodSize(uint256 _nextMinimumPodSize) external onlyOwner {
// Will be updated next epoch
nextMinimumPodSize = _nextMinimumPodSize;
}
/// @notice Allows the contract owner to update the minimum epoch interval.
/// @param _nextMinimumEpochInterval The minimum number of blocks between epochs.
function updateMinimumEpochInterval(uint256 _nextMinimumEpochInterval) external onlyOwner {
// Will be updated next epoch
nextMinimumEpochInterval = _nextMinimumEpochInterval;
}
/// @notice Allow the contract owner to update the DarknodeSlasher contract
/// address.
/// @param _slasher The new slasher address.
function updateSlasher(DarknodeSlasher _slasher) external onlyOwner {
require(address(_slasher) != address(0), "invalid slasher address");
nextSlasher = _slasher;
}
/// @notice Allow the DarknodeSlasher contract to slash half of a darknode's
/// bond and deregister it. The bond is distributed as follows:
/// 1/2 is kept by the guilty prover
/// 1/8 is rewarded to the first challenger
/// 1/8 is rewarded to the second challenger
/// 1/4 becomes unassigned
/// @param _prover The guilty prover whose bond is being slashed
/// @param _challenger1 The first of the two darknodes who submitted the challenge
/// @param _challenger2 The second of the two darknodes who submitted the challenge
function slash(address _prover, address _challenger1, address _challenger2)
external
onlySlasher
{
uint256 penalty = store.darknodeBond(_prover) / 2;
uint256 reward = penalty / 4;
// Slash the bond of the failed prover in half
store.updateDarknodeBond(_prover, penalty);
// If the darknode has not been deregistered then deregister it
if (isDeregisterable(_prover)) {
deregisterDarknode(_prover);
}
// Reward the challengers with less than the penalty so that it is not
// worth challenging yourself
require(ren.transfer(store.darknodeOwner(_challenger1), reward), "reward transfer failed");
require(ren.transfer(store.darknodeOwner(_challenger2), reward), "reward transfer failed");
}
/// @notice Refund the bond of a deregistered darknode. This will make the
/// darknode available for registration again. Anyone can call this function
/// but the bond will always be refunded to the darknode owner.
///
/// @param _darknodeID The darknode ID that will be refunded. The caller
/// of this method must be the owner of this darknode.
function refund(address _darknodeID) external onlyRefundable(_darknodeID) {
address darknodeOwner = store.darknodeOwner(_darknodeID);
// Remember the bond amount
uint256 amount = store.darknodeBond(_darknodeID);
// Erase the darknode from the registry
store.removeDarknode(_darknodeID);
// Refund the owner by transferring REN
require(ren.transfer(darknodeOwner, amount), "bond transfer failed");
// Emit an event.
emit LogDarknodeOwnerRefunded(darknodeOwner, amount);
}
/// @notice Retrieves the address of the account that registered a darknode.
/// @param _darknodeID The ID of the darknode to retrieve the owner for.
function getDarknodeOwner(address _darknodeID) external view returns (address payable) {
return store.darknodeOwner(_darknodeID);
}
/// @notice Retrieves the bond amount of a darknode in 10^-18 REN.
/// @param _darknodeID The ID of the darknode to retrieve the bond for.
function getDarknodeBond(address _darknodeID) external view returns (uint256) {
return store.darknodeBond(_darknodeID);
}
/// @notice Retrieves the encryption public key of the darknode.
/// @param _darknodeID The ID of the darknode to retrieve the public key for.
function getDarknodePublicKey(address _darknodeID) external view returns (bytes memory) {
return store.darknodePublicKey(_darknodeID);
}
/// @notice Retrieves a list of darknodes which are registered for the
/// current epoch.
/// @param _start A darknode ID used as an offset for the list. If _start is
/// 0x0, the first dark node will be used. _start won't be
/// included it is not registered for the epoch.
/// @param _count The number of darknodes to retrieve starting from _start.
/// If _count is 0, all of the darknodes from _start are
/// retrieved. If _count is more than the remaining number of
/// registered darknodes, the rest of the list will contain
/// 0x0s.
function getDarknodes(address _start, uint256 _count) external view returns (address[] memory) {
uint256 count = _count;
if (count == 0) {
count = numDarknodes;
}
return getDarknodesFromEpochs(_start, count, false);
}
/// @notice Retrieves a list of darknodes which were registered for the
/// previous epoch. See `getDarknodes` for the parameter documentation.
function getPreviousDarknodes(address _start, uint256 _count) external view returns (address[] memory) {
uint256 count = _count;
if (count == 0) {
count = numDarknodesPreviousEpoch;
}
return getDarknodesFromEpochs(_start, count, true);
}
/// @notice Returns whether a darknode is scheduled to become registered
/// at next epoch.
/// @param _darknodeID The ID of the darknode to return
function isPendingRegistration(address _darknodeID) external view returns (bool) {
uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID);
return registeredAt != 0 && registeredAt > currentEpoch.blocknumber;
}
/// @notice Returns if a darknode is in the pending deregistered state. In
/// this state a darknode is still considered registered.
function isPendingDeregistration(address _darknodeID) external view returns (bool) {
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
return deregisteredAt != 0 && deregisteredAt > currentEpoch.blocknumber;
}
/// @notice Returns if a darknode is in the deregistered state.
function isDeregistered(address _darknodeID) public view returns (bool) {
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
return deregisteredAt != 0 && deregisteredAt <= currentEpoch.blocknumber;
}
/// @notice Returns if a darknode can be deregistered. This is true if the
/// darknodes is in the registered state and has not attempted to
/// deregister yet.
function isDeregisterable(address _darknodeID) public view returns (bool) {
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
// The Darknode is currently in the registered state and has not been
// transitioned to the pending deregistration, or deregistered, state
return isRegistered(_darknodeID) && deregisteredAt == 0;
}
/// @notice Returns if a darknode is in the refunded state. This is true
/// for darknodes that have never been registered, or darknodes that have
/// been deregistered and refunded.
function isRefunded(address _darknodeID) public view returns (bool) {
uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID);
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
return registeredAt == 0 && deregisteredAt == 0;
}
/// @notice Returns if a darknode is refundable. This is true for darknodes
/// that have been in the deregistered state for one full epoch.
function isRefundable(address _darknodeID) public view returns (bool) {
return isDeregistered(_darknodeID) && store.darknodeDeregisteredAt(_darknodeID) <= previousEpoch.blocknumber;
}
/// @notice Returns if a darknode is in the registered state.
function isRegistered(address _darknodeID) public view returns (bool) {
return isRegisteredInEpoch(_darknodeID, currentEpoch);
}
/// @notice Returns if a darknode was in the registered state last epoch.
function isRegisteredInPreviousEpoch(address _darknodeID) public view returns (bool) {
return isRegisteredInEpoch(_darknodeID, previousEpoch);
}
/// @notice Returns if a darknode was in the registered state for a given
/// epoch.
/// @param _darknodeID The ID of the darknode
/// @param _epoch One of currentEpoch, previousEpoch
function isRegisteredInEpoch(address _darknodeID, Epoch memory _epoch) private view returns (bool) {
uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID);
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
bool registered = registeredAt != 0 && registeredAt <= _epoch.blocknumber;
bool notDeregistered = deregisteredAt == 0 || deregisteredAt > _epoch.blocknumber;
// The Darknode has been registered and has not yet been deregistered,
// although it might be pending deregistration
return registered && notDeregistered;
}
/// @notice Returns a list of darknodes registered for either the current
/// or the previous epoch. See `getDarknodes` for documentation on the
/// parameters `_start` and `_count`.
/// @param _usePreviousEpoch If true, use the previous epoch, otherwise use
/// the current epoch.
function getDarknodesFromEpochs(address _start, uint256 _count, bool _usePreviousEpoch) private view returns (address[] memory) {
uint256 count = _count;
if (count == 0) {
count = numDarknodes;
}
address[] memory nodes = new address[](count);
// Begin with the first node in the list
uint256 n = 0;
address next = _start;
if (next == address(0)) {
next = store.begin();
}
// Iterate until all registered Darknodes have been collected
while (n < count) {
if (next == address(0)) {
break;
}
// Only include Darknodes that are currently registered
bool includeNext;
if (_usePreviousEpoch) {
includeNext = isRegisteredInPreviousEpoch(next);
} else {
includeNext = isRegistered(next);
}
if (!includeNext) {
next = store.next(next);
continue;
}
nodes[n] = next;
next = store.next(next);
n += 1;
}
return nodes;
}
/// Private function called by `deregister` and `slash`
function deregisterDarknode(address _darknodeID) private {
// Flag the darknode for deregistration
store.updateDarknodeDeregisteredAt(_darknodeID, currentEpoch.blocknumber.add(minimumEpochInterval));
numDarknodesNextEpoch = numDarknodesNextEpoch.sub(1);
// Emit an event
emit LogDarknodeDeregistered(_darknodeID);
}
}
/// @notice DarknodePaymentStore is responsible for tracking black/whitelisted
/// darknodes as well as the balances which have been allocated to the
/// darknodes. It is also responsible for holding the tokens to be paid
/// out to darknodes.
contract DarknodePaymentStore is Claimable {
using SafeMath for uint256;
using CompatibleERC20Functions for ERC20;
string public VERSION; // Passed in as a constructor parameter.
/// @notice The special address for Ether.
address constant public ETHEREUM = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @notice The size of the whitelist
uint256 public darknodeWhitelistLength;
/// @notice Mapping of darknode -> token -> balance
mapping(address => mapping(address => uint256)) public darknodeBalances;
/// @notice Mapping of token -> lockedAmount
mapping(address => uint256) public lockedBalances;
/// @notice mapping of darknode -> blacklistTimestamp
mapping(address => uint256) public darknodeBlacklist;
/// @notice mapping of darknode -> whitelistTimestamp
mapping(address => uint256) public darknodeWhitelist;
/// @notice The contract constructor.
///
/// @param _VERSION A string defining the contract version.
constructor(
string memory _VERSION
) public {
VERSION = _VERSION;
}
/// @notice Allow direct payments to be made to the DarknodePaymentStore.
function () external payable {
}
/// @notice Checks to see if a darknode is blacklisted
///
/// @param _darknode The address of the darknode
/// @return true if the darknode is blacklisted
function isBlacklisted(address _darknode) public view returns (bool) {
return darknodeBlacklist[_darknode] != 0;
}
/// @notice Checks to see if a darknode is whitelisted
///
/// @param _darknode The address of the darknode
/// @return true if the darknode is whitelisted
function isWhitelisted(address _darknode) public view returns (bool) {
return darknodeWhitelist[_darknode] != 0;
}
/// @notice Get the total balance of the contract for a particular token
///
/// @param _token The token to check balance of
/// @return The total balance of the contract
function totalBalance(address _token) public view returns (uint256) {
if (_token == ETHEREUM) {
return address(this).balance;
} else {
return ERC20(_token).balanceOf(address(this));
}
}
/// @notice Get the available balance of the contract for a particular token
/// This is the free amount which has not yet been allocated to
/// darknodes.
///
/// @param _token The token to check balance of
/// @return The available balance of the contract
function availableBalance(address _token) public view returns (uint256) {
return totalBalance(_token).sub(lockedBalances[_token]);
}
/// @notice Blacklists a darknode from participating in reward allocation.
/// If the darknode is whitelisted, it is removed from the whitelist
/// and the number of whitelisted nodes is decreased.
///
/// @param _darknode The address of the darknode to blacklist
function blacklist(address _darknode) external onlyOwner {
require(!isBlacklisted(_darknode), "darknode already blacklisted");
darknodeBlacklist[_darknode] = now;
// Unwhitelist if necessary
if (isWhitelisted(_darknode)) {
darknodeWhitelist[_darknode] = 0;
// Use SafeMath when subtracting to avoid underflows
darknodeWhitelistLength = darknodeWhitelistLength.sub(1);
}
}
/// @notice Whitelists a darknode allowing it to participate in reward
/// allocation.
///
/// @param _darknode The address of the darknode to whitelist
function whitelist(address _darknode) external onlyOwner {
require(!isBlacklisted(_darknode), "darknode is blacklisted");
require(!isWhitelisted(_darknode), "darknode already whitelisted");
darknodeWhitelist[_darknode] = now;
darknodeWhitelistLength++;
}
/// @notice Increments the amount of funds allocated to a particular
/// darknode.
///
/// @param _darknode The address of the darknode to increase balance of
/// @param _token The token which the balance should be incremented
/// @param _amount The amount that the balance should be incremented by
function incrementDarknodeBalance(address _darknode, address _token, uint256 _amount) external onlyOwner {
require(_amount > 0, "invalid amount");
require(availableBalance(_token) >= _amount, "insufficient contract balance");
darknodeBalances[_darknode][_token] = darknodeBalances[_darknode][_token].add(_amount);
lockedBalances[_token] = lockedBalances[_token].add(_amount);
}
/// @notice Transfers an amount out of balance to a specified address
///
/// @param _darknode The address of the darknode
/// @param _token Which token to transfer
/// @param _amount The amount to transfer
/// @param _recipient The address to withdraw it to
function transfer(address _darknode, address _token, uint256 _amount, address payable _recipient) external onlyOwner {
require(darknodeBalances[_darknode][_token] >= _amount, "insufficient darknode balance");
darknodeBalances[_darknode][_token] = darknodeBalances[_darknode][_token].sub(_amount);
lockedBalances[_token] = lockedBalances[_token].sub(_amount);
if (_token == ETHEREUM) {
_recipient.transfer(_amount);
} else {
ERC20(_token).safeTransfer(_recipient, _amount);
}
}
}
/// @notice DarknodePayment is responsible for paying off darknodes for their
/// computation.
contract DarknodePayment is Ownable {
using SafeMath for uint256;
using CompatibleERC20Functions for ERC20;
string public VERSION; // Passed in as a constructor parameter.
/// @notice The special address for Ether.
address constant public ETHEREUM = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
DarknodeRegistry public darknodeRegistry; // Passed in as a constructor parameter.
/// @notice DarknodePaymentStore is the storage contract for darknode
/// payments.
DarknodePaymentStore public store; // Passed in as a constructor parameter.
/// @notice The address that can call blacklist()
address public blacklister;
uint256 public currentCycle;
uint256 public previousCycle;
/// @notice The number of whitelisted darknodes this cycle
uint256 public shareCount;
/// @notice The list of tokens that will be registered next cycle.
/// We only update the shareCount at the change of cycle to
/// prevent the number of shares from changing.
address[] public pendingTokens;
/// @notice The list of tokens which are already registered and rewards can
/// be claimed for.
address[] public registeredTokens;
/// @notice Mapping from token -> index. Index starts from 1. 0 means not in
/// list.
mapping(address => uint256) public registeredTokenIndex;
/// @notice Mapping from token -> amount.
/// The amount of rewards allocated for all darknodes to claim into
/// their account.
mapping(address => uint256) public unclaimedRewards;
/// @notice Mapping from token -> amount.
/// The amount of rewards allocated for each darknode.
mapping(address => uint256) public previousCycleRewardShare;
/// @notice The time that the current cycle started.
uint256 public cycleStartTime;
/// @notice The minimum duration that the current cycle must go for.
uint256 public cycleDuration;
/// @notice The earliest timestamp that changeCycle() can be called.
uint256 public cycleTimeout;
/// @notice Mapping of darknode -> cycle -> already_claimed
/// Used to keep track of which darknodes have already claimed their
/// rewards.
mapping(address => mapping(uint256 => bool)) public rewardClaimed;
/// @notice Emitted when a darknode is blacklisted from receiving rewards
/// @param _darknode The address of the darknode which was blacklisted
/// @param _time The time at which the darknode was blacklisted
event LogDarknodeBlacklisted(address indexed _darknode, uint256 _time);
/// @notice Emitted when a darknode is whitelisted to receive rewards
/// @param _darknode The address of the darknode which was whitelisted
/// @param _time The time at which the darknode was whitelisted
event LogDarknodeWhitelisted(address indexed _darknode, uint256 _time);
/// @notice Emitted when a darknode claims their share of reward
/// @param _darknode The darknode which claimed
/// @param _cycle The cycle that the darknode claimed for
event LogDarknodeClaim(address indexed _darknode, uint256 _cycle);
/// @notice Emitted when someone pays the DarknodePayment contract
/// @param _payer The darknode which claimed
/// @param _amount The cycle that the darknode claimed for
/// @param _token The address of the token that was transferred
event LogPaymentReceived(address indexed _payer, uint256 _amount, address _token);
/// @notice Emitted when a darknode calls withdraw
/// @param _payee The address of the darknode which withdrew
/// @param _value The amount of DAI withdrawn
/// @param _token The address of the token that was withdrawn
event LogDarknodeWithdrew(address indexed _payee, uint256 _value, address _token);
/// @notice Emitted when a new cycle happens
/// @param _newCycle The new, current cycle
/// @param _lastCycle The previous cycle
/// @param _cycleTimeout The earliest a new cycle can be called
event LogNewCycle(uint256 _newCycle, uint256 _lastCycle, uint256 _cycleTimeout);
/// @notice Emitted when the cycle duration changes
/// @param _newDuration The new duration
/// @param _oldDuration The old duration
event LogCycleDurationChanged(uint256 _newDuration, uint256 _oldDuration);
/// @notice Emitted when the Blacklister contract changes
/// @param _newBlacklister The new Blacklister
/// @param _oldBlacklister The old Blacklister
event LogBlacklisterChanged(address _newBlacklister, address _oldBlacklister);
/// @notice Emitted when a new token is registered
/// @param _token The token that was registered
event LogTokenRegistered(address _token);
/// @notice Emitted when a token is deregistered
/// @param _token The token that was deregistered
event LogTokenDeregistered(address _token);
/// @notice Only allow registered dark nodes.
modifier onlyDarknode(address _darknode) {
require(darknodeRegistry.isRegistered(_darknode), "darknode is not registered");
_;
}
/// @notice Only allow the Darknode Payment contract.
modifier onlyBlacklister() {
require(blacklister == msg.sender, "not Blacklister");
_;
}
/// @notice Only allow darknodes which haven't been blacklisted
modifier notBlacklisted(address _darknode) {
require(!store.isBlacklisted(_darknode), "darknode is blacklisted");
_;
}
/// @notice The contract constructor. Starts the current cycle using the
/// time of deploy.
///
/// @param _VERSION A string defining the contract version.
/// @param _darknodeRegistry The address of the DarknodeRegistry contract
/// @param _darknodePaymentStore The address of the DarknodePaymentStore
/// contract
/// @param _cycleDurationSeconds The minimum time before a new cycle can occur in seconds
constructor(
string memory _VERSION,
DarknodeRegistry _darknodeRegistry,
DarknodePaymentStore _darknodePaymentStore,
uint256 _cycleDurationSeconds
) public {
VERSION = _VERSION;
darknodeRegistry = _darknodeRegistry;
store = _darknodePaymentStore;
cycleDuration = _cycleDurationSeconds;
// Default the blacklister to owner
blacklister = msg.sender;
// Start the current cycle
currentCycle = block.number;
cycleStartTime = now;
cycleTimeout = cycleStartTime.add(cycleDuration);
}
/// @notice Transfers the funds allocated to the darknode to the darknode
/// owner.
///
/// @param _darknode The address of the darknode
/// @param _token Which token to transfer
function withdraw(address _darknode, address _token) public {
address payable darknodeOwner = darknodeRegistry.getDarknodeOwner(_darknode);
require(darknodeOwner != address(0x0), "invalid darknode owner");
uint256 amount = store.darknodeBalances(_darknode, _token);
require(amount > 0, "nothing to withdraw");
store.transfer(_darknode, _token, amount, darknodeOwner);
emit LogDarknodeWithdrew(_darknode, amount, _token);
}
function withdrawMultiple(address _darknode, address[] calldata _tokens) external {
for (uint i = 0; i < _tokens.length; i++) {
withdraw(_darknode, _tokens[i]);
}
}
/// @notice Forward all payments to the DarknodePaymentStore.
function () external payable { //inject DOS BY COMPLEX FALLBACK
address(store).call.gas(2301).value(msg.value)("");
emit LogPaymentReceived(msg.sender, msg.value, ETHEREUM);
}
/// @notice The current balance of the contract available as reward for the
/// current cycle
function currentCycleRewardPool(address _token) external view returns (uint256) {
return store.availableBalance(_token).sub(unclaimedRewards[_token]);
}
function darknodeBalances(address _darknodeID, address _token) external view returns (uint256) {
return store.darknodeBalances(_darknodeID, _token);
}
/// @notice Changes the current cycle.
function changeCycle() external returns (uint256) {
require(now >= cycleTimeout, "cannot cycle yet: too early");
require(block.number != currentCycle, "no new block");
// Snapshot balances for the past cycle
uint arrayLength = registeredTokens.length;
for (uint i = 0; i < arrayLength; i++) {
_snapshotBalance(registeredTokens[i]);
}
// Start a new cycle
previousCycle = currentCycle;
currentCycle = block.number;
cycleStartTime = now;
cycleTimeout = cycleStartTime.add(cycleDuration);
// Update the share size for next cycle
shareCount = store.darknodeWhitelistLength();
// Update the list of registeredTokens
_updateTokenList();
emit LogNewCycle(currentCycle, previousCycle, cycleTimeout);
return currentCycle;
}
/// @notice Deposits token into the contract to be paid to the Darknodes
///
/// @param _value The amount of token deposit in the token's smallest unit.
/// @param _token The token address
function deposit(uint256 _value, address _token) external payable {
uint256 receivedValue;
if (_token == ETHEREUM) {
require(_value == msg.value, "mismatched deposit value");
receivedValue = msg.value;
address(store).transfer(msg.value);
} else {
require(msg.value == 0, "unexpected ether transfer");
// Forward the funds to the store
receivedValue = ERC20(_token).safeTransferFromWithFees(msg.sender, address(store), _value);
}
emit LogPaymentReceived(msg.sender, receivedValue, _token);
}
/// @notice Claims the rewards allocated to the darknode last cycle and
/// increments the darknode balances. Whitelists the darknode if it
/// hasn't already been whitelisted. If a darknode does not call
/// claim() then the rewards for the previous cycle is lost.
///
/// @param _darknode The address of the darknode to claim
function claim(address _darknode) external onlyDarknode(_darknode) notBlacklisted(_darknode) {
uint256 whitelistedTime = store.darknodeWhitelist(_darknode);
// The darknode hasn't been whitelisted before
if (whitelistedTime == 0) {
store.whitelist(_darknode);
emit LogDarknodeWhitelisted(_darknode, now);
return;
}
require(whitelistedTime < cycleStartTime, "cannot claim for this cycle");
// Claim share of rewards allocated for last cycle
_claimDarknodeReward(_darknode);
emit LogDarknodeClaim(_darknode, previousCycle);
}
/// @notice Blacklists a darknode from participating in rewards.
///
/// @param _darknode The address of the darknode to blacklist
function blacklist(address _darknode) external onlyBlacklister onlyDarknode(_darknode) {
store.blacklist(_darknode);
emit LogDarknodeBlacklisted(_darknode, now);
}
/// @notice Adds tokens to be payable. Registration is pending until next
/// cycle.
///
/// @param _token The address of the token to be registered.
function registerToken(address _token) external onlyOwner {
require(registeredTokenIndex[_token] == 0, "token already registered");
uint arrayLength = pendingTokens.length;
for (uint i = 0; i < arrayLength; i++) {
require(pendingTokens[i] != _token, "token already pending registration");
}
pendingTokens.push(_token);
}
/// @notice Removes a token from the list of supported tokens.
/// Deregistration is pending until next cycle.
///
/// @param _token The address of the token to be deregistered.
function deregisterToken(address _token) external onlyOwner {
require(registeredTokenIndex[_token] > 0, "token not registered");
_deregisterToken(_token);
}
/// @notice Updates the Blacklister contract address.
///
/// @param _addr The new Blacklister contract address.
function updateBlacklister(address _addr) external onlyOwner {
require(_addr != address(0), "invalid contract address");
emit LogBlacklisterChanged(_addr, blacklister);
blacklister = _addr;
}
/// @notice Updates cycle duration
///
/// @param _durationSeconds The amount of time (in seconds) that should have
/// passed before a new cycle can be called.
function updateCycleDuration(uint256 _durationSeconds) external onlyOwner {
uint256 oldDuration = cycleDuration;
cycleDuration = _durationSeconds;
emit LogCycleDurationChanged(cycleDuration, oldDuration);
}
/// @notice Allows the contract owner to initiate an ownership transfer of
/// the DarknodePaymentStore.
///
/// @param _newOwner The address to transfer the ownership to.
function transferStoreOwnership(address _newOwner) external onlyOwner {
store.transferOwnership(_newOwner);
}
/// @notice Claims ownership of the store passed in to the constructor.
/// `transferStoreOwnership` must have previously been called when
/// transferring from another DarknodePaymentStore.
function claimStoreOwnership() external onlyOwner {
store.claimOwnership();
}
/// @notice Claims the darknode reward for all registered tokens into
/// darknodeBalances in the DarknodePaymentStore.
/// Rewards can only be claimed once per cycle.
///
/// @param _darknode The address to the darknode to claim rewards for
function _claimDarknodeReward(address _darknode) private {
require(!rewardClaimed[_darknode][previousCycle], "reward already claimed");
rewardClaimed[_darknode][previousCycle] = true;
uint arrayLength = registeredTokens.length;
for (uint i = 0; i < arrayLength; i++) {
address token = registeredTokens[i];
// Only increment balance if shares were allocated last cycle
if (previousCycleRewardShare[token] > 0) {
unclaimedRewards[token] = unclaimedRewards[token].sub(previousCycleRewardShare[token]);
store.incrementDarknodeBalance(_darknode, token, previousCycleRewardShare[token]);
}
}
}
/// @notice Snapshots the current balance of the tokens, for all registered
/// tokens.
///
/// @param _token The address the token to snapshot.
function _snapshotBalance(address _token) private {
if (shareCount == 0) {
unclaimedRewards[_token] = 0;
previousCycleRewardShare[_token] = 0;
} else {
// Lock up the current balance for darknode reward allocation
unclaimedRewards[_token] = store.availableBalance(_token);
previousCycleRewardShare[_token] = unclaimedRewards[_token].div(shareCount);
}
}
/// @notice Deregisters a token, removing it from the list of
/// registeredTokens.
///
/// @param _token The address of the token to deregister.
function _deregisterToken(address _token) private {
address lastToken = registeredTokens[registeredTokens.length.sub(1)];
uint256 deletedTokenIndex = registeredTokenIndex[_token].sub(1);
// Move the last token to _token's position and update it's index
registeredTokens[deletedTokenIndex] = lastToken;
registeredTokenIndex[lastToken] = registeredTokenIndex[_token];
// Decreasing the length will clean up the storage for us
// So we don't need to manually delete the element
registeredTokens.length = registeredTokens.length.sub(1);
registeredTokenIndex[_token] = 0;
emit LogTokenDeregistered(_token);
}
/// @notice Updates the list of registeredTokens adding tokens that are to be registered.
/// The list of tokens that are pending registration are emptied afterwards.
function _updateTokenList() private {
// Register tokens
uint arrayLength = pendingTokens.length;
for (uint i = 0; i < arrayLength; i++) {
address token = pendingTokens[i];
registeredTokens.push(token);
registeredTokenIndex[token] = registeredTokens.length;
emit LogTokenRegistered(token);
}
pendingTokens.length = 0;
}
}
|
Transfers the funds allocated to the darknode to the darknode owner. _darknode The address of the darknode _token Which token to transfer
|
function withdraw(address _darknode, address _token) public {
address payable darknodeOwner = darknodeRegistry.getDarknodeOwner(_darknode);
require(darknodeOwner != address(0x0), "invalid darknode owner");
uint256 amount = store.darknodeBalances(_darknode, _token);
require(amount > 0, "nothing to withdraw");
store.transfer(_darknode, _token, amount, darknodeOwner);
emit LogDarknodeWithdrew(_darknode, amount, _token);
}
| 6,360,681
|
// SPDX-License-Identifier: MIT
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() {
_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;
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
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 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 "../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 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;
/**
* @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;
/**
* @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));
}
}
// 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 "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "./ProtectedMint.sol";
import "./IOpenSeaProxy.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, ProtectedMint {
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) internal _owners;
// Mapping owner address to token count
mapping(address => uint16) internal _balances;
// Mapping from token ID to approved address
mapping(uint16 => address) internal _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) internal _operatorApprovals;
// OpenSea's proxy registry address
address proxyRegistryAddress;
/**
* @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 = 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, uint16(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[uint16(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) {
if (proxyRegistryAddress != address(0)) {
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
}
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 Sets OpenSea's proxy registry address
*/
function setProxyRegistryAddress(address _proxyRegistryAddress) external onlyOwner {
proxyRegistryAddress = _proxyRegistryAddress;
}
/**
* @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 = 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(uint16 tokenId) internal virtual {
address owner = 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(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), uint16(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, uint16 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(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 "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "./QueensAndKingsAvatars.sol";
contract FirstDrop is Ownable {
modifier callerIsUser() {
require(tx.origin == msg.sender, "The caller is another contract");
_;
}
address public avatarContractAddress;
address public signerAddress;
address public sAddress;
uint16 public sMintLimit = 300;
uint16 public sMintedTokens = 0;
uint16 public totalAvatars = 2000;
uint256 public mintPrice = 0.423 ether;
string public ipfsAvatars;
mapping(uint16 => uint16) private tokenMatrix;
mapping(address => uint8) public mintsPerUser;
// DEBUG
function setTotalAvatars(uint16 _totalAvatars) external onlyOwner {
totalAvatars = _totalAvatars;
}
// ONLY OWNER
/**
* @dev Allows to withdraw the Ether in the contract
*/
function withdraw() external onlyOwner {
payable(msg.sender).transfer(address(this).balance);
}
/**
* @dev Sets the mint price
*/
function setMintPrice(uint256 _mintPrice) external onlyOwner {
mintPrice = _mintPrice;
}
/**
* @dev Sets the avatar contract address
*/
function setAvatarContractAddress(address _address) external onlyOwner {
avatarContractAddress = _address;
}
/**
* @dev Sets the address that generates the signatures for whitelisting
*/
function setSignerAddress(address _signerAddress) external onlyOwner {
signerAddress = _signerAddress;
}
/**
* @dev Sets the address that can call mintTo
*/
function setSAddress(address _sAddress) external onlyOwner {
sAddress = _sAddress;
}
/**
* @dev Sets how many mints can the sAddress do
*/
function setSMintLimit(uint16 _sMintLimit) external onlyOwner {
sMintLimit = _sMintLimit;
}
function setIPFSAvatars(string memory _ipfsAvatars) external onlyOwner {
ipfsAvatars = _ipfsAvatars;
}
// END ONLY OWNER
/**
* @dev Mint function
*/
function mint(
uint8 _quantity,
uint256 _fromTimestamp,
uint256 _toTimestamp,
uint8 _maxQuantity,
bytes calldata _signature
) external payable callerIsUser {
bytes32 messageHash = generateMessageHash(msg.sender, _fromTimestamp, _toTimestamp, _maxQuantity);
address recoveredWallet = ECDSA.recover(messageHash, _signature);
require(recoveredWallet == signerAddress, "Invalid signature for the caller");
require(block.timestamp >= _fromTimestamp, "Too early to mint");
require(block.timestamp <= _toTimestamp, "The signature has expired");
QueensAndKingsAvatars qakContract = QueensAndKingsAvatars(avatarContractAddress);
uint16 tmpTotalSupply = qakContract.totalSupply();
uint256 tokensLeft = totalAvatars - tmpTotalSupply;
require(tokensLeft > 0, "No tokens left to be minted");
if (_quantity + mintsPerUser[msg.sender] > _maxQuantity) {
_quantity = _maxQuantity - mintsPerUser[msg.sender];
}
if (_quantity > tokensLeft) {
_quantity = uint8(tokensLeft);
}
uint256 totalMintPrice = mintPrice * _quantity;
require(msg.value >= totalMintPrice, "Not enough Ether provided to mint");
if (msg.value > totalMintPrice) {
payable(msg.sender).transfer(msg.value - totalMintPrice);
}
require(_quantity != 0, "Address mint limit reached");
mintsPerUser[msg.sender] += _quantity;
for (uint16 i; i < _quantity; i++) {
uint16 _tokenId = _getTokenToBeMinted(tmpTotalSupply);
qakContract.mint(_tokenId, msg.sender);
tmpTotalSupply++;
}
}
/**
* @dev mint to address
*/
function mintTo(address[] memory _addresses) external {
require(msg.sender == sAddress, "Caller is not allowed to mint");
require(_addresses.length > 0, "At least one token should be minted");
require(sMintedTokens + _addresses.length <= sMintLimit, "Mint limit reached");
QueensAndKingsAvatars qakContract = QueensAndKingsAvatars(avatarContractAddress);
uint16 tmpTotalSupply = qakContract.totalSupply();
sMintedTokens += uint16(_addresses.length);
for (uint256 i; i < _addresses.length; i++) {
qakContract.mint(_getTokenToBeMinted(tmpTotalSupply), _addresses[i]);
tmpTotalSupply++;
}
}
/**
* @dev mint to address
*/
function mintToDev(address[] memory _addresses) external onlyOwner {
require(_addresses.length > 0, "At least one token should be minted");
QueensAndKingsAvatars qakContract = QueensAndKingsAvatars(avatarContractAddress);
uint16 tmpTotalSupply = qakContract.totalSupply();
uint256 tokensLeft = totalAvatars - tmpTotalSupply;
require(tokensLeft > 0, "No tokens left to be minted");
for (uint256 i; i < _addresses.length; i++) {
qakContract.mint(_getTokenToBeMinted(tmpTotalSupply), _addresses[i]);
tmpTotalSupply++;
}
}
/**
* @dev gets the amount of available tokens left to be minted
*/
function getAvailableTokens() external view returns (uint16) {
QueensAndKingsAvatars qakContract = QueensAndKingsAvatars(avatarContractAddress);
return totalAvatars - qakContract.totalSupply();
}
/**
* @dev Generates the message hash for the given parameters
*/
function generateMessageHash(
address _address,
uint256 _fromTimestamp,
uint256 _toTimestamp,
uint8 _maxQuantity
) internal pure returns (bytes32) {
return
keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n85",
_address,
_fromTimestamp,
_toTimestamp,
_maxQuantity
)
);
}
/**
* @dev Returns a random available token to be minted
*/
function _getTokenToBeMinted(uint16 _totalMintedTokens) private returns (uint16) {
uint16 maxIndex = totalAvatars + sMintLimit - _totalMintedTokens;
uint16 random = _getRandomNumber(maxIndex, _totalMintedTokens);
uint16 tokenId = tokenMatrix[random];
if (tokenMatrix[random] == 0) {
tokenId = random;
}
tokenMatrix[maxIndex - 1] == 0 ? tokenMatrix[random] = maxIndex - 1 : tokenMatrix[random] = tokenMatrix[
maxIndex - 1
];
// IDs start from 1 instead of 0
return tokenId + 1;
}
/**
* @dev Generates a pseudo-random number.
*/
function _getRandomNumber(uint16 _upper, uint16 _totalMintedTokens) private view returns (uint16) {
uint16 random = uint16(
uint256(
keccak256(
abi.encodePacked(
_totalMintedTokens,
blockhash(block.number - 1),
block.coinbase,
block.difficulty,
msg.sender
)
)
)
);
return (random % _upper);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
interface ITrait is IERC721 {
function onTraitAddedToAvatar(uint16 _tokenId, uint16 _avatarId) external;
function onAvatarTransfer(
address _from,
address _to,
uint16 _tokenId
) external;
function onTraitRemovedFromAvatar(uint16 _tokenId, address _owner) external;
function traitToAvatar(uint16) external returns (uint16);
function mint(uint256 _tokenId, address _to) external;
function burn(uint16 _tokenId) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
abstract contract ProtectedMint is Ownable {
address[] public minterAddresses;
modifier onlyMinter() {
bool isAllowed;
for (uint256 i; i < minterAddresses.length; i++) {
if (minterAddresses[i] == msg.sender) {
isAllowed = true;
break;
}
}
require(isAllowed, "Minter: caller is not an allowed minter");
_;
}
/**
* @dev Adds an address that is allowed to mint
*/
function addMinterAddress(address _minterAddress) external onlyOwner {
minterAddresses.push(_minterAddress);
}
/**
* @dev Removes
*/
function removeMinterAddress(address _minterAddress) external onlyOwner {
for (uint256 i; i < minterAddresses.length; i++) {
if (minterAddresses[i] != _minterAddress) {
continue;
}
minterAddresses[i] = minterAddresses[minterAddresses.length - 1];
minterAddresses.pop();
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "./ERC721.sol";
import "./ITrait.sol";
contract QueensAndKingsAvatars is ERC721 {
using Strings for uint256;
modifier onlyAvatarOwner(uint256 _tokenId) {
require(ownerOf(_tokenId) == msg.sender, "Caller is not the owner of the avatar");
_;
}
address public signerAddress;
string public baseURI = "ipfs://HASH/";
uint16 public totalTokens = 6900;
uint16 public totalSupply = 0;
uint256 public latestExternalTokenId = totalTokens + 1;
address[] public traitTypeToAddress;
// TokenId => Trait => TraitId
mapping(uint16 => mapping(uint8 => uint16)) public avatarTraits;
mapping(uint16 => bool) public hasMintedTraits;
mapping(uint256 => uint16) public externalToInternalMapping;
mapping(uint16 => uint256) public internalToExternalMapping;
mapping(uint16 => bool) public frozenAvatars;
bool isFreezeAllowed;
constructor() ERC721("Queens+KingsAvatars", "Q+KA") {}
// ONLY OWNER
/**
* @dev Sets the address that generates the signatures for whitelisting
*/
function setSignerAddress(address _signerAddress) external onlyOwner {
signerAddress = _signerAddress;
}
/**
* @dev Sets the base URI for the API that provides the NFT data.
*/
function setBaseTokenURI(string memory _uri) external onlyOwner {
baseURI = _uri;
}
/**
* @dev Adds the contract address of a trait type
*/
function addTraitType(address _traitAddress) external onlyOwner {
traitTypeToAddress.push(_traitAddress);
}
/**
* @dev Adds the contract address of a trait type
*/
function resetTraitTypes() external onlyOwner {
delete traitTypeToAddress;
}
function setFreezedAllowed(bool _isFreezeAllowed) external onlyOwner {
isFreezeAllowed = _isFreezeAllowed;
}
// END ONLY OWNER
// ONLY MINTER
/**
* @dev Mints a avatars
*/
function mint(uint16 _tokenId, address _to) external onlyMinter {
require(_tokenId > 0 && _tokenId <= totalTokens, "Token ID cannot be 0");
require(totalSupply < totalTokens, "Cannot mint more avatars");
externalToInternalMapping[_tokenId] = _tokenId;
internalToExternalMapping[_tokenId] = _tokenId;
totalSupply++;
_mint(_to, _tokenId);
}
// END ONLY MITNER
// ONLY AVATAR OWNER
/**
* @dev Adds full traits to an avatar
*/
function setTraitsToAvatar(uint256 _tokenId, uint16[] memory _traits) external onlyAvatarOwner(_tokenId) {
require(traitTypeToAddress.length == _traits.length, "Invalid amount of traits");
uint16 _iTokenId = getInternalMapping(_tokenId);
require(hasMintedTraits[_iTokenId], "Can not modify avatar until original traits are minted");
require(!frozenAvatars[_iTokenId], "Can not change the traits of a frozen avatar");
bool regenerate;
uint256[] memory traitsPreviousAvatar = new uint256[](_traits.length);
uint256 regeneratePreviousAvatarCounter;
for (uint8 i; i < _traits.length; i++) {
if (_traits[i] == avatarTraits[_iTokenId][i]) {
continue;
}
ITrait trait = ITrait(traitTypeToAddress[i]);
require(_traits[i] == 0 || trait.ownerOf(_traits[i]) == msg.sender, "Caller is not the owner of the trait");
uint16 newTraitCurrentAvatarId = trait.traitToAvatar(_traits[i]);
if (newTraitCurrentAvatarId != 0 && newTraitCurrentAvatarId != _iTokenId) {
avatarTraits[newTraitCurrentAvatarId][i] = 0;
traitsPreviousAvatar[regeneratePreviousAvatarCounter] = getExternalMapping(newTraitCurrentAvatarId);
regeneratePreviousAvatarCounter++;
}
if (avatarTraits[_iTokenId][i] != 0) {
regenerate = true;
trait.onTraitRemovedFromAvatar(avatarTraits[_iTokenId][i], ownerOf(_tokenId));
}
avatarTraits[_iTokenId][i] = _traits[i];
if (_traits[i] != 0) {
trait.onTraitAddedToAvatar(_traits[i], _iTokenId);
}
}
for (uint256 i; i < regeneratePreviousAvatarCounter; i++) {
if (_exists(traitsPreviousAvatar[i])) {
regenerateAvatar(traitsPreviousAvatar[i]);
}
}
if (regenerate) {
regenerateAvatar(_tokenId);
}
}
/**
* @dev mints the traits for a given avatar
*/
function mintTraits(
uint16 _tokenId,
uint16[] memory _traits,
bytes calldata _signature
) external {
require(ownerOf(_tokenId) == msg.sender, "Caller is not the owner of the avatar");
require(_tokenId <= totalTokens, "Invalid token Id");
require(!hasMintedTraits[_tokenId], "Traits already minted");
bytes32 messageHash = generateMessageHash(_tokenId, _traits);
address recoveredWallet = ECDSA.recover(messageHash, _signature);
require(recoveredWallet == signerAddress, "Invalid signature for the caller");
hasMintedTraits[_tokenId] = true;
for (uint8 i; i < _traits.length; i++) {
if (_traits[i] == 0) {
continue;
}
ITrait trait = ITrait(traitTypeToAddress[i]);
trait.mint(_traits[i], msg.sender);
avatarTraits[_tokenId][i] = _traits[i];
trait.onTraitAddedToAvatar(_traits[i], _tokenId);
}
}
function freeze(uint256 _tokenId) external {
require(isFreezeAllowed, "Cannot freeze at this stage");
uint16 _iTokenId = getInternalMapping(_tokenId);
require(ownerOf(_tokenId) == msg.sender, "Caller is not the owner of the avatar");
require(hasMintedTraits[_iTokenId], "Traits have not been minted");
require(!frozenAvatars[_iTokenId], "Avatar is already frozen");
frozenAvatars[_iTokenId] = true;
for (uint8 i; i < traitTypeToAddress.length; i++) {
if (avatarTraits[_iTokenId][i] == 0) {
continue;
}
ITrait trait = ITrait(traitTypeToAddress[i]);
trait.burn(avatarTraits[_iTokenId][i]);
}
}
// END ONLY AVATAR OWNER
// ONLY TRAIT CONTRACTS
/**
* @dev removes a single trait from an avatar
* by it's contract type
*/
function removeTrait(uint16 _iTokenId) external {
require(!frozenAvatars[_iTokenId], "Avatar is already frozen");
bool found;
uint256 _tokenId = getExternalMapping(_iTokenId);
for (uint8 i; i < traitTypeToAddress.length; i++) {
if (traitTypeToAddress[i] == msg.sender) {
avatarTraits[getInternalMapping(_tokenId)][i] = 0;
found = true;
break;
}
}
require(found, "Caller is not allowed");
regenerateAvatar(_tokenId);
}
// END ONLY TRAIT CONTRACTS
// CUSTOM ERC721
/**
* @dev See {ERC721}.
*
* Calls avatarTransfer for all the traits that the avatar has
* in order to emit the transfer event for all the traits
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal override {
require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
uint16 _iTokenId = getInternalMapping(tokenId);
// Clear approvals from the previous owner
_approve(address(0), uint16(tokenId));
_balances[from] -= 1;
_balances[to] += 1;
_owners[_iTokenId] = to;
emit Transfer(from, to, tokenId);
for (uint8 i; i < traitTypeToAddress.length; i++) {
if (avatarTraits[_iTokenId][i] == 0) {
continue;
}
ITrait traitContract = ITrait(traitTypeToAddress[i]);
traitContract.onAvatarTransfer(from, to, avatarTraits[_iTokenId][i]);
}
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
uint16 _iTokenId;
if (tokenId > totalTokens) {
_iTokenId = getInternalMapping(tokenId);
} else {
_iTokenId = uint16(tokenId);
}
address owner = _owners[_iTokenId];
require(owner != address(0), "ERC721 Avatar: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IRC721-_exists}.
*/
function _exists(uint256 tokenId) internal view override returns (bool) {
uint16 _iTokenId = externalToInternalMapping[tokenId];
return _owners[_iTokenId] != address(0);
}
/**
* @dev See {ERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[getInternalMapping(tokenId)];
}
/**
* @dev See {ERC721-_approve}.
*/
function _approve(address to, uint16 tokenId) internal virtual override {
_tokenApprovals[getInternalMapping(tokenId)] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
// END CUSTOM ERC721
/**
* @dev Returns the traits for the given token id
*/
function getAvatarTraits(uint256 _tokenId) external view returns (uint16[] memory) {
require(_exists(_tokenId), "ERC721: operator query for nonexistent token");
uint16 _iTokenId = getInternalMapping(_tokenId);
uint16[] memory traits = new uint16[](traitTypeToAddress.length);
for (uint8 i; i < traitTypeToAddress.length; i++) {
traits[i] = avatarTraits[_iTokenId][i];
}
return traits;
}
// INTERNAL
/**
* @dev to avoid users receiving offers for their complete avatars, removing
* the parts and accepting the offers; The NFT changes ID every time a part is removed
* or replaced
*/
function regenerateAvatar(uint256 _tokenId) internal returns (uint256) {
address _owner = ownerOf(_tokenId);
emit Transfer(_owner, address(0), _tokenId);
emit Transfer(address(0), _owner, latestExternalTokenId);
uint16 _iTokenId = getInternalMapping(_tokenId);
externalToInternalMapping[latestExternalTokenId] = _iTokenId;
internalToExternalMapping[_iTokenId] = latestExternalTokenId;
delete externalToInternalMapping[_tokenId];
latestExternalTokenId++;
return latestExternalTokenId - 1;
}
/**
* @dev returns the original id for the given avatar
*/
function getInternalMapping(uint256 _tokenId) internal view returns (uint16) {
require(externalToInternalMapping[_tokenId] != 0, "getInternalMapping: Invalid mapping");
return externalToInternalMapping[_tokenId];
}
/**
8 @dev returns the external id for the original given id
*/
function getExternalMapping(uint16 _iTokenId) internal view returns (uint256) {
require(internalToExternalMapping[_iTokenId] != 0, "getExternalMapping: Invalid mapping");
return internalToExternalMapping[_iTokenId];
}
/**
* @dev See {ERC721}.
*/
function _baseURI() internal view override returns (string memory) {
return baseURI;
}
/**
* @dev Generate a message hash for the given parameters
*/
function generateMessageHash(uint256 _avatarId, uint16[] memory _traitIds) internal pure returns (bytes32) {
uint256 signatureBytes = 32 + _traitIds.length * 32;
return
keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n", signatureBytes.toString(), _avatarId, _traitIds)
);
}
}
|
mint to address/
|
function mintTo(address[] memory _addresses) external {
require(msg.sender == sAddress, "Caller is not allowed to mint");
require(_addresses.length > 0, "At least one token should be minted");
require(sMintedTokens + _addresses.length <= sMintLimit, "Mint limit reached");
QueensAndKingsAvatars qakContract = QueensAndKingsAvatars(avatarContractAddress);
uint16 tmpTotalSupply = qakContract.totalSupply();
sMintedTokens += uint16(_addresses.length);
for (uint256 i; i < _addresses.length; i++) {
qakContract.mint(_getTokenToBeMinted(tmpTotalSupply), _addresses[i]);
tmpTotalSupply++;
}
}
| 12,144,892
|
./full_match/1/0xABE46f13C833Ab07bf9e523F485B53c9a633DD60/sources/contracts/IdleCDO.sol
|
Check that the msg.sender is the either the owner or the rebalancer
|
function _checkOnlyOwnerOrRebalancer() internal view {
require(msg.sender == rebalancer || msg.sender == owner(), "6");
}
| 8,321,949
|
/**
*Submitted for verification at Etherscan.io on 2021-08-02
*/
// Sources flattened with hardhat v2.5.0 https://hardhat.org
// File @openzeppelin/contracts/GSN/[email protected]
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/[email protected]
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/[email protected]
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;
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
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 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.
*/
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 {
_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/utils/[email protected]
pragma solidity >=0.6.0 <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 () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File @openzeppelin/contracts/math/[email protected]
pragma solidity >=0.6.0 <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, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File @openzeppelin/contracts/utils/[email protected]
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);
}
}
// File @openzeppelin/contracts/utils/[email protected]
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);
}
}
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity >=0.6.0 <0.8.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 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");
}
}
}
// File contracts/interfaces/IController.sol
/*
Copyright 2021 Cook Finance.
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;
interface IController {
function addCK(address _ckToken) external;
function feeRecipient() external view returns(address);
function getModuleFee(address _module, uint256 _feeType) external view returns(uint256);
function isModule(address _module) external view returns(bool);
function isCK(address _ckToken) external view returns(bool);
function isSystemContract(address _contractAddress) external view returns (bool);
function resourceId(uint256 _id) external view returns(address);
}
// File contracts/interfaces/ICKToken.sol
/*
Copyright 2021 Cook Finance.
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.6.10;
pragma experimental "ABIEncoderV2";
/**
* @title ICKToken
* @author Cook Finance
*
* Interface for operating with CKTokens.
*/
interface ICKToken is IERC20 {
/* ============ Enums ============ */
enum ModuleState {
NONE,
PENDING,
INITIALIZED
}
/* ============ Structs ============ */
/**
* The base definition of a CKToken Position
*
* @param component Address of token in the Position
* @param module If not in default state, the address of associated module
* @param unit Each unit is the # of components per 10^18 of a CKToken
* @param positionState Position ENUM. Default is 0; External is 1
* @param data Arbitrary data
*/
struct Position {
address component;
address module;
int256 unit;
uint8 positionState;
bytes data;
}
/**
* A struct that stores a component's cash position details and external positions
* This data structure allows O(1) access to a component's cash position units and
* virtual units.
*
* @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency
* updating all units at once via the position multiplier. Virtual units are achieved
* by dividing a "real" value by the "positionMultiplier"
* @param componentIndex
* @param externalPositionModules List of external modules attached to each external position. Each module
* maps to an external position
* @param externalPositions Mapping of module => ExternalPosition struct for a given component
*/
struct ComponentPosition {
int256 virtualUnit;
address[] externalPositionModules;
mapping(address => ExternalPosition) externalPositions;
}
/**
* A struct that stores a component's external position details including virtual unit and any
* auxiliary data.
*
* @param virtualUnit Virtual value of a component's EXTERNAL position.
* @param data Arbitrary data
*/
struct ExternalPosition {
int256 virtualUnit;
bytes data;
}
/* ============ Functions ============ */
function addComponent(address _component) external;
function removeComponent(address _component) external;
function editDefaultPositionUnit(address _component, int256 _realUnit) external;
function addExternalPositionModule(address _component, address _positionModule) external;
function removeExternalPositionModule(address _component, address _positionModule) external;
function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external;
function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external;
function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory);
function editPositionMultiplier(int256 _newMultiplier) external;
function mint(address _account, uint256 _quantity) external;
function burn(address _account, uint256 _quantity) external;
function lock() external;
function unlock() external;
function addModule(address _module) external;
function removeModule(address _module) external;
function initializeModule() external;
function setManager(address _manager) external;
function manager() external view returns (address);
function moduleStates(address _module) external view returns (ModuleState);
function getModules() external view returns (address[] memory);
function getDefaultPositionRealUnit(address _component) external view returns(int256);
function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256);
function getComponents() external view returns(address[] memory);
function getExternalPositionModules(address _component) external view returns(address[] memory);
function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory);
function isExternalPositionModule(address _component, address _module) external view returns(bool);
function isComponent(address _component) external view returns(bool);
function positionMultiplier() external view returns (int256);
function getPositions() external view returns (Position[] memory);
function getTotalComponentRealUnits(address _component) external view returns(int256);
function isInitializedModule(address _module) external view returns(bool);
function isPendingModule(address _module) external view returns(bool);
function isLocked() external view returns (bool);
}
// File contracts/interfaces/IBasicIssuanceModule.sol
/*
Copyright 2021 Cook Finance.
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.6.10;
interface IBasicIssuanceModule {
function getRequiredComponentUnitsForIssue(
ICKToken _ckToken,
uint256 _quantity
) external returns(address[] memory, uint256[] memory);
function issue(ICKToken _ckToken, uint256 _quantity, address _to) external;
}
// File contracts/interfaces/IIndexExchangeAdapter.sol
/*
Copyright 2021 Cook Finance.
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.6.10;
interface IIndexExchangeAdapter {
function getSpender() external view returns(address);
/**
* Returns calldata for executing trade on given adapter's exchange when using the GeneralIndexModule.
*
* @param _sourceToken Address of source token to be sold
* @param _destinationToken Address of destination token to buy
* @param _destinationAddress Address that assets should be transferred to
* @param _isSendTokenFixed Boolean indicating if the send quantity is fixed, used to determine correct trade interface
* @param _sourceQuantity Fixed/Max amount of source token to sell
* @param _destinationQuantity Min/Fixed amount of destination tokens to receive
* @param _data Arbitrary bytes that can be used to store exchange specific parameters or logic
*
* @return address Target contract address
* @return uint256 Call value
* @return bytes Trade calldata
*/
function getTradeCalldata(
address _sourceToken,
address _destinationToken,
address _destinationAddress,
bool _isSendTokenFixed,
uint256 _sourceQuantity,
uint256 _destinationQuantity,
bytes memory _data
)
external
view
returns (address, uint256, bytes memory);
}
// File contracts/interfaces/IPriceOracle.sol
/*
Copyright 2021 Cook Finance.
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.6.10;
/**
* @title IPriceOracle
* @author Cook Finance
*
* Interface for interacting with PriceOracle
*/
interface IPriceOracle {
/* ============ Functions ============ */
function getPrice(address _assetOne, address _assetTwo) external view returns (uint256);
function masterQuoteAsset() external view returns (address);
}
// File contracts/interfaces/external/IWETH.sol
/*
Copyright 2018 Cook Finance.
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.6.10;
/**
* @title IWETH
* @author Cook Finance
*
* Interface for Wrapped Ether. This interface allows for interaction for wrapped ether's deposit and withdrawal
* functionality.
*/
interface IWETH is IERC20{
function deposit()
external
payable;
function withdraw(
uint256 wad
)
external;
}
// File contracts/lib/AddressArrayUtils.sol
/*
Copyright 2021 Cook Finance.
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.6.10;
/**
* @title AddressArrayUtils
* @author Cook Finance
*
* Utility functions to handle Address Arrays
*/
library AddressArrayUtils {
/**
* Finds the index of the first occurrence of the given element.
* @param A The input array to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/
function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (uint256(-1), false);
}
/**
* Returns true if the value is present in the list. Uses indexOf internally.
* @param A The input array to search
* @param a The value to find
* @return Returns isIn for the first occurrence starting from index 0
*/
function contains(address[] memory A, address a) internal pure returns (bool) {
(, bool isIn) = indexOf(A, a);
return isIn;
}
/**
* Returns true if there are 2 elements that are the same in an array
* @param A The input array to search
* @return Returns boolean for the first occurrence of a duplicate
*/
function hasDuplicate(address[] memory A) internal pure returns(bool) {
require(A.length > 0, "A is empty");
for (uint256 i = 0; i < A.length - 1; i++) {
address current = A[i];
for (uint256 j = i + 1; j < A.length; j++) {
if (current == A[j]) {
return true;
}
}
}
return false;
}
/**
* @param A The input array to search
* @param a The address to remove
* @return Returns the array with the object removed.
*/
function remove(address[] memory A, address a)
internal
pure
returns (address[] memory)
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
(address[] memory _A,) = pop(A, index);
return _A;
}
}
/**
* @param A The input array to search
* @param a The address to remove
*/
function removeStorage(address[] storage A, address a)
internal
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here
if (index != lastIndex) { A[index] = A[lastIndex]; }
A.pop();
}
}
/**
* Removes specified index from array
* @param A The input array to search
* @param index The index to remove
* @return Returns the new array and the removed entry
*/
function pop(address[] memory A, uint256 index)
internal
pure
returns (address[] memory, address)
{
uint256 length = A.length;
require(index < A.length, "Index must be < A length");
address[] memory newAddresses = new address[](length - 1);
for (uint256 i = 0; i < index; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = index + 1; j < length; j++) {
newAddresses[j - 1] = A[j];
}
return (newAddresses, A[index]);
}
/**
* Returns the combination of the two arrays
* @param A The first array
* @param B The second array
* @return Returns A extended by B
*/
function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
uint256 aLength = A.length;
uint256 bLength = B.length;
address[] memory newAddresses = new address[](aLength + bLength);
for (uint256 i = 0; i < aLength; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = 0; j < bLength; j++) {
newAddresses[aLength + j] = B[j];
}
return newAddresses;
}
/**
* Validate that address and uint array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of uint
*/
function validatePairsWithArray(address[] memory A, uint[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address and bool array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of bool
*/
function validatePairsWithArray(address[] memory A, bool[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address and string array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of strings
*/
function validatePairsWithArray(address[] memory A, string[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address array lengths match, and calling address array are not empty
* and contain no duplicate elements.
*
* @param A Array of addresses
* @param B Array of addresses
*/
function validatePairsWithArray(address[] memory A, address[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address and bytes array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of bytes
*/
function validatePairsWithArray(address[] memory A, bytes[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate address array is not empty and contains no duplicate elements.
*
* @param A Array of addresses
*/
function _validateLengthAndUniqueness(address[] memory A) internal pure {
require(A.length > 0, "Array length must be > 0");
require(!hasDuplicate(A), "Cannot duplicate addresses");
}
}
// File contracts/lib/ExplicitERC20.sol
/*
Copyright 2021 Cook Finance.
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.6.10;
/**
* @title ExplicitERC20
* @author Cook Finance
*
* Utility functions for ERC20 transfers that require the explicit amount to be transferred.
*/
library ExplicitERC20 {
using SafeMath for uint256;
/**
* When given allowance, transfers a token from the "_from" to the "_to" of quantity "_quantity".
* Ensures that the recipient has received the correct quantity (ie no fees taken on transfer)
*
* @param _token ERC20 token to approve
* @param _from The account to transfer tokens from
* @param _to The account to transfer tokens to
* @param _quantity The quantity to transfer
*/
function transferFrom(
IERC20 _token,
address _from,
address _to,
uint256 _quantity
)
internal
{
// Call specified ERC20 contract to transfer tokens (via proxy).
if (_quantity > 0) {
uint256 existingBalance = _token.balanceOf(_to);
SafeERC20.safeTransferFrom(
_token,
_from,
_to,
_quantity
);
uint256 newBalance = _token.balanceOf(_to);
// Verify transfer quantity is reflected in balance
require(
newBalance == existingBalance.add(_quantity),
"Invalid post transfer balance"
);
}
}
}
// File contracts/interfaces/IModule.sol
/*
Copyright 2021 Cook Finance.
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.6.10;
/**
* @title IModule
* @author Cook Finance
*
* Interface for interacting with Modules.
*/
interface IModule {
/**
* Called by a CKToken to notify that this module was removed from the CK token. Any logic can be included
* in case checks need to be made or state needs to be cleared.
*/
function removeModule() external;
}
// File contracts/protocol/lib/Invoke.sol
/*
Copyright 2021 Cook Finance.
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.6.10;
/**
* @title Invoke
* @author Cook Finance
*
* A collection of common utility functions for interacting with the CKToken's invoke function
*/
library Invoke {
using SafeMath for uint256;
/* ============ Internal ============ */
/**
* Instructs the CKToken to set approvals of the ERC20 token to a spender.
*
* @param _ckToken CKToken instance to invoke
* @param _token ERC20 token to approve
* @param _spender The account allowed to spend the CKToken's balance
* @param _quantity The quantity of allowance to allow
*/
function invokeApprove(
ICKToken _ckToken,
address _token,
address _spender,
uint256 _quantity
)
internal
{
bytes memory callData = abi.encodeWithSignature("approve(address,uint256)", _spender, _quantity);
_ckToken.invoke(_token, 0, callData);
}
/**
* Instructs the CKToken to transfer the ERC20 token to a recipient.
*
* @param _ckToken CKToken instance to invoke
* @param _token ERC20 token to transfer
* @param _to The recipient account
* @param _quantity The quantity to transfer
*/
function invokeTransfer(
ICKToken _ckToken,
address _token,
address _to,
uint256 _quantity
)
internal
{
if (_quantity > 0) {
bytes memory callData = abi.encodeWithSignature("transfer(address,uint256)", _to, _quantity);
_ckToken.invoke(_token, 0, callData);
}
}
/**
* Instructs the CKToken to transfer the ERC20 token to a recipient.
* The new CKToken balance must equal the existing balance less the quantity transferred
*
* @param _ckToken CKToken instance to invoke
* @param _token ERC20 token to transfer
* @param _to The recipient account
* @param _quantity The quantity to transfer
*/
function strictInvokeTransfer(
ICKToken _ckToken,
address _token,
address _to,
uint256 _quantity
)
internal
{
if (_quantity > 0) {
// Retrieve current balance of token for the CKToken
uint256 existingBalance = IERC20(_token).balanceOf(address(_ckToken));
Invoke.invokeTransfer(_ckToken, _token, _to, _quantity);
// Get new balance of transferred token for CKToken
uint256 newBalance = IERC20(_token).balanceOf(address(_ckToken));
// Verify only the transfer quantity is subtracted
require(
newBalance == existingBalance.sub(_quantity),
"Invalid post transfer balance"
);
}
}
/**
* Instructs the CKToken to unwrap the passed quantity of WETH
*
* @param _ckToken CKToken instance to invoke
* @param _weth WETH address
* @param _quantity The quantity to unwrap
*/
function invokeUnwrapWETH(ICKToken _ckToken, address _weth, uint256 _quantity) internal {
bytes memory callData = abi.encodeWithSignature("withdraw(uint256)", _quantity);
_ckToken.invoke(_weth, 0, callData);
}
/**
* Instructs the CKToken to wrap the passed quantity of ETH
*
* @param _ckToken CKToken instance to invoke
* @param _weth WETH address
* @param _quantity The quantity to unwrap
*/
function invokeWrapWETH(ICKToken _ckToken, address _weth, uint256 _quantity) internal {
bytes memory callData = abi.encodeWithSignature("deposit()");
_ckToken.invoke(_weth, _quantity, callData);
}
}
// File @openzeppelin/contracts/math/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @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) {
// 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;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @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) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Returns the addition of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
// File contracts/lib/PreciseUnitMath.sol
/*
Copyright 2021 Cook Finance.
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.6.10;
/**
* @title PreciseUnitMath
* @author Cook Finance
*
* Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from
* dYdX's BaseMath library.
*
* CHANGELOG:
* - 9/21/20: Added safePower function
*/
library PreciseUnitMath {
using SafeMath for uint256;
using SignedSafeMath for int256;
// The number One in precise units.
uint256 constant internal PRECISE_UNIT = 10 ** 18;
int256 constant internal PRECISE_UNIT_INT = 10 ** 18;
// Max unsigned integer value
uint256 constant internal MAX_UINT_256 = type(uint256).max;
// Max and min signed integer value
int256 constant internal MAX_INT_256 = type(int256).max;
int256 constant internal MIN_INT_256 = type(int256).min;
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function preciseUnit() internal pure returns (uint256) {
return PRECISE_UNIT;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function preciseUnitInt() internal pure returns (int256) {
return PRECISE_UNIT_INT;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function maxUint256() internal pure returns (uint256) {
return MAX_UINT_256;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function maxInt256() internal pure returns (int256) {
return MAX_INT_256;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function minInt256() internal pure returns (int256) {
return MIN_INT_256;
}
/**
* @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand
* of a number with 18 decimals precision.
*/
function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mul(b).div(PRECISE_UNIT);
}
/**
* @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the
* significand of a number with 18 decimals precision.
*/
function preciseMul(int256 a, int256 b) internal pure returns (int256) {
return a.mul(b).div(PRECISE_UNIT_INT);
}
/**
* @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand
* of a number with 18 decimals precision.
*/
function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
return a.mul(b).sub(1).div(PRECISE_UNIT).add(1);
}
/**
* @dev Divides value a by value b (result is rounded down).
*/
function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mul(PRECISE_UNIT).div(b);
}
/**
* @dev Divides value a by value b (result is rounded towards 0).
*/
function preciseDiv(int256 a, int256 b) internal pure returns (int256) {
return a.mul(PRECISE_UNIT_INT).div(b);
}
/**
* @dev Divides value a by value b (result is rounded up or away from 0).
*/
function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "Cant divide by 0");
return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0;
}
/**
* @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0).
*/
function divDown(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "Cant divide by 0");
require(a != MIN_INT_256 || b != -1, "Invalid input");
int256 result = a.div(b);
if (a ^ b < 0 && a % b != 0) {
result -= 1;
}
return result;
}
/**
* @dev Multiplies value a by value b where rounding is towards the lesser number.
* (positive values are rounded towards zero and negative values are rounded away from 0).
*/
function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) {
return divDown(a.mul(b), PRECISE_UNIT_INT);
}
/**
* @dev Divides value a by value b where rounding is towards the lesser number.
* (positive values are rounded towards zero and negative values are rounded away from 0).
*/
function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) {
return divDown(a.mul(PRECISE_UNIT_INT), b);
}
/**
* @dev Performs the power on a specified value, reverts on overflow.
*/
function safePower(
uint256 a,
uint256 pow
)
internal
pure
returns (uint256)
{
require(a > 0, "Value must be positive");
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 Returns true if a =~ b within range, false otherwise.
*/
function approximatelyEquals(uint256 a, uint256 b, uint256 range) internal pure returns (bool) {
return a <= b.add(range) && a >= b.sub(range);
}
}
// File contracts/protocol/lib/Position.sol
/*
Copyright 2021 Cook Finance.
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.6.10;
/**
* @title Position
* @author Cook Finance
*
* Collection of helper functions for handling and updating CKToken Positions
*
* CHANGELOG:
* - Updated editExternalPosition to work when no external position is associated with module
*/
library Position {
using SafeCast for uint256;
using SafeMath for uint256;
using SafeCast for int256;
using SignedSafeMath for int256;
using PreciseUnitMath for uint256;
/* ============ Helper ============ */
/**
* Returns whether the CKToken has a default position for a given component (if the real unit is > 0)
*/
function hasDefaultPosition(ICKToken _ckToken, address _component) internal view returns(bool) {
return _ckToken.getDefaultPositionRealUnit(_component) > 0;
}
/**
* Returns whether the CKToken has an external position for a given component (if # of position modules is > 0)
*/
function hasExternalPosition(ICKToken _ckToken, address _component) internal view returns(bool) {
return _ckToken.getExternalPositionModules(_component).length > 0;
}
/**
* Returns whether the CKToken component default position real unit is greater than or equal to units passed in.
*/
function hasSufficientDefaultUnits(ICKToken _ckToken, address _component, uint256 _unit) internal view returns(bool) {
return _ckToken.getDefaultPositionRealUnit(_component) >= _unit.toInt256();
}
/**
* Returns whether the CKToken component external position is greater than or equal to the real units passed in.
*/
function hasSufficientExternalUnits(
ICKToken _ckToken,
address _component,
address _positionModule,
uint256 _unit
)
internal
view
returns(bool)
{
return _ckToken.getExternalPositionRealUnit(_component, _positionModule) >= _unit.toInt256();
}
/**
* If the position does not exist, create a new Position and add to the CKToken. If it already exists,
* then set the position units. If the new units is 0, remove the position. Handles adding/removing of
* components where needed (in light of potential external positions).
*
* @param _ckToken Address of CKToken being modified
* @param _component Address of the component
* @param _newUnit Quantity of Position units - must be >= 0
*/
function editDefaultPosition(ICKToken _ckToken, address _component, uint256 _newUnit) internal {
bool isPositionFound = hasDefaultPosition(_ckToken, _component);
if (!isPositionFound && _newUnit > 0) {
// If there is no Default Position and no External Modules, then component does not exist
if (!hasExternalPosition(_ckToken, _component)) {
_ckToken.addComponent(_component);
}
} else if (isPositionFound && _newUnit == 0) {
// If there is a Default Position and no external positions, remove the component
if (!hasExternalPosition(_ckToken, _component)) {
_ckToken.removeComponent(_component);
}
}
_ckToken.editDefaultPositionUnit(_component, _newUnit.toInt256());
}
/**
* Update an external position and remove and external positions or components if necessary. The logic flows as follows:
* 1) If component is not already added then add component and external position.
* 2) If component is added but no existing external position using the passed module exists then add the external position.
* 3) If the existing position is being added to then just update the unit and data
* 4) If the position is being closed and no other external positions or default positions are associated with the component
* then untrack the component and remove external position.
* 5) If the position is being closed and other existing positions still exist for the component then just remove the
* external position.
*
* @param _ckToken CKToken being updated
* @param _component Component position being updated
* @param _module Module external position is associated with
* @param _newUnit Position units of new external position
* @param _data Arbitrary data associated with the position
*/
function editExternalPosition(
ICKToken _ckToken,
address _component,
address _module,
int256 _newUnit,
bytes memory _data
)
internal
{
if (_newUnit != 0) {
if (!_ckToken.isComponent(_component)) {
_ckToken.addComponent(_component);
_ckToken.addExternalPositionModule(_component, _module);
} else if (!_ckToken.isExternalPositionModule(_component, _module)) {
_ckToken.addExternalPositionModule(_component, _module);
}
_ckToken.editExternalPositionUnit(_component, _module, _newUnit);
_ckToken.editExternalPositionData(_component, _module, _data);
} else {
require(_data.length == 0, "Passed data must be null");
// If no default or external position remaining then remove component from components array
if (_ckToken.getExternalPositionRealUnit(_component, _module) != 0) {
address[] memory positionModules = _ckToken.getExternalPositionModules(_component);
if (_ckToken.getDefaultPositionRealUnit(_component) == 0 && positionModules.length == 1) {
require(positionModules[0] == _module, "External positions must be 0 to remove component");
_ckToken.removeComponent(_component);
}
_ckToken.removeExternalPositionModule(_component, _module);
}
}
}
/**
* Get total notional amount of Default position
*
* @param _ckTokenSupply Supply of CKToken in precise units (10^18)
* @param _positionUnit Quantity of Position units
*
* @return Total notional amount of units
*/
function getDefaultTotalNotional(uint256 _ckTokenSupply, uint256 _positionUnit) internal pure returns (uint256) {
return _ckTokenSupply.preciseMul(_positionUnit);
}
/**
* Get position unit from total notional amount
*
* @param _ckTokenSupply Supply of CKToken in precise units (10^18)
* @param _totalNotional Total notional amount of component prior to
* @return Default position unit
*/
function getDefaultPositionUnit(uint256 _ckTokenSupply, uint256 _totalNotional) internal pure returns (uint256) {
return _totalNotional.preciseDiv(_ckTokenSupply);
}
/**
* Get the total tracked balance - total supply * position unit
*
* @param _ckToken Address of the CKToken
* @param _component Address of the component
* @return Notional tracked balance
*/
function getDefaultTrackedBalance(ICKToken _ckToken, address _component) internal view returns(uint256) {
int256 positionUnit = _ckToken.getDefaultPositionRealUnit(_component);
return _ckToken.totalSupply().preciseMul(positionUnit.toUint256());
}
/**
* Calculates the new default position unit and performs the edit with the new unit
*
* @param _ckToken Address of the CKToken
* @param _component Address of the component
* @param _ckTotalSupply Current CKToken supply
* @param _componentPreviousBalance Pre-action component balance
* @return Current component balance
* @return Previous position unit
* @return New position unit
*/
function calculateAndEditDefaultPosition(
ICKToken _ckToken,
address _component,
uint256 _ckTotalSupply,
uint256 _componentPreviousBalance
)
internal
returns(uint256, uint256, uint256)
{
uint256 currentBalance = IERC20(_component).balanceOf(address(_ckToken));
uint256 positionUnit = _ckToken.getDefaultPositionRealUnit(_component).toUint256();
uint256 newTokenUnit;
if (currentBalance > 0) {
newTokenUnit = calculateDefaultEditPositionUnit(
_ckTotalSupply,
_componentPreviousBalance,
currentBalance,
positionUnit
);
} else {
newTokenUnit = 0;
}
editDefaultPosition(_ckToken, _component, newTokenUnit);
return (currentBalance, positionUnit, newTokenUnit);
}
/**
* Calculate the new position unit given total notional values pre and post executing an action that changes CKToken state
* The intention is to make updates to the units without accidentally picking up airdropped assets as well.
*
* @param _ckTokenSupply Supply of CKToken in precise units (10^18)
* @param _preTotalNotional Total notional amount of component prior to executing action
* @param _postTotalNotional Total notional amount of component after the executing action
* @param _prePositionUnit Position unit of CKToken prior to executing action
* @return New position unit
*/
function calculateDefaultEditPositionUnit(
uint256 _ckTokenSupply,
uint256 _preTotalNotional,
uint256 _postTotalNotional,
uint256 _prePositionUnit
)
internal
pure
returns (uint256)
{
// If pre action total notional amount is greater then subtract post action total notional and calculate new position units
uint256 airdroppedAmount = _preTotalNotional.sub(_prePositionUnit.preciseMul(_ckTokenSupply));
return _postTotalNotional.sub(airdroppedAmount).preciseDiv(_ckTokenSupply);
}
}
// File contracts/interfaces/IIntegrationRegistry.sol
/*
Copyright 2021 Cook Finance.
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.6.10;
interface IIntegrationRegistry {
function addIntegration(address _module, string memory _id, address _wrapper) external;
function getIntegrationAdapter(address _module, string memory _id) external view returns(address);
function getIntegrationAdapterWithHash(address _module, bytes32 _id) external view returns(address);
function isValidIntegration(address _module, string memory _id) external view returns(bool);
}
// File contracts/interfaces/ICKValuer.sol
/*
Copyright 2021 Cook Finance.
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.6.10;
interface ICKValuer {
function calculateCKTokenValuation(ICKToken _ckToken, address _quoteAsset) external view returns (uint256);
}
// File contracts/protocol/lib/ResourceIdentifier.sol
/*
Copyright 2021 Cook Finance.
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.6.10;
/**
* @title ResourceIdentifier
* @author Cook Finance
*
* A collection of utility functions to fetch information related to Resource contracts in the system
*/
library ResourceIdentifier {
// IntegrationRegistry will always be resource ID 0 in the system
uint256 constant internal INTEGRATION_REGISTRY_RESOURCE_ID = 0;
// PriceOracle will always be resource ID 1 in the system
uint256 constant internal PRICE_ORACLE_RESOURCE_ID = 1;
// CKValuer resource will always be resource ID 2 in the system
uint256 constant internal CK_VALUER_RESOURCE_ID = 2;
/* ============ Internal ============ */
/**
* Gets the instance of integration registry stored on Controller. Note: IntegrationRegistry is stored as index 0 on
* the Controller
*/
function getIntegrationRegistry(IController _controller) internal view returns (IIntegrationRegistry) {
return IIntegrationRegistry(_controller.resourceId(INTEGRATION_REGISTRY_RESOURCE_ID));
}
/**
* Gets instance of price oracle on Controller. Note: PriceOracle is stored as index 1 on the Controller
*/
function getPriceOracle(IController _controller) internal view returns (IPriceOracle) {
return IPriceOracle(_controller.resourceId(PRICE_ORACLE_RESOURCE_ID));
}
/**
* Gets the instance of CK valuer on Controller. Note: CKValuer is stored as index 2 on the Controller
*/
function getCKValuer(IController _controller) internal view returns (ICKValuer) {
return ICKValuer(_controller.resourceId(CK_VALUER_RESOURCE_ID));
}
}
// File contracts/protocol/lib/ModuleBase.sol
/*
Copyright 2021 Cook Finance.
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.6.10;
/**
* @title ModuleBase
* @author Cook Finance
*
* Abstract class that houses common Module-related state and functions.
*/
abstract contract ModuleBase is IModule {
using AddressArrayUtils for address[];
using Invoke for ICKToken;
using Position for ICKToken;
using PreciseUnitMath for uint256;
using ResourceIdentifier for IController;
using SafeCast for int256;
using SafeCast for uint256;
using SafeMath for uint256;
using SignedSafeMath for int256;
/* ============ State Variables ============ */
// Address of the controller
IController public controller;
/* ============ Modifiers ============ */
modifier onlyManagerAndValidCK(ICKToken _ckToken) {
_validateOnlyManagerAndValidCK(_ckToken);
_;
}
modifier onlyCKManager(ICKToken _ckToken, address _caller) {
_validateOnlyCKManager(_ckToken, _caller);
_;
}
modifier onlyValidAndInitializedCK(ICKToken _ckToken) {
_validateOnlyValidAndInitializedCK(_ckToken);
_;
}
/**
* Throws if the sender is not a CKToken's module or module not enabled
*/
modifier onlyModule(ICKToken _ckToken) {
_validateOnlyModule(_ckToken);
_;
}
/**
* Utilized during module initializations to check that the module is in pending state
* and that the CKToken is valid
*/
modifier onlyValidAndPendingCK(ICKToken _ckToken) {
_validateOnlyValidAndPendingCK(_ckToken);
_;
}
/* ============ Constructor ============ */
/**
* Set state variables and map asset pairs to their oracles
*
* @param _controller Address of controller contract
*/
constructor(IController _controller) public {
controller = _controller;
}
/* ============ Internal Functions ============ */
/**
* Transfers tokens from an address (that has set allowance on the module).
*
* @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(IERC20 _token, address _from, address _to, uint256 _quantity) internal {
ExplicitERC20.transferFrom(_token, _from, _to, _quantity);
}
/**
* Gets the integration for the module with the passed in name. Validates that the address is not empty
*/
function getAndValidateAdapter(string memory _integrationName) internal view returns(address) {
bytes32 integrationHash = getNameHash(_integrationName);
return getAndValidateAdapterWithHash(integrationHash);
}
/**
* Gets the integration for the module with the passed in hash. Validates that the address is not empty
*/
function getAndValidateAdapterWithHash(bytes32 _integrationHash) internal view returns(address) {
address adapter = controller.getIntegrationRegistry().getIntegrationAdapterWithHash(
address(this),
_integrationHash
);
require(adapter != address(0), "Must be valid adapter");
return adapter;
}
/**
* Gets the total fee for this module of the passed in index (fee % * quantity)
*/
function getModuleFee(uint256 _feeIndex, uint256 _quantity) internal view returns(uint256) {
uint256 feePercentage = controller.getModuleFee(address(this), _feeIndex);
return _quantity.preciseMul(feePercentage);
}
/**
* Pays the _feeQuantity from the _ckToken denominated in _token to the protocol fee recipient
*/
function payProtocolFeeFromCKToken(ICKToken _ckToken, address _token, uint256 _feeQuantity) internal {
if (_feeQuantity > 0) {
_ckToken.strictInvokeTransfer(_token, controller.feeRecipient(), _feeQuantity);
}
}
/**
* Returns true if the module is in process of initialization on the CKToken
*/
function isCKPendingInitialization(ICKToken _ckToken) internal view returns(bool) {
return _ckToken.isPendingModule(address(this));
}
/**
* Returns true if the address is the CKToken's manager
*/
function isCKManager(ICKToken _ckToken, address _toCheck) internal view returns(bool) {
return _ckToken.manager() == _toCheck;
}
/**
* Returns true if CKToken must be enabled on the controller
* and module is registered on the CKToken
*/
function isCKValidAndInitialized(ICKToken _ckToken) internal view returns(bool) {
return controller.isCK(address(_ckToken)) &&
_ckToken.isInitializedModule(address(this));
}
/**
* Hashes the string and returns a bytes32 value
*/
function getNameHash(string memory _name) internal pure returns(bytes32) {
return keccak256(bytes(_name));
}
/* ============== Modifier Helpers ===============
* Internal functions used to reduce bytecode size
*/
/**
* Caller must CKToken manager and CKToken must be valid and initialized
*/
function _validateOnlyManagerAndValidCK(ICKToken _ckToken) internal view {
require(isCKManager(_ckToken, msg.sender), "Must be the CKToken manager");
require(isCKValidAndInitialized(_ckToken), "Must be a valid and initialized CKToken");
}
/**
* Caller must CKToken manager
*/
function _validateOnlyCKManager(ICKToken _ckToken, address _caller) internal view {
require(isCKManager(_ckToken, _caller), "Must be the CKToken manager");
}
/**
* CKToken must be valid and initialized
*/
function _validateOnlyValidAndInitializedCK(ICKToken _ckToken) internal view {
require(isCKValidAndInitialized(_ckToken), "Must be a valid and initialized CKToken");
}
/**
* Caller must be initialized module and module must be enabled on the controller
*/
function _validateOnlyModule(ICKToken _ckToken) internal view {
require(
_ckToken.moduleStates(msg.sender) == ICKToken.ModuleState.INITIALIZED,
"Only the module can call"
);
require(
controller.isModule(msg.sender),
"Module must be enabled on controller"
);
}
/**
* CKToken must be in a pending state and module must be in pending state
*/
function _validateOnlyValidAndPendingCK(ICKToken _ckToken) internal view {
require(controller.isCK(address(_ckToken)), "Must be controller-enabled CKToken");
require(isCKPendingInitialization(_ckToken), "Must be pending initialization");
}
}
// File contracts/protocol/modules/BatchIssuanceModule.sol
/*
Copyright 2021 Cook Finance.
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.6.10;
/**
* @title BatchIssuanceModule
* @author Cook Finance
*
* Module that enables batch issuance and redemption functionality on a CKToken, for the purpose of gas saving.
* This is a module that is required to bring the totalSupply of a CK above 0.
*/
contract BatchIssuanceModule is ModuleBase, ReentrancyGuard {
using PreciseUnitMath for uint256;
using SafeMath for uint256;
using Math for uint256;
using SafeCast for int256;
using SafeERC20 for IWETH;
using SafeERC20 for IERC20;
using Address for address;
/* ============ Events ============ */
event CKTokenBatchIssued(
ICKToken indexed _ckToken,
uint256 _inputUsed,
uint256 _outputCK,
uint256 _numberOfRounds
);
event ManagerFeeEdited(ICKToken indexed _ckToken, uint256 _newManagerFee, uint256 _index);
event FeeRecipientEdited(ICKToken indexed _ckToken, address _feeRecipient);
event AssetExchangeUpdated(ICKToken indexed _ckToken, address _component, string _newExchangeName);
event DepositAllowanceUpdated(ICKToken indexed _ckToken, bool _allowDeposit);
event RoundInputCapsUpdated(ICKToken indexed _ckToken, uint256 roundInputCap);
event Deposit(address indexed _to, uint256 _amount);
event WithdrawCKToken(
ICKToken indexed _ckToken,
address indexed _from,
address indexed _to,
uint256 _inputAmount,
uint256 _outputAmount
);
/* ============ Structs ============ */
struct BatchIssuanceSetting {
address feeRecipient; // Manager fee recipient
uint256[2] managerFees; // Manager fees. 0 index is issue and 1 index is redeem fee (0.01% = 1e14, 1% = 1e16)
uint256 maxManagerFee; // Maximum fee manager is allowed to set for issue and redeem
uint256 minCKTokenSupply; // Minimum CKToken supply required for issuance and redemption
// to prevent dramatic inflationary changes to the CKToken's position multiplier
bool allowDeposit; // to pause users from depositting into batchIssuance module
}
struct ActionInfo {
uint256 preFeeReserveQuantity; // Reserve value before fees; During issuance, represents raw quantity
uint256 totalFeePercentage; // Total protocol fees (direct + manager revenue share)
uint256 protocolFees; // Total protocol fees (direct + manager revenue share)
uint256 managerFee; // Total manager fee paid in reserve asset
uint256 netFlowQuantity; // When issuing, quantity of reserve asset sent to CKToken
uint256 ckTokenQuantity; // When issuing, quantity of CKTokens minted to mintee
uint256 previousCKTokenSupply; // CKToken supply prior to issue/redeem action
uint256 newCKTokenSupply; // CKToken supply after issue/redeem action
}
struct TradeExecutionParams {
string exchangeName; // Exchange adapter name
bytes exchangeData; // Arbitrary data that can be used to encode exchange specific
// settings (fee tier) or features (multi-hop)
}
struct TradeInfo {
IIndexExchangeAdapter exchangeAdapter; // Instance of Exchange Adapter
address receiveToken; // Address of token being bought
uint256 sendQuantityMax; // Max amount of tokens to sent to the exchange
uint256 receiveQuantity; // Amount of tokens receiving
bytes exchangeData; // Arbitrary data for executing trade on given exchange
}
struct Round {
uint256 totalDeposited; // Total WETH deposited in a round
mapping(address => uint256) deposits; // Mapping address to uint256, shows which address deposited how much WETH
uint256 totalBakedInput; // Total WETH used for issuance in a round
uint256 totalOutput; // Total CK amount issued in a round
}
/* ============ Constants ============ */
// 0 index stores the manager fee in managerFees array, percentage charged on issue (denominated in reserve asset)
uint256 constant internal MANAGER_ISSUE_FEE_INDEX = 0;
// 0 index stores the manager revenue share protocol fee % on the controller, charged in the issuance function
uint256 constant internal PROTOCOL_ISSUE_MANAGER_REVENUE_SHARE_FEE_INDEX = 0;
// 2 index stores the direct protocol fee % on the controller, charged in the issuance function
uint256 constant internal PROTOCOL_ISSUE_DIRECT_FEE_INDEX = 2;
/* ============ State Variables ============ */
IWETH public immutable weth; // Wrapped ETH address
IBasicIssuanceModule public basicIssuanceModule; // Basic Issuance Module
// Mapping of CKToken to Batch issuance setting
mapping(ICKToken => BatchIssuanceSetting) private batchIssuanceSettings;
// Mapping of CKToken to (component to execution params)
mapping(ICKToken => mapping(IERC20 => TradeExecutionParams)) private tradeExecutionInfo;
// Mapping of CKToken to Input amount size per round
mapping(ICKToken => uint256) private roundInputCaps;
// Mapping of CKToken to Array of rounds
mapping(ICKToken => Round[]) private rounds;
// Mapping of CKToken to User round, a user can have multiple rounds
mapping(ICKToken => mapping(address => uint256[])) private userRounds;
/* ============ Constructor ============ */
/**
* Set state controller state variable
*
* @param _controller Address of controller contract
* @param _weth Address of WETH
* @param _basicIssuanceModule Instance of the basic issuance module
*/
constructor(
IController _controller,
IWETH _weth,
IBasicIssuanceModule _basicIssuanceModule
) public ModuleBase(_controller) {
weth = _weth;
// set basic issuance module
basicIssuanceModule = _basicIssuanceModule;
}
/* ============ External Functions ============ */
/**
* Initializes this module to the CKToken with issuance settings and round input cap(limit)
*
* @param _ckToken Instance of the CKToken to issue
* @param _batchIssuanceSetting BatchIssuanceSetting struct define parameters
* @param _roundInputCap Maximum input amount per round
*/
function initialize(
ICKToken _ckToken,
BatchIssuanceSetting memory _batchIssuanceSetting,
uint256 _roundInputCap
)
external
onlyCKManager(_ckToken, msg.sender)
onlyValidAndPendingCK(_ckToken)
{
require(_ckToken.isInitializedModule(address(basicIssuanceModule)), "BasicIssuanceModule must be initialized");
require(_batchIssuanceSetting.maxManagerFee < PreciseUnitMath.preciseUnit(), "Max manager fee must be less than 100%");
require(_batchIssuanceSetting.managerFees[0] <= _batchIssuanceSetting.maxManagerFee, "Manager issue fee must be less than max");
require(_batchIssuanceSetting.managerFees[1] <= _batchIssuanceSetting.maxManagerFee, "Manager redeem fee must be less than max");
require(_batchIssuanceSetting.feeRecipient != address(0), "Fee Recipient must be non-zero address.");
require(_batchIssuanceSetting.minCKTokenSupply > 0, "Min CKToken supply must be greater than 0");
// create first empty round
rounds[_ckToken].push();
// set round input limit
roundInputCaps[_ckToken] = _roundInputCap;
// set batch issuance setting
batchIssuanceSettings[_ckToken] = _batchIssuanceSetting;
// initialize module for the CKToken
_ckToken.initializeModule();
}
/**
* CK MANAGER ONLY. Edit manager fee
*
* @param _ckToken Instance of the CKToken
* @param _managerFeePercentage Manager fee percentage in 10e16 (e.g. 10e16 = 1%)
* @param _managerFeeIndex Manager fee index. 0 index is issue fee, 1 index is redeem fee
*/
function editManagerFee(
ICKToken _ckToken,
uint256 _managerFeePercentage,
uint256 _managerFeeIndex
)
external
onlyManagerAndValidCK(_ckToken)
{
require(_managerFeePercentage <= batchIssuanceSettings[_ckToken].maxManagerFee, "Manager fee must be less than maximum allowed");
batchIssuanceSettings[_ckToken].managerFees[_managerFeeIndex] = _managerFeePercentage;
emit ManagerFeeEdited(_ckToken, _managerFeePercentage, _managerFeeIndex);
}
/**
* CK MANAGER ONLY. Edit the manager fee recipient
*
* @param _ckToken Instance of the CKToken
* @param _managerFeeRecipient Manager fee recipient
*/
function editFeeRecipient(
ICKToken _ckToken,
address _managerFeeRecipient
) external onlyManagerAndValidCK(_ckToken) {
require(_managerFeeRecipient != address(0), "Fee recipient must not be 0 address");
batchIssuanceSettings[_ckToken].feeRecipient = _managerFeeRecipient;
emit FeeRecipientEdited(_ckToken, _managerFeeRecipient);
}
function setDepositAllowance(ICKToken _ckToken, bool _allowDeposit) external onlyManagerAndValidCK(_ckToken) {
batchIssuanceSettings[_ckToken].allowDeposit = _allowDeposit;
emit DepositAllowanceUpdated(_ckToken, _allowDeposit);
}
function editRoundInputCaps(ICKToken _ckToken, uint256 _roundInputCap) external onlyManagerAndValidCK(_ckToken) {
roundInputCaps[_ckToken] = _roundInputCap;
emit RoundInputCapsUpdated(_ckToken, _roundInputCap);
}
/**
* CK MANAGER ONLY: Set exchanges for underlying components of the CKToken. Can be called at anytime.
*
* @param _ckToken Instance of the CKToken
* @param _components Array of components
* @param _exchangeNames Array of exchange names mapping to correct component
*/
function setExchanges(
ICKToken _ckToken,
address[] memory _components,
string[] memory _exchangeNames
)
external
onlyManagerAndValidCK(_ckToken)
{
_components.validatePairsWithArray(_exchangeNames);
for (uint256 i = 0; i < _components.length; i++) {
if (_components[i] != address(weth)) {
require(
controller.getIntegrationRegistry().isValidIntegration(address(this), _exchangeNames[i]),
"Unrecognized exchange name"
);
tradeExecutionInfo[_ckToken][IERC20(_components[i])].exchangeName = _exchangeNames[i];
emit AssetExchangeUpdated(_ckToken, _components[i], _exchangeNames[i]);
}
}
}
/**
* Mints the appropriate % of Net Asset Value of the CKToken from the deposited WETH in the rounds.
* Fee(protocol fee + manager shared fee + manager fee in the module) will be used as slipage to trade on DEXs.
* The exact amount protocol fee will be deliver to the protocol. Only remaining WETH will be paid to the manager as a fee.
*
* @param _ckToken Instance of the CKToken
* @param _rounds Array of round indexes
*/
function batchIssue(
ICKToken _ckToken, uint256[] memory _rounds
)
external
nonReentrant
onlyValidAndInitializedCK(_ckToken)
{
uint256 maxInputAmount;
Round[] storage roundsPerCK = rounds[_ckToken];
// Get max input amount
for(uint256 i = 0; i < _rounds.length; i ++) {
// Prevent round from being baked twice
if(i != 0) {
require(_rounds[i] > _rounds[i - 1], "Rounds out of order");
}
Round storage round = roundsPerCK[_rounds[i]];
maxInputAmount = maxInputAmount.add(round.totalDeposited.sub(round.totalBakedInput));
}
require(maxInputAmount > 0, "Quantity must be > 0");
ActionInfo memory issueInfo = _createIssuanceInfo(_ckToken, address(weth), maxInputAmount);
_validateIssuanceInfo(_ckToken, issueInfo);
uint256 inputUsed = 0;
uint256 outputAmount = issueInfo.ckTokenQuantity;
// To issue ckTokenQuantity amount of CKs, swap the required underlying components amount
(
address[] memory components,
uint256[] memory componentQuantities
) = basicIssuanceModule.getRequiredComponentUnitsForIssue(_ckToken, outputAmount);
for (uint256 i = 0; i < components.length; i++) {
IERC20 component_ = IERC20(components[i]);
uint256 quantity_ = componentQuantities[i];
if (address(component_) != address(weth)) {
TradeInfo memory tradeInfo = _createTradeInfo(
_ckToken,
IERC20(component_),
quantity_,
issueInfo.totalFeePercentage
);
uint256 usedAmountForTrade = _executeTrade(tradeInfo);
inputUsed = inputUsed.add(usedAmountForTrade);
} else {
inputUsed = inputUsed.add(quantity_);
}
// approve every component for basic issuance module
if (component_.allowance(address(this), address(basicIssuanceModule)) < quantity_) {
component_.safeIncreaseAllowance(address(basicIssuanceModule), quantity_);
}
}
// Mint the CKToken
basicIssuanceModule.issue(_ckToken, outputAmount, address(this));
uint256 inputUsedRemaining = maxInputAmount;
for(uint256 i = 0; i < _rounds.length; i ++) {
Round storage round = roundsPerCK[_rounds[i]];
uint256 roundTotalBaked = round.totalBakedInput;
uint256 roundTotalDeposited = round.totalDeposited;
uint256 roundInputBaked = (roundTotalDeposited.sub(roundTotalBaked)).min(inputUsedRemaining);
// Skip round if it is already baked
if(roundInputBaked == 0) {
continue;
}
uint256 roundOutputBaked = outputAmount.mul(roundInputBaked).div(maxInputAmount);
round.totalBakedInput = roundTotalBaked.add(roundInputBaked);
inputUsedRemaining = inputUsedRemaining.sub(roundInputBaked);
round.totalOutput = round.totalOutput.add(roundOutputBaked);
// Sanity check for round
require(round.totalBakedInput <= round.totalDeposited, "Round input sanity check failed");
}
// Sanity check
uint256 inputUsedWithProtocolFee = inputUsed.add(issueInfo.protocolFees);
require(inputUsedWithProtocolFee <= maxInputAmount, "Max input sanity check failed");
// turn remaining amount into manager fee
issueInfo.managerFee = maxInputAmount.sub(inputUsedWithProtocolFee);
_transferFees(_ckToken, issueInfo);
emit CKTokenBatchIssued(_ckToken, maxInputAmount, outputAmount, _rounds.length);
}
/**
* Wrap ETH and then deposit
*
* @param _ckToken Instance of the CKToken
*/
function depositEth(ICKToken _ckToken) external payable onlyValidAndInitializedCK(_ckToken) {
weth.deposit{ value: msg.value }();
_depositTo(_ckToken, msg.value, msg.sender);
}
/**
* Deposit WETH
*
* @param _ckToken Instance of the CKToken
* @param _amount Amount of WETH
*/
function deposit(ICKToken _ckToken, uint256 _amount) external onlyValidAndInitializedCK(_ckToken) {
weth.safeTransferFrom(msg.sender, address(this), _amount);
_depositTo(_ckToken, _amount, msg.sender);
}
/**
* Withdraw CKToken within the number of rounds limit
*
* @param _ckToken Instance of the CKToken
* @param _roundsLimit Number of rounds limit
*/
function withdrawCKToken(ICKToken _ckToken, uint256 _roundsLimit) external onlyValidAndInitializedCK(_ckToken) {
withdrawCKTokenTo(_ckToken, msg.sender, _roundsLimit);
}
/**
* Withdraw CKToken within the number of rounds limit, to a specific address
*
* @param _ckToken Instance of the CKToken
* @param _to Address to withdraw to
* @param _roundsLimit Number of rounds limit
*/
function withdrawCKTokenTo(
ICKToken _ckToken,
address _to,
uint256 _roundsLimit
) public nonReentrant onlyValidAndInitializedCK(_ckToken) {
uint256 inputAmount;
uint256 outputAmount;
mapping(address => uint256[]) storage userRoundsPerCK = userRounds[_ckToken];
Round[] storage roundsPerCK = rounds[_ckToken];
uint256 userRoundsLength = userRoundsPerCK[msg.sender].length;
uint256 numRounds = userRoundsLength.min(_roundsLimit);
for(uint256 i = 0; i < numRounds; i ++) {
// start at end of array for efficient popping of elements
uint256 userRoundIndex = userRoundsLength.sub(i).sub(1);
uint256 roundIndex = userRoundsPerCK[msg.sender][userRoundIndex];
Round storage round = roundsPerCK[roundIndex];
// amount of input of user baked
uint256 bakedInput = round.deposits[msg.sender].mul(round.totalBakedInput).div(round.totalDeposited);
// amount of output the user is entitled to
uint256 userRoundOutput;
if(bakedInput == 0) {
userRoundOutput = 0;
} else {
userRoundOutput = round.totalOutput.mul(bakedInput).div(round.totalBakedInput);
}
// unbaked input
uint256 unspentInput = round.deposits[msg.sender].sub(bakedInput);
inputAmount = inputAmount.add(unspentInput);
//amount of output the user is entitled to
outputAmount = outputAmount.add(userRoundOutput);
round.totalDeposited = round.totalDeposited.sub(round.deposits[msg.sender]);
round.deposits[msg.sender] = 0;
round.totalBakedInput = round.totalBakedInput.sub(bakedInput);
round.totalOutput = round.totalOutput.sub(userRoundOutput);
// pop of user round
userRoundsPerCK[msg.sender].pop();
}
if(inputAmount != 0) {
// handle rounding issues due to integer division inaccuracies
inputAmount = inputAmount.min(weth.balanceOf(address(this)));
weth.safeTransfer(_to, inputAmount);
}
if(outputAmount != 0) {
// handle rounding issues due to integer division inaccuracies
outputAmount = outputAmount.min(_ckToken.balanceOf(address(this)));
_ckToken.transfer(_to, outputAmount);
}
emit WithdrawCKToken(_ckToken, msg.sender, _to, inputAmount, outputAmount);
}
/**
* Removes this module from the CKToken, via call by the CKToken.
*/
function removeModule() external override {
ICKToken ckToken_ = ICKToken(msg.sender);
// delete tradeExecutionInfo
address[] memory components = ckToken_.getComponents();
for (uint256 i = 0; i < components.length; i++) {
delete tradeExecutionInfo[ckToken_][IERC20(components[i])];
}
delete batchIssuanceSettings[ckToken_];
delete roundInputCaps[ckToken_];
delete rounds[ckToken_];
// delete userRounds[ckToken_];
}
/* ============ External Getter Functions ============ */
/**
* Get current round index
*
* @param _ckToken Instance of the CKToken
*/
function getRoundInputCap(ICKToken _ckToken) public view returns(uint256) {
return roundInputCaps[_ckToken];
}
/**
* Get current round index
*
* @param _ckToken Instance of the CKToken
*/
function getCurrentRound(ICKToken _ckToken) public view returns(uint256) {
return rounds[_ckToken].length.sub(1);
}
/**
* Get ETH amount deposited in current round
*
* @param _ckToken Instance of the CKToken
*/
function getCurrentRoundDeposited(ICKToken _ckToken) public view returns(uint256) {
uint256 currentRound = rounds[_ckToken].length.sub(1);
return rounds[_ckToken][currentRound].totalDeposited;
}
/**
* Get un-baked round indexes
*
* @param _ckToken Instance of the CKToken
*/
function getRoundsToBake(ICKToken _ckToken, uint256 _start) external view returns(uint256[] memory) {
uint256 count = 0;
Round[] storage roundsPerCK = rounds[_ckToken];
for(uint256 i = _start; i < roundsPerCK.length; i ++) {
Round storage round = roundsPerCK[i];
if (round.totalDeposited.sub(round.totalBakedInput) > 0) {
count ++;
}
}
uint256[] memory roundsToBake = new uint256[](count);
uint256 focus = 0;
for(uint256 i = _start; i < roundsPerCK.length; i ++) {
Round storage round = roundsPerCK[i];
if (round.totalDeposited.sub(round.totalBakedInput) > 0) {
roundsToBake[focus] = i;
focus ++;
}
}
return roundsToBake;
}
/**
* Get round input of an address(user)
*
* @param _ckToken Instance of the CKToken
* @param _round index of the round
* @param _of address of the user
*/
function roundInputBalanceOf(ICKToken _ckToken, uint256 _round, address _of) public view returns(uint256) {
Round storage round = rounds[_ckToken][_round];
// if there are zero deposits the input balance of `_of` would be zero too
if(round.totalDeposited == 0) {
return 0;
}
uint256 bakedInput = round.deposits[_of].mul(round.totalBakedInput).div(round.totalDeposited);
return round.deposits[_of].sub(bakedInput);
}
/**
* Get total input of an address(user)
*
* @param _ckToken Instance of the CKToken
* @param _of address of the user
*/
function inputBalanceOf(ICKToken _ckToken, address _of) public view returns(uint256) {
mapping(address => uint256[]) storage userRoundsPerCK = userRounds[_ckToken];
uint256 roundsCount = userRoundsPerCK[_of].length;
uint256 balance;
for(uint256 i = 0; i < roundsCount; i ++) {
balance = balance.add(roundInputBalanceOf(_ckToken, userRoundsPerCK[_of][i], _of));
}
return balance;
}
/**
* Get round output of an address(user)
*
* @param _ckToken Instance of the CKToken
* @param _round index of the round
* @param _of address of the user
*/
function roundOutputBalanceOf(ICKToken _ckToken, uint256 _round, address _of) public view returns(uint256) {
Round storage round = rounds[_ckToken][_round];
if(round.totalBakedInput == 0) {
return 0;
}
// amount of input of user baked
uint256 bakedInput = round.deposits[_of].mul(round.totalBakedInput).div(round.totalDeposited);
// amount of output the user is entitled to
uint256 userRoundOutput = round.totalOutput.mul(bakedInput).div(round.totalBakedInput);
return userRoundOutput;
}
/**
* Get total output of an address(user)
*
* @param _ckToken Instance of the CKToken
* @param _of address of the user
*/
function outputBalanceOf(ICKToken _ckToken, address _of) external view returns(uint256) {
mapping(address => uint256[]) storage userRoundsPerCK = userRounds[_ckToken];
uint256 roundsCount = userRoundsPerCK[_of].length;
uint256 balance;
for(uint256 i = 0; i < roundsCount; i ++) {
balance = balance.add(roundOutputBalanceOf(_ckToken, userRoundsPerCK[_of][i], _of));
}
return balance;
}
/**
* Get user's round count
*
* @param _ckToken Instance of the CKToken
* @param _user address of the user
*/
function getUserRoundsCount(ICKToken _ckToken, address _user) external view returns(uint256) {
return userRounds[_ckToken][_user].length;
}
/**
* Get user round number
*
* @param _ckToken Instance of the CKToken
* @param _user address of the user
* @param _index index in the round array
*/
function getUserRound(ICKToken _ckToken, address _user, uint256 _index) external view returns(uint256) {
return userRounds[_ckToken][_user][_index];
}
/**
* Get total round count
*
* @param _ckToken Instance of the CKToken
*/
function getRoundsCount(ICKToken _ckToken) external view returns(uint256) {
return rounds[_ckToken].length;
}
/**
* Get manager fee by index
*
* @param _ckToken Instance of the CKToken
* @param _managerFeeIndex Manager fee index
*/
function getManagerFee(ICKToken _ckToken, uint256 _managerFeeIndex) external view returns (uint256) {
return batchIssuanceSettings[_ckToken].managerFees[_managerFeeIndex];
}
/**
* Get batch issuance setting for a CK
*
* @param _ckToken Instance of the CKToken
*/
function getBatchIssuanceSetting(ICKToken _ckToken) external view returns (BatchIssuanceSetting memory) {
return batchIssuanceSettings[_ckToken];
}
/**
* Get tradeExecutionParam for a component of a CK
*
* @param _ckToken Instance of the CKToken
* @param _component ERC20 instance of the component
*/
function getTradeExecutionParam(
ICKToken _ckToken,
IERC20 _component
) external view returns (TradeExecutionParams memory) {
return tradeExecutionInfo[_ckToken][_component];
}
/**
* Get bake round for a CK
*
* @param _ckToken Instance of the CKToken
* @param _index index number of a round
*/
function getRound(ICKToken _ckToken, uint256 _index) external view returns (uint256, uint256, uint256) {
Round[] storage roundsPerCK = rounds[_ckToken];
Round memory round = roundsPerCK[_index];
return (round.totalDeposited, round.totalBakedInput, round.totalOutput);
}
/* ============ Internal Functions ============ */
/**
* Deposit by user by round
*
* @param _ckToken Instance of the CKToken
* @param _amount Amount of WETH
* @param _to Address of depositor
*/
function _depositTo(ICKToken _ckToken, uint256 _amount, address _to) internal {
// if amount is zero return early
if(_amount == 0) {
return;
}
require(batchIssuanceSettings[_ckToken].allowDeposit, "not allowed to deposit");
Round[] storage roundsPerCK = rounds[_ckToken];
uint256 currentRound = getCurrentRound(_ckToken);
uint256 deposited = 0;
while(deposited < _amount) {
//if the current round does not exist create it
if(currentRound >= roundsPerCK.length) {
roundsPerCK.push();
}
//if the round is already partially baked create a new round
if(roundsPerCK[currentRound].totalBakedInput != 0) {
currentRound = currentRound.add(1);
roundsPerCK.push();
}
Round storage round = roundsPerCK[currentRound];
uint256 roundDeposit = (_amount.sub(deposited)).min(roundInputCaps[_ckToken].sub(round.totalDeposited));
round.totalDeposited = round.totalDeposited.add(roundDeposit);
round.deposits[_to] = round.deposits[_to].add(roundDeposit);
deposited = deposited.add(roundDeposit);
// only push roundsPerCK we are actually in
if(roundDeposit != 0) {
_pushUserRound(_ckToken, _to, currentRound);
}
// if full amount assigned to roundsPerCK break the loop
if(deposited == _amount) {
break;
}
currentRound = currentRound.add(1);
}
emit Deposit(_to, _amount);
}
/**
* Create and return TradeInfo struct. Send Token is WETH
*
* @param _ckToken Instance of the CKToken
* @param _component IERC20 component to trade
* @param _receiveQuantity Amount of the component asset
* @param _slippage Limitation percentage
*
* @return tradeInfo Struct containing data for trade
*/
function _createTradeInfo(
ICKToken _ckToken,
IERC20 _component,
uint256 _receiveQuantity,
uint256 _slippage
)
internal
view
virtual
returns (TradeInfo memory tradeInfo)
{
// set the exchange info
tradeInfo.exchangeAdapter = IIndexExchangeAdapter(
getAndValidateAdapter(tradeExecutionInfo[_ckToken][_component].exchangeName)
);
tradeInfo.exchangeData = tradeExecutionInfo[_ckToken][_component].exchangeData;
// set receive token info
tradeInfo.receiveToken = address(_component);
tradeInfo.receiveQuantity = _receiveQuantity;
// exactSendQuantity is calculated based on the price from the oracle, not the price from the proper exchange
uint256 receiveTokenPrice = _calculateComponentPrice(address(_component), address(weth));
uint256 wethDecimals = ERC20(address(weth)).decimals();
uint256 componentDecimals = ERC20(address(_component)).decimals();
uint256 exactSendQuantity = tradeInfo.receiveQuantity
.preciseMul(receiveTokenPrice)
.mul(10**wethDecimals)
.div(10**componentDecimals);
// set max send limit
uint256 unit_ = 1e18;
tradeInfo.sendQuantityMax = exactSendQuantity.mul(unit_).div(unit_.sub(_slippage));
}
/**
* Function handles all interactions with exchange.
*
* @param _tradeInfo Struct containing trade information used in internal functions
*/
function _executeTrade(TradeInfo memory _tradeInfo) internal returns (uint256) {
ERC20(address(weth)).approve(_tradeInfo.exchangeAdapter.getSpender(), _tradeInfo.sendQuantityMax);
(
address targetExchange,
uint256 callValue,
bytes memory methodData
) = _tradeInfo.exchangeAdapter.getTradeCalldata(
address(weth),
_tradeInfo.receiveToken,
address(this),
false,
_tradeInfo.sendQuantityMax,
_tradeInfo.receiveQuantity,
_tradeInfo.exchangeData
);
uint256 preTradeReserveAmount = weth.balanceOf(address(this));
targetExchange.functionCallWithValue(methodData, callValue);
uint256 postTradeReserveAmount = weth.balanceOf(address(this));
uint256 usedAmount = preTradeReserveAmount.sub(postTradeReserveAmount);
return usedAmount;
}
/**
* Validate issuance info used internally.
*
* @param _ckToken Instance of the CKToken
* @param _issueInfo Struct containing inssuance information used in internal functions
*/
function _validateIssuanceInfo(ICKToken _ckToken, ActionInfo memory _issueInfo) internal view {
// Check that total supply is greater than min supply needed for issuance
// Note: A min supply amount is needed to avoid division by 0 when CKToken supply is 0
require(
_issueInfo.previousCKTokenSupply >= batchIssuanceSettings[_ckToken].minCKTokenSupply,
"Supply must be greater than minimum issuance"
);
}
/**
* Create and return ActionInfo struct.
*
* @param _ckToken Instance of the CKToken
* @param _reserveAsset Address of reserve asset
* @param _reserveAssetQuantity Amount of the reserve asset
*
* @return issueInfo Struct containing data for issuance
*/
function _createIssuanceInfo(
ICKToken _ckToken,
address _reserveAsset,
uint256 _reserveAssetQuantity
)
internal
view
returns (ActionInfo memory)
{
ActionInfo memory issueInfo;
issueInfo.previousCKTokenSupply = _ckToken.totalSupply();
issueInfo.preFeeReserveQuantity = _reserveAssetQuantity;
(issueInfo.totalFeePercentage, issueInfo.protocolFees, issueInfo.managerFee) = _getFees(
_ckToken,
issueInfo.preFeeReserveQuantity,
PROTOCOL_ISSUE_MANAGER_REVENUE_SHARE_FEE_INDEX,
PROTOCOL_ISSUE_DIRECT_FEE_INDEX,
MANAGER_ISSUE_FEE_INDEX
);
issueInfo.netFlowQuantity = issueInfo.preFeeReserveQuantity
.sub(issueInfo.protocolFees)
.sub(issueInfo.managerFee);
issueInfo.ckTokenQuantity = _getCKTokenMintQuantity(
_ckToken,
_reserveAsset,
issueInfo.netFlowQuantity
);
issueInfo.newCKTokenSupply = issueInfo.ckTokenQuantity.add(issueInfo.previousCKTokenSupply);
return issueInfo;
}
/**
* Calculate CKToken mint amount.
*
* @param _ckToken Instance of the CKToken
* @param _reserveAsset Address of reserve asset
* @param _netReserveFlows Value of reserve asset net of fees
*
* @return uint256 Amount of CKToken to mint
*/
function _getCKTokenMintQuantity(
ICKToken _ckToken,
address _reserveAsset,
uint256 _netReserveFlows
)
internal
view
returns (uint256)
{
// Get valuation of the CKToken with the quote asset as the reserve asset. Returns value in precise units (1e18)
// Reverts if price is not found
uint256 ckTokenValuation = controller.getCKValuer().calculateCKTokenValuation(_ckToken, _reserveAsset);
// Get reserve asset decimals
uint256 reserveAssetDecimals = ERC20(_reserveAsset).decimals();
uint256 normalizedTotalReserveQuantityNetFees = _netReserveFlows.preciseDiv(10 ** reserveAssetDecimals);
// Calculate CKTokens to mint to issuer
return normalizedTotalReserveQuantityNetFees.preciseDiv(ckTokenValuation);
}
/**
* Add new roundId to user's rounds array
*
* @param _ckToken Instance of the CKToken
* @param _to Address of depositor
* @param _roundId Round id to add in userRounds
*/
function _pushUserRound(ICKToken _ckToken, address _to, uint256 _roundId) internal {
// only push when its not already added
mapping(address => uint256[]) storage userRoundsPerCK = userRounds[_ckToken];
if(userRoundsPerCK[_to].length == 0 || userRoundsPerCK[_to][userRoundsPerCK[_to].length - 1] != _roundId) {
userRoundsPerCK[_to].push(_roundId);
}
}
/**
* Returns the fees attributed to the manager and the protocol. The fees are calculated as follows:
*
* ManagerFee = (manager fee % - % to protocol) * reserveAssetQuantity, will be recalculated after trades
* Protocol Fee = (% manager fee share + direct fee %) * reserveAssetQuantity
*
* @param _ckToken Instance of the CKToken
* @param _reserveAssetQuantity Quantity of reserve asset to calculate fees from
* @param _protocolManagerFeeIndex Index to pull rev share batch Issuance fee from the Controller
* @param _protocolDirectFeeIndex Index to pull direct batch issuance fee from the Controller
* @param _managerFeeIndex Index from BatchIssuanceSettings (0 = issue fee, 1 = redeem fee)
*
* @return uint256 Total fee percentage
* @return uint256 Fees paid to the protocol in reserve asset
* @return uint256 Fees paid to the manager in reserve asset
*/
function _getFees(
ICKToken _ckToken,
uint256 _reserveAssetQuantity,
uint256 _protocolManagerFeeIndex,
uint256 _protocolDirectFeeIndex,
uint256 _managerFeeIndex
)
internal
view
returns (uint256, uint256, uint256)
{
(uint256 protocolFeePercentage, uint256 managerFeePercentage) = _getProtocolAndManagerFeePercentages(
_ckToken,
_protocolManagerFeeIndex,
_protocolDirectFeeIndex,
_managerFeeIndex
);
// total fee percentage
uint256 totalFeePercentage = protocolFeePercentage.add(managerFeePercentage);
// Calculate total notional fees
uint256 protocolFees = protocolFeePercentage.preciseMul(_reserveAssetQuantity);
uint256 managerFee = managerFeePercentage.preciseMul(_reserveAssetQuantity);
return (totalFeePercentage, protocolFees, managerFee);
}
/**
* Returns the fee percentages of the manager and the protocol.
*
* @param _ckToken Instance of the CKToken
* @param _protocolManagerFeeIndex Index to pull rev share Batch Issuance fee from the Controller
* @param _protocolDirectFeeIndex Index to pull direct Batc issuance fee from the Controller
* @param _managerFeeIndex Index from BatchIssuanceSettings (0 = issue fee, 1 = redeem fee)
*
* @return uint256 Fee percentage to the protocol in reserve asset
* @return uint256 Fee percentage to the manager in reserve asset
*/
function _getProtocolAndManagerFeePercentages(
ICKToken _ckToken,
uint256 _protocolManagerFeeIndex,
uint256 _protocolDirectFeeIndex,
uint256 _managerFeeIndex
)
internal
view
returns(uint256, uint256)
{
// Get protocol fee percentages
uint256 protocolDirectFeePercent = controller.getModuleFee(address(this), _protocolDirectFeeIndex);
uint256 protocolManagerShareFeePercent = controller.getModuleFee(address(this), _protocolManagerFeeIndex);
uint256 managerFeePercent = batchIssuanceSettings[_ckToken].managerFees[_managerFeeIndex];
// Calculate revenue share split percentage
uint256 protocolRevenueSharePercentage = protocolManagerShareFeePercent.preciseMul(managerFeePercent);
uint256 managerRevenueSharePercentage = managerFeePercent.sub(protocolRevenueSharePercentage);
uint256 totalProtocolFeePercentage = protocolRevenueSharePercentage.add(protocolDirectFeePercent);
return (totalProtocolFeePercentage, managerRevenueSharePercentage);
}
/**
* Get the price of the component
*
* @param _component Component to get the price for
* @param _quoteAsset Address of token to quote valuation in
*
* @return uint256 Component's price
*/
function _calculateComponentPrice(address _component, address _quoteAsset) internal view returns (uint256) {
IPriceOracle priceOracle = controller.getPriceOracle();
address masterQuoteAsset = priceOracle.masterQuoteAsset();
// Get component price from price oracle. If price does not exist, revert.
uint256 componentPrice = priceOracle.getPrice(_component, masterQuoteAsset);
if (masterQuoteAsset != _quoteAsset) {
uint256 quoteToMaster = priceOracle.getPrice(_quoteAsset, masterQuoteAsset);
componentPrice = componentPrice.preciseDiv(quoteToMaster);
}
return componentPrice;
}
/**
* Transfer fees(WETH) from module to appropriate fee recipients
*
* @param _ckToken Instance of the CKToken
* @param _issueInfo Issuance information, contains fee recipient address and fee amounts
*/
function _transferFees(ICKToken _ckToken, ActionInfo memory _issueInfo) internal {
if (_issueInfo.protocolFees > 0) {
weth.safeTransfer(controller.feeRecipient(), _issueInfo.protocolFees);
}
if (_issueInfo.managerFee > 0) {
weth.safeTransfer(batchIssuanceSettings[_ckToken].feeRecipient, _issueInfo.managerFee);
}
}
}
|
Mints the appropriate % of Net Asset Value of the CKToken from the deposited WETH in the rounds. Fee(protocol fee + manager shared fee + manager fee in the module) will be used as slipage to trade on DEXs. The exact amount protocol fee will be deliver to the protocol. Only remaining WETH will be paid to the manager as a fee. _ckToken Instance of the CKToken _rounds Array of round indexes/ Get max input amount Prevent round from being baked twice approve every component for basic issuance module Skip round if it is already baked
|
function batchIssue(
ICKToken _ckToken, uint256[] memory _rounds
)
external
nonReentrant
onlyValidAndInitializedCK(_ckToken)
{
uint256 maxInputAmount;
Round[] storage roundsPerCK = rounds[_ckToken];
for(uint256 i = 0; i < _rounds.length; i ++) {
if(i != 0) {
require(_rounds[i] > _rounds[i - 1], "Rounds out of order");
}
Round storage round = roundsPerCK[_rounds[i]];
maxInputAmount = maxInputAmount.add(round.totalDeposited.sub(round.totalBakedInput));
}
require(maxInputAmount > 0, "Quantity must be > 0");
ActionInfo memory issueInfo = _createIssuanceInfo(_ckToken, address(weth), maxInputAmount);
_validateIssuanceInfo(_ckToken, issueInfo);
uint256 inputUsed = 0;
uint256 outputAmount = issueInfo.ckTokenQuantity;
address[] memory components,
uint256[] memory componentQuantities
) = basicIssuanceModule.getRequiredComponentUnitsForIssue(_ckToken, outputAmount);
for (uint256 i = 0; i < components.length; i++) {
IERC20 component_ = IERC20(components[i]);
uint256 quantity_ = componentQuantities[i];
if (address(component_) != address(weth)) {
TradeInfo memory tradeInfo = _createTradeInfo(
_ckToken,
IERC20(component_),
quantity_,
issueInfo.totalFeePercentage
);
uint256 usedAmountForTrade = _executeTrade(tradeInfo);
inputUsed = inputUsed.add(usedAmountForTrade);
inputUsed = inputUsed.add(quantity_);
}
if (component_.allowance(address(this), address(basicIssuanceModule)) < quantity_) {
component_.safeIncreaseAllowance(address(basicIssuanceModule), quantity_);
}
}
uint256 inputUsedRemaining = maxInputAmount;
for(uint256 i = 0; i < _rounds.length; i ++) {
Round storage round = roundsPerCK[_rounds[i]];
uint256 roundTotalBaked = round.totalBakedInput;
uint256 roundTotalDeposited = round.totalDeposited;
uint256 roundInputBaked = (roundTotalDeposited.sub(roundTotalBaked)).min(inputUsedRemaining);
if(roundInputBaked == 0) {
continue;
}
uint256 roundOutputBaked = outputAmount.mul(roundInputBaked).div(maxInputAmount);
round.totalBakedInput = roundTotalBaked.add(roundInputBaked);
inputUsedRemaining = inputUsedRemaining.sub(roundInputBaked);
round.totalOutput = round.totalOutput.add(roundOutputBaked);
}
require(inputUsedWithProtocolFee <= maxInputAmount, "Max input sanity check failed");
_transferFees(_ckToken, issueInfo);
emit CKTokenBatchIssued(_ckToken, maxInputAmount, outputAmount, _rounds.length);
}
| 2,363,695
|
./partial_match/1/0x508efB44A06a64Bd4020e8c5e8Ecf1A9236C75aE/sources/bytesUtilsExporter.sol
|
export _bytesToAddress() as an external function.
|
function bytesToAddress(bytes calldata _bts, uint256 _from) external pure returns (address) {
return _bts._bytesToAddress(_from);
}
| 3,598,152
|
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/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 {
// 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/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/access/roles/WhitelistAdminRole.sol
pragma solidity ^0.5.0;
/**
* @title WhitelistAdminRole
* @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts.
*/
contract WhitelistAdminRole is Context {
using Roles for Roles.Role;
event WhitelistAdminAdded(address indexed account);
event WhitelistAdminRemoved(address indexed account);
Roles.Role private _whitelistAdmins;
constructor () internal {
_addWhitelistAdmin(_msgSender());
}
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);
}
}
// File: @openzeppelin/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 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 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);
}
}
// File: @openzeppelin/contracts/drafts/Strings.sol
pragma solidity ^0.5.0;
/**
* @title Strings
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to a `string`.
* via OraclizeAPI - MIT licence
* https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
*/
function fromUint256(uint256 value) internal pure returns (string memory) {
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--] = byte(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// File: @openzeppelin/contracts/introspection/IERC165.sol
pragma solidity ^0.5.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.5.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
contract IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of NFTs in `owner`'s account.
*/
function balanceOf(address owner) public view returns (uint256 balance);
/**
* @dev Returns the owner of the NFT specified by `tokenId`.
*/
function ownerOf(uint256 tokenId) public view returns (address owner);
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
*
*
* Requirements:
* - `from`, `to` cannot be zero.
* - `tokenId` must be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this
* NFT by either {approve} or {setApprovalForAll}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public;
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
* Requirements:
* - If the caller is not `from`, it must be approved to move this NFT by
* either {approve} or {setApprovalForAll}.
*/
function transferFrom(address from, address to, uint256 tokenId) public;
function approve(address to, uint256 tokenId) public;
function getApproved(uint256 tokenId) public view returns (address operator);
function setApprovalForAll(address operator, bool _approved) public;
function isApprovedForAll(address owner, address operator) public view returns (bool);
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public;
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^0.5.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract IERC721Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a {IERC721-safeTransferFrom}. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 contract address is always the message sender.
* @param operator The address which called `safeTransferFrom` function
* @param from The address which previously owned the token
* @param tokenId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data)
public returns (bytes4);
}
// 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/drafts/Counters.sol
pragma solidity ^0.5.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// File: @openzeppelin/contracts/introspection/ERC165.sol
pragma solidity ^0.5.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
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) external view 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 {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity ^0.5.0;
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
// 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 token ID to owner
mapping (uint256 => address) private _tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => Counters.Counter) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
/*
* 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
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
constructor () public {
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
}
/**
* @dev Gets the balance of the specified address.
* @param owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address owner) public view returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _ownedTokensCount[owner].current();
}
/**
* @dev Gets the owner of the specified token ID.
* @param tokenId uint256 ID of the token to query the owner of
* @return address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 tokenId) public view returns (address) {
address owner = _tokenOwner[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
function approve(address to, uint256 tokenId) public {
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"
);
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 tokenId) public view returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf.
* @param to operator address to set the approval
* @param approved representing the status of the approval to be set
*/
function setApprovalForAll(address to, bool approved) public {
require(to != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][to] = approved;
emit ApprovalForAll(_msgSender(), to, approved);
}
/**
* @dev Tells whether an operator is approved by a given owner.
* @param owner owner address which you want to query the approval of
* @param operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address owner, address operator) public view returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address.
* Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
* Requires the msg.sender to be the owner, approved, or operator.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function transferFrom(address from, address to, uint256 tokenId) public {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transferFrom(from, to, tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the _msgSender() to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransferFrom(from, to, tokenId, _data);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) internal {
_transferFrom(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether the specified token exists.
* @param tokenId uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(uint256 tokenId) internal view returns (bool) {
address owner = _tokenOwner[tokenId];
return owner != address(0);
}
/**
* @dev Returns whether the given spender can transfer a given token ID.
* @param spender address of the spender to query
* @param tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _safeMint(address to, uint256 tokenId) internal {
_safeMint(to, tokenId, "");
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
* @param _data bytes data to send along with a safe transfer check
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _mint(address to, uint256 tokenId) internal {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_tokenOwner[tokenId] = to;
_ownedTokensCount[to].increment();
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use {_burn} instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, uint256 tokenId) internal {
require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own");
_clearApproval(tokenId);
_ownedTokensCount[owner].decrement();
_tokenOwner[tokenId] = address(0);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* @param tokenId uint256 ID of the token being burned
*/
function _burn(uint256 tokenId) internal {
_burn(ownerOf(tokenId), tokenId);
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _transferFrom(address from, address to, uint256 tokenId) internal {
require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_clearApproval(tokenId);
_ownedTokensCount[from].decrement();
_ownedTokensCount[to].increment();
_tokenOwner[tokenId] = to;
emit Transfer(from, 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.
*
* This function is deprecated.
* @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)
internal returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes4 retval = IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data);
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Private function to clear current approval of a given token ID.
* @param tokenId uint256 ID of the token to be transferred
*/
function _clearApproval(uint256 tokenId) private {
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol
pragma solidity ^0.5.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract IERC721Enumerable is IERC721 {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId);
function tokenByIndex(uint256 index) public view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/ERC721Enumerable.sol
pragma solidity ^0.5.0;
/**
* @title ERC-721 Non-Fungible Token with optional enumeration extension logic
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721Enumerable is Context, ERC165, ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => 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;
/*
* 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 Constructor function.
*/
constructor () public {
// register the supported interface to conform to ERC721Enumerable via ERC165
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner.
* @param owner address owning the tokens list to be accessed
* @param index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) {
require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev Gets the total amount of tokens stored by the contract.
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return _allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens.
* @param index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 index) public view returns (uint256) {
require(index < totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to transferFrom, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _transferFrom(address from, address to, uint256 tokenId) internal {
super._transferFrom(from, to, tokenId);
_removeTokenFromOwnerEnumeration(from, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
}
/**
* @dev Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to address the beneficiary that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _mint(address to, uint256 tokenId) internal {
super._mint(to, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
_addTokenToAllTokensEnumeration(tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use {ERC721-_burn} instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
_removeTokenFromOwnerEnumeration(owner, tokenId);
// Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund
_ownedTokensIndex[tokenId] = 0;
_removeTokenFromAllTokensEnumeration(tokenId);
}
/**
* @dev Gets the list of token IDs of the requested owner.
* @param owner address owning the tokens
* @return uint256[] List of token IDs owned by the requested address
*/
function _tokensOfOwner(address owner) internal view returns (uint256[] storage) {
return _ownedTokens[owner];
}
/**
* @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 {
_ownedTokensIndex[tokenId] = _ownedTokens[to].length;
_ownedTokens[to].push(tokenId);
}
/**
* @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 = _ownedTokens[from].length.sub(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
_ownedTokens[from].length--;
// Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by
// lastTokenId, or just over the end of the array if the token was the last one).
}
/**
* @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.sub(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
_allTokens.length--;
_allTokensIndex[tokenId] = 0;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol
pragma solidity ^0.5.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: contracts/interfaces/erc721/ERC721MetadataWithoutTokenURI.sol
pragma solidity ^0.5.14;
contract ERC721MetadataWithoutTokenURI is ERC165, ERC721, IERC721Metadata {
// Token name
string private _name;
// Token symbol
string private _symbol;
/*
* 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;
/**
* @dev Constructor function
*/
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_METADATA);
}
/**
* @dev Gets the token name.
* @return string representing the token name
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol.
* @return string representing the token symbol
*/
function symbol() external view returns (string memory) {
return _symbol;
}
}
// File: contracts/interfaces/erc721/CustomERC721Full.sol
pragma solidity ^0.5.14;
/**
* @title Custom version of the Full ERC721 Token contract produced by OpenZeppelin
* This implementation includes all the required, some optional functionality of the ERC721 standard and removes
* tokenURIs from the base ERC721Metadata contract.
* Moreover, it includes approve all functionality using operator terminology
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract CustomERC721Full is ERC721, ERC721Enumerable, ERC721MetadataWithoutTokenURI {
constructor (string memory name, string memory symbol) public ERC721MetadataWithoutTokenURI(name, symbol) {
// solhint-disable-previous-line no-empty-blocks
}
}
// File: contracts/interfaces/ITokenlandiaTokenCreator.sol
pragma solidity ^0.5.14;
contract ITokenlandiaTokenCreator {
function mintToken(
uint256 _tokenId,
address _recipient,
string calldata _productCode,
string calldata _ipfsHash
) external returns (bool success);
}
// File: @openzeppelin/contracts/GSN/IRelayRecipient.sol
pragma solidity ^0.5.0;
/**
* @dev Base interface for a contract that will be called via the GSN from {IRelayHub}.
*
* TIP: You don't need to write an implementation yourself! Inherit from {GSNRecipient} instead.
*/
contract IRelayRecipient {
/**
* @dev Returns the address of the {IRelayHub} instance this recipient interacts with.
*/
function getHubAddr() public view returns (address);
/**
* @dev Called by {IRelayHub} to validate if this recipient accepts being charged for a relayed call. Note that the
* recipient will be charged regardless of the execution result of the relayed call (i.e. if it reverts or not).
*
* The relay request was originated by `from` and will be served by `relay`. `encodedFunction` is the relayed call
* calldata, so its first four bytes are the function selector. The relayed call will be forwarded `gasLimit` gas,
* and the transaction executed with a gas price of at least `gasPrice`. `relay`'s fee is `transactionFee`, and the
* recipient will be charged at most `maxPossibleCharge` (in wei). `nonce` is the sender's (`from`) nonce for
* replay attack protection in {IRelayHub}, and `approvalData` is a optional parameter that can be used to hold a signature
* over all or some of the previous values.
*
* Returns a tuple, where the first value is used to indicate approval (0) or rejection (custom non-zero error code,
* values 1 to 10 are reserved) and the second one is data to be passed to the other {IRelayRecipient} functions.
*
* {acceptRelayedCall} is called with 50k gas: if it runs out during execution, the request will be considered
* rejected. A regular revert will also trigger a rejection.
*/
function acceptRelayedCall(
address relay,
address from,
bytes calldata encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes calldata approvalData,
uint256 maxPossibleCharge
)
external
view
returns (uint256, bytes memory);
/**
* @dev Called by {IRelayHub} on approved relay call requests, before the relayed call is executed. This allows to e.g.
* pre-charge the sender of the transaction.
*
* `context` is the second value returned in the tuple by {acceptRelayedCall}.
*
* Returns a value to be passed to {postRelayedCall}.
*
* {preRelayedCall} is called with 100k gas: if it runs out during exection or otherwise reverts, the relayed call
* will not be executed, but the recipient will still be charged for the transaction's cost.
*/
function preRelayedCall(bytes calldata context) external returns (bytes32);
/**
* @dev Called by {IRelayHub} on approved relay call requests, after the relayed call is executed. This allows to e.g.
* charge the user for the relayed call costs, return any overcharges from {preRelayedCall}, or perform
* contract-specific bookkeeping.
*
* `context` is the second value returned in the tuple by {acceptRelayedCall}. `success` is the execution status of
* the relayed call. `actualCharge` is an estimate of how much the recipient will be charged for the transaction,
* not including any gas used by {postRelayedCall} itself. `preRetVal` is {preRelayedCall}'s return value.
*
*
* {postRelayedCall} is called with 100k gas: if it runs out during execution or otherwise reverts, the relayed call
* and the call to {preRelayedCall} will be reverted retroactively, but the recipient will still be charged for the
* transaction's cost.
*/
function postRelayedCall(bytes calldata context, bool success, uint256 actualCharge, bytes32 preRetVal) external;
}
// File: @openzeppelin/contracts/GSN/IRelayHub.sol
pragma solidity ^0.5.0;
/**
* @dev Interface for `RelayHub`, the core contract of the GSN. Users should not need to interact with this contract
* directly.
*
* See the https://github.com/OpenZeppelin/openzeppelin-gsn-helpers[OpenZeppelin GSN helpers] for more information on
* how to deploy an instance of `RelayHub` on your local test network.
*/
contract IRelayHub {
// Relay management
/**
* @dev Adds stake to a relay and sets its `unstakeDelay`. If the relay does not exist, it is created, and the caller
* of this function becomes its owner. If the relay already exists, only the owner can call this function. A relay
* cannot be its own owner.
*
* All Ether in this function call will be added to the relay's stake.
* Its unstake delay will be assigned to `unstakeDelay`, but the new value must be greater or equal to the current one.
*
* Emits a {Staked} event.
*/
function stake(address relayaddr, uint256 unstakeDelay) external payable;
/**
* @dev Emitted when a relay's stake or unstakeDelay are increased
*/
event Staked(address indexed relay, uint256 stake, uint256 unstakeDelay);
/**
* @dev Registers the caller as a relay.
* The relay must be staked for, and not be a contract (i.e. this function must be called directly from an EOA).
*
* This function can be called multiple times, emitting new {RelayAdded} events. Note that the received
* `transactionFee` is not enforced by {relayCall}.
*
* Emits a {RelayAdded} event.
*/
function registerRelay(uint256 transactionFee, string memory url) public;
/**
* @dev Emitted when a relay is registered or re-registerd. Looking at these events (and filtering out
* {RelayRemoved} events) lets a client discover the list of available relays.
*/
event RelayAdded(address indexed relay, address indexed owner, uint256 transactionFee, uint256 stake, uint256 unstakeDelay, string url);
/**
* @dev Removes (deregisters) a relay. Unregistered (but staked for) relays can also be removed.
*
* Can only be called by the owner of the relay. After the relay's `unstakeDelay` has elapsed, {unstake} will be
* callable.
*
* Emits a {RelayRemoved} event.
*/
function removeRelayByOwner(address relay) public;
/**
* @dev Emitted when a relay is removed (deregistered). `unstakeTime` is the time when unstake will be callable.
*/
event RelayRemoved(address indexed relay, uint256 unstakeTime);
/** Deletes the relay from the system, and gives back its stake to the owner.
*
* Can only be called by the relay owner, after `unstakeDelay` has elapsed since {removeRelayByOwner} was called.
*
* Emits an {Unstaked} event.
*/
function unstake(address relay) public;
/**
* @dev Emitted when a relay is unstaked for, including the returned stake.
*/
event Unstaked(address indexed relay, uint256 stake);
// States a relay can be in
enum RelayState {
Unknown, // The relay is unknown to the system: it has never been staked for
Staked, // The relay has been staked for, but it is not yet active
Registered, // The relay has registered itself, and is active (can relay calls)
Removed // The relay has been removed by its owner and can no longer relay calls. It must wait for its unstakeDelay to elapse before it can unstake
}
/**
* @dev Returns a relay's status. Note that relays can be deleted when unstaked or penalized, causing this function
* to return an empty entry.
*/
function getRelay(address relay) external view returns (uint256 totalStake, uint256 unstakeDelay, uint256 unstakeTime, address payable owner, RelayState state);
// Balance management
/**
* @dev Deposits Ether for a contract, so that it can receive (and pay for) relayed transactions.
*
* Unused balance can only be withdrawn by the contract itself, by calling {withdraw}.
*
* Emits a {Deposited} event.
*/
function depositFor(address target) public payable;
/**
* @dev Emitted when {depositFor} is called, including the amount and account that was funded.
*/
event Deposited(address indexed recipient, address indexed from, uint256 amount);
/**
* @dev Returns an account's deposits. These can be either a contracts's funds, or a relay owner's revenue.
*/
function balanceOf(address target) external view returns (uint256);
/**
* Withdraws from an account's balance, sending it back to it. Relay owners call this to retrieve their revenue, and
* contracts can use it to reduce their funding.
*
* Emits a {Withdrawn} event.
*/
function withdraw(uint256 amount, address payable dest) public;
/**
* @dev Emitted when an account withdraws funds from `RelayHub`.
*/
event Withdrawn(address indexed account, address indexed dest, uint256 amount);
// Relaying
/**
* @dev Checks if the `RelayHub` will accept a relayed operation.
* Multiple things must be true for this to happen:
* - all arguments must be signed for by the sender (`from`)
* - the sender's nonce must be the current one
* - the recipient must accept this transaction (via {acceptRelayedCall})
*
* Returns a `PreconditionCheck` value (`OK` when the transaction can be relayed), or a recipient-specific error
* code if it returns one in {acceptRelayedCall}.
*/
function canRelay(
address relay,
address from,
address to,
bytes memory encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes memory signature,
bytes memory approvalData
) public view returns (uint256 status, bytes memory recipientContext);
// Preconditions for relaying, checked by canRelay and returned as the corresponding numeric values.
enum PreconditionCheck {
OK, // All checks passed, the call can be relayed
WrongSignature, // The transaction to relay is not signed by requested sender
WrongNonce, // The provided nonce has already been used by the sender
AcceptRelayedCallReverted, // The recipient rejected this call via acceptRelayedCall
InvalidRecipientStatusCode // The recipient returned an invalid (reserved) status code
}
/**
* @dev Relays a transaction.
*
* For this to succeed, multiple conditions must be met:
* - {canRelay} must `return PreconditionCheck.OK`
* - the sender must be a registered relay
* - the transaction's gas price must be larger or equal to the one that was requested by the sender
* - the transaction must have enough gas to not run out of gas if all internal transactions (calls to the
* recipient) use all gas available to them
* - the recipient must have enough balance to pay the relay for the worst-case scenario (i.e. when all gas is
* spent)
*
* If all conditions are met, the call will be relayed and the recipient charged. {preRelayedCall}, the encoded
* function and {postRelayedCall} will be called in that order.
*
* Parameters:
* - `from`: the client originating the request
* - `to`: the target {IRelayRecipient} contract
* - `encodedFunction`: the function call to relay, including data
* - `transactionFee`: fee (%) the relay takes over actual gas cost
* - `gasPrice`: gas price the client is willing to pay
* - `gasLimit`: gas to forward when calling the encoded function
* - `nonce`: client's nonce
* - `signature`: client's signature over all previous params, plus the relay and RelayHub addresses
* - `approvalData`: dapp-specific data forwared to {acceptRelayedCall}. This value is *not* verified by the
* `RelayHub`, but it still can be used for e.g. a signature.
*
* Emits a {TransactionRelayed} event.
*/
function relayCall(
address from,
address to,
bytes memory encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes memory signature,
bytes memory approvalData
) public;
/**
* @dev Emitted when an attempt to relay a call failed.
*
* This can happen due to incorrect {relayCall} arguments, or the recipient not accepting the relayed call. The
* actual relayed call was not executed, and the recipient not charged.
*
* The `reason` parameter contains an error code: values 1-10 correspond to `PreconditionCheck` entries, and values
* over 10 are custom recipient error codes returned from {acceptRelayedCall}.
*/
event CanRelayFailed(address indexed relay, address indexed from, address indexed to, bytes4 selector, uint256 reason);
/**
* @dev Emitted when a transaction is relayed.
* Useful when monitoring a relay's operation and relayed calls to a contract
*
* Note that the actual encoded function might be reverted: this is indicated in the `status` parameter.
*
* `charge` is the Ether value deducted from the recipient's balance, paid to the relay's owner.
*/
event TransactionRelayed(address indexed relay, address indexed from, address indexed to, bytes4 selector, RelayCallStatus status, uint256 charge);
// Reason error codes for the TransactionRelayed event
enum RelayCallStatus {
OK, // The transaction was successfully relayed and execution successful - never included in the event
RelayedCallFailed, // The transaction was relayed, but the relayed call failed
PreRelayedFailed, // The transaction was not relayed due to preRelatedCall reverting
PostRelayedFailed, // The transaction was relayed and reverted due to postRelatedCall reverting
RecipientBalanceChanged // The transaction was relayed and reverted due to the recipient's balance changing
}
/**
* @dev Returns how much gas should be forwarded to a call to {relayCall}, in order to relay a transaction that will
* spend up to `relayedCallStipend` gas.
*/
function requiredGas(uint256 relayedCallStipend) public view returns (uint256);
/**
* @dev Returns the maximum recipient charge, given the amount of gas forwarded, gas price and relay fee.
*/
function maxPossibleCharge(uint256 relayedCallStipend, uint256 gasPrice, uint256 transactionFee) public view returns (uint256);
// Relay penalization.
// Any account can penalize relays, removing them from the system immediately, and rewarding the
// reporter with half of the relay's stake. The other half is burned so that, even if the relay penalizes itself, it
// still loses half of its stake.
/**
* @dev Penalize a relay that signed two transactions using the same nonce (making only the first one valid) and
* different data (gas price, gas limit, etc. may be different).
*
* The (unsigned) transaction data and signature for both transactions must be provided.
*/
function penalizeRepeatedNonce(bytes memory unsignedTx1, bytes memory signature1, bytes memory unsignedTx2, bytes memory signature2) public;
/**
* @dev Penalize a relay that sent a transaction that didn't target `RelayHub`'s {registerRelay} or {relayCall}.
*/
function penalizeIllegalTransaction(bytes memory unsignedTx, bytes memory signature) public;
/**
* @dev Emitted when a relay is penalized.
*/
event Penalized(address indexed relay, address sender, uint256 amount);
/**
* @dev Returns an account's nonce in `RelayHub`.
*/
function getNonce(address from) external view returns (uint256);
}
// File: @openzeppelin/contracts/GSN/GSNRecipient.sol
pragma solidity ^0.5.0;
/**
* @dev Base GSN recipient contract: includes the {IRelayRecipient} interface
* and enables GSN support on all contracts in the inheritance tree.
*
* TIP: This contract is abstract. The functions {acceptRelayedCall},
* {_preRelayedCall}, and {_postRelayedCall} are not implemented and must be
* provided by derived contracts. See the
* xref:ROOT:gsn-strategies.adoc#gsn-strategies[GSN strategies] for more
* information on how to use the pre-built {GSNRecipientSignature} and
* {GSNRecipientERC20Fee}, or how to write your own.
*/
contract GSNRecipient is IRelayRecipient, Context {
// Default RelayHub address, deployed on mainnet and all testnets at the same address
address private _relayHub = 0xD216153c06E857cD7f72665E0aF1d7D82172F494;
uint256 constant private RELAYED_CALL_ACCEPTED = 0;
uint256 constant private RELAYED_CALL_REJECTED = 11;
// How much gas is forwarded to postRelayedCall
uint256 constant internal POST_RELAYED_CALL_MAX_GAS = 100000;
/**
* @dev Emitted when a contract changes its {IRelayHub} contract to a new one.
*/
event RelayHubChanged(address indexed oldRelayHub, address indexed newRelayHub);
/**
* @dev Returns the address of the {IRelayHub} contract for this recipient.
*/
function getHubAddr() public view returns (address) {
return _relayHub;
}
/**
* @dev Switches to a new {IRelayHub} instance. This method is added for future-proofing: there's no reason to not
* use the default instance.
*
* IMPORTANT: After upgrading, the {GSNRecipient} will no longer be able to receive relayed calls from the old
* {IRelayHub} instance. Additionally, all funds should be previously withdrawn via {_withdrawDeposits}.
*/
function _upgradeRelayHub(address newRelayHub) internal {
address currentRelayHub = _relayHub;
require(newRelayHub != address(0), "GSNRecipient: new RelayHub is the zero address");
require(newRelayHub != currentRelayHub, "GSNRecipient: new RelayHub is the current one");
emit RelayHubChanged(currentRelayHub, newRelayHub);
_relayHub = newRelayHub;
}
/**
* @dev Returns the version string of the {IRelayHub} for which this recipient implementation was built. If
* {_upgradeRelayHub} is used, the new {IRelayHub} instance should be compatible with this version.
*/
// This function is view for future-proofing, it may require reading from
// storage in the future.
function relayHubVersion() public view returns (string memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return "1.0.0";
}
/**
* @dev Withdraws the recipient's deposits in `RelayHub`.
*
* Derived contracts should expose this in an external interface with proper access control.
*/
function _withdrawDeposits(uint256 amount, address payable payee) internal {
IRelayHub(_relayHub).withdraw(amount, payee);
}
// Overrides for Context's functions: when called from RelayHub, sender and
// data require some pre-processing: the actual sender is stored at the end
// of the call data, which in turns means it needs to be removed from it
// when handling said data.
/**
* @dev Replacement for msg.sender. Returns the actual sender of a transaction: msg.sender for regular transactions,
* and the end-user for GSN relayed calls (where msg.sender is actually `RelayHub`).
*
* IMPORTANT: Contracts derived from {GSNRecipient} should never use `msg.sender`, and use {_msgSender} instead.
*/
function _msgSender() internal view returns (address payable) {
if (msg.sender != _relayHub) {
return msg.sender;
} else {
return _getRelayedCallSender();
}
}
/**
* @dev Replacement for msg.data. Returns the actual calldata of a transaction: msg.data for regular transactions,
* and a reduced version for GSN relayed calls (where msg.data contains additional information).
*
* IMPORTANT: Contracts derived from {GSNRecipient} should never use `msg.data`, and use {_msgData} instead.
*/
function _msgData() internal view returns (bytes memory) {
if (msg.sender != _relayHub) {
return msg.data;
} else {
return _getRelayedCallData();
}
}
// Base implementations for pre and post relayedCall: only RelayHub can invoke them, and data is forwarded to the
// internal hook.
/**
* @dev See `IRelayRecipient.preRelayedCall`.
*
* This function should not be overriden directly, use `_preRelayedCall` instead.
*
* * Requirements:
*
* - the caller must be the `RelayHub` contract.
*/
function preRelayedCall(bytes calldata context) external returns (bytes32) {
require(msg.sender == getHubAddr(), "GSNRecipient: caller is not RelayHub");
return _preRelayedCall(context);
}
/**
* @dev See `IRelayRecipient.preRelayedCall`.
*
* Called by `GSNRecipient.preRelayedCall`, which asserts the caller is the `RelayHub` contract. Derived contracts
* must implement this function with any relayed-call preprocessing they may wish to do.
*
*/
function _preRelayedCall(bytes memory context) internal returns (bytes32);
/**
* @dev See `IRelayRecipient.postRelayedCall`.
*
* This function should not be overriden directly, use `_postRelayedCall` instead.
*
* * Requirements:
*
* - the caller must be the `RelayHub` contract.
*/
function postRelayedCall(bytes calldata context, bool success, uint256 actualCharge, bytes32 preRetVal) external {
require(msg.sender == getHubAddr(), "GSNRecipient: caller is not RelayHub");
_postRelayedCall(context, success, actualCharge, preRetVal);
}
/**
* @dev See `IRelayRecipient.postRelayedCall`.
*
* Called by `GSNRecipient.postRelayedCall`, which asserts the caller is the `RelayHub` contract. Derived contracts
* must implement this function with any relayed-call postprocessing they may wish to do.
*
*/
function _postRelayedCall(bytes memory context, bool success, uint256 actualCharge, bytes32 preRetVal) internal;
/**
* @dev Return this in acceptRelayedCall to proceed with the execution of a relayed call. Note that this contract
* will be charged a fee by RelayHub
*/
function _approveRelayedCall() internal pure returns (uint256, bytes memory) {
return _approveRelayedCall("");
}
/**
* @dev See `GSNRecipient._approveRelayedCall`.
*
* This overload forwards `context` to _preRelayedCall and _postRelayedCall.
*/
function _approveRelayedCall(bytes memory context) internal pure returns (uint256, bytes memory) {
return (RELAYED_CALL_ACCEPTED, context);
}
/**
* @dev Return this in acceptRelayedCall to impede execution of a relayed call. No fees will be charged.
*/
function _rejectRelayedCall(uint256 errorCode) internal pure returns (uint256, bytes memory) {
return (RELAYED_CALL_REJECTED + errorCode, "");
}
/*
* @dev Calculates how much RelayHub will charge a recipient for using `gas` at a `gasPrice`, given a relayer's
* `serviceFee`.
*/
function _computeCharge(uint256 gas, uint256 gasPrice, uint256 serviceFee) internal pure returns (uint256) {
// The fee is expressed as a percentage. E.g. a value of 40 stands for a 40% fee, so the recipient will be
// charged for 1.4 times the spent amount.
return (gas * gasPrice * (100 + serviceFee)) / 100;
}
function _getRelayedCallSender() private pure returns (address payable result) {
// We need to read 20 bytes (an address) located at array index msg.data.length - 20. In memory, the array
// is prefixed with a 32-byte length value, so we first add 32 to get the memory read index. However, doing
// so would leave the address in the upper 20 bytes of the 32-byte word, which is inconvenient and would
// require bit shifting. We therefore subtract 12 from the read index so the address lands on the lower 20
// bytes. This can always be done due to the 32-byte prefix.
// The final memory read index is msg.data.length - 20 + 32 - 12 = msg.data.length. Using inline assembly is the
// easiest/most-efficient way to perform this operation.
// These fields are not accessible from assembly
bytes memory array = msg.data;
uint256 index = msg.data.length;
// solhint-disable-next-line no-inline-assembly
assembly {
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
result := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
return result;
}
function _getRelayedCallData() private pure returns (bytes memory) {
// RelayHub appends the sender address at the end of the calldata, so in order to retrieve the actual msg.data,
// we must strip the last 20 bytes (length of an address type) from it.
uint256 actualDataLength = msg.data.length - 20;
bytes memory actualData = new bytes(actualDataLength);
for (uint256 i = 0; i < actualDataLength; ++i) {
actualData[i] = msg.data[i];
}
return actualData;
}
}
// File: @openzeppelin/contracts/cryptography/ECDSA.sol
pragma solidity ^0.5.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.
*
* NOTE: This call _does not revert_ if the signature is invalid, or
* if the signer is otherwise unable to be retrieved. In those scenarios,
* the zero address is returned.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return address(0);
}
if (v != 27 && v != 28) {
return address(0);
}
// If the signature is valid (and not malleable), return the signer address
return ecrecover(hash, v, r, s);
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// File: contracts/GSN/TokenLandiaWhitelistGSNRecipient.sol
pragma solidity ^0.5.14;
/* Based on v2.4.0 of GSNRecipientSignature from openzeppelin */
contract TokenLandiaWhitelistGSNRecipient is WhitelistedRole, GSNRecipient {
using ECDSA for bytes32;
enum GSNRecipientSignatureErrorCodes {
INVALID_SENDER
}
constructor() public {
super.addWhitelisted(_msgSender());
}
/**
* @dev Ensures that only transactions with a trusted signature can be relayed through the GSN.
*/
function acceptRelayedCall(
address relay,
address from,
bytes calldata encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes calldata approvalData,
uint256
)
external
view
returns (uint256, bytes memory)
{
bytes memory blob = abi.encodePacked(
relay,
from,
encodedFunction,
transactionFee,
gasPrice,
gasLimit,
nonce, // Prevents replays on RelayHub
getHubAddr(), // Prevents replays in multiple RelayHubs
address(this) // Prevents replays in multiple recipients
);
bool isOriginalCallerWhitelisted = isWhitelisted(keccak256(blob).toEthSignedMessageHash().recover(approvalData));
if (isOriginalCallerWhitelisted) {
return _approveRelayedCall();
} else {
return _rejectRelayedCall(uint256(GSNRecipientSignatureErrorCodes.INVALID_SENDER));
}
}
function _preRelayedCall(bytes memory) internal returns (bytes32) {
// solhint-disable-previous-line no-empty-blocks
}
function _postRelayedCall(bytes memory, bool, uint256, bytes32) internal {
// solhint-disable-previous-line no-empty-blocks
}
function upgradeRelayHub(address newRelayHub) external onlyWhitelistAdmin {
_upgradeRelayHub(newRelayHub);
}
}
// File: contracts/token/Tokenlandia.sol
pragma solidity ^0.5.14;
contract Tokenlandia is CustomERC721Full, ITokenlandiaTokenCreator, TokenLandiaWhitelistGSNRecipient {
using SafeMath for uint256;
string public tokenBaseURI = "";
struct Token {
string productCode;
string ipfsHash;
}
mapping(uint256 => Token) internal tokens;
// Reverse mapping so we can lookup the token from the product ID
mapping(string => uint256) internal productIdToTokenId;
modifier onlyWhenTokenExists(uint256 _tokenId) {
require(_exists(_tokenId), "Token ID not valid");
_;
}
constructor (string memory _tokenBaseURI) public
CustomERC721Full("TokenLandia NFT", "TLN")
TokenLandiaWhitelistGSNRecipient() {
tokenBaseURI = _tokenBaseURI;
}
/**
* Mint a token to a specific recipient
* @dev Only callable from whitelisted address
* @param _tokenId uint256 id of the token
* @param _recipient address of the recipient
* @param _productCode string the product code identified - [productCode-tokenId] provides a uniqueness guarantee
* @param _ipfsHash string the IPFS hash
**/
function mintToken(
uint256 _tokenId,
address _recipient,
string calldata _productCode,
string calldata _ipfsHash
) external onlyWhitelisted returns (bool success) {
require(bytes(_productCode).length > 0, "Product code invalid");
require(bytes(_ipfsHash).length > 0, "IPFS hash invalid");
// Create Token metadata
tokens[_tokenId] = Token({
productCode : _productCode,
ipfsHash : _ipfsHash
});
// Mint token
_mint(_recipient, _tokenId);
// Create reverse lookup from productId to tokenId
productIdToTokenId[string(abi.encodePacked(_productCode, "-", Strings.fromUint256(_tokenId)))] = _tokenId;
return true;
}
function ipfsUrlForProductId(string calldata productId)
external
view returns (
string memory _ipfsUrl
) {
uint256 tokenId = productIdToTokenId[productId];
require(_exists(tokenId), "Token not found for product ID");
return string(abi.encodePacked(tokenBaseURI, tokens[tokenId].ipfsHash));
}
function attributes(uint256 _tokenId)
external
onlyWhenTokenExists(_tokenId) view returns (
string memory _productCode,
string memory _productId,
string memory _ipfsUrl
) {
Token storage token = tokens[_tokenId];
return (
token.productCode,
string(abi.encodePacked(token.productCode, "-", Strings.fromUint256(_tokenId))),
string(abi.encodePacked(tokenBaseURI, token.ipfsHash))
);
}
function productCode(uint256 _tokenId)
external
onlyWhenTokenExists(_tokenId) view returns (string memory _productCode) {
Token storage token = tokens[_tokenId];
return token.productCode;
}
function productId(uint256 _tokenId)
external
onlyWhenTokenExists(_tokenId) view returns (string memory _productId) {
Token storage token = tokens[_tokenId];
return string(abi.encodePacked(token.productCode, "-", Strings.fromUint256(_tokenId)));
}
function tokenIdForProductId(string calldata _productId)
external
view returns (uint256 _tokenId) {
return productIdToTokenId[_productId];
}
function tokenURI(uint256 _tokenId)
external
onlyWhenTokenExists(_tokenId) view returns (string memory) {
return string(abi.encodePacked(tokenBaseURI, tokens[_tokenId].ipfsHash));
}
function tokensOfOwner(address owner)
external
view returns (uint256[] memory) {
return _tokensOfOwner(owner);
}
function updateProductCode(uint256 _tokenId, string calldata _productCode)
external
onlyWhitelisted onlyWhenTokenExists(_tokenId) {
Token storage token = tokens[_tokenId];
token.productCode = _productCode;
productIdToTokenId[string(abi.encodePacked(_productCode, "-", Strings.fromUint256(_tokenId)))] = _tokenId;
}
function updateIpfsHash(uint256 _tokenId, string calldata _newIpfsHash)
external
onlyWhitelisted onlyWhenTokenExists(_tokenId) {
require(bytes(_newIpfsHash).length != 0, "New IPFS hash invalid");
tokens[_tokenId].ipfsHash = _newIpfsHash;
}
function updateTokenBaseURI(string calldata _newBaseURI)
external
onlyWhitelistAdmin {
require(bytes(_newBaseURI).length != 0, "Base URI invalid");
tokenBaseURI = _newBaseURI;
}
/**
* @dev Burns a specific token.
* @dev Only callable from whitelisted address
* @param _tokenId uint256 id of the token to be burned.
*/
function burn(uint256 _tokenId)
public
onlyWhitelistAdmin onlyWhenTokenExists(_tokenId) {
// Clean up product ID mapping
Token storage token = tokens[_tokenId];
delete productIdToTokenId[string(abi.encodePacked(token.productCode, "-", Strings.fromUint256(_tokenId)))];
_burn(_tokenId);
}
}
|
See `IRelayRecipient.preRelayedCall`. Called by `GSNRecipient.preRelayedCall`, which asserts the caller is the `RelayHub` contract. Derived contracts must implement this function with any relayed-call preprocessing they may wish to do./ See `IRelayRecipient.postRelayedCall`. This function should not be overriden directly, use `_postRelayedCall` instead. Requirements: - the caller must be the `RelayHub` contract./
|
function _preRelayedCall(bytes memory context) internal returns (bytes32);
function postRelayedCall(bytes calldata context, bool success, uint256 actualCharge, bytes32 preRetVal) external {
require(msg.sender == getHubAddr(), "GSNRecipient: caller is not RelayHub");
_postRelayedCall(context, success, actualCharge, preRetVal);
}
| 1,014,295
|
//Address: 0xb8bf73550f251562d308882e032225a700a7b9bc
//Contract name: DWorldCore
//Balance: 0 Ether
//Verification Date: 2/3/2018
//Transacion Count: 7
// CODE STARTS HERE
pragma solidity ^0.4.18;
/**
* @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));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @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 Claimable is Ownable {
address public pendingOwner;
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() onlyPendingOwner public {
OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
/**
* @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 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 view 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 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);
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* 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 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
/**
* @title Contracts that should be able to recover tokens
* @author SylTi
* @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner.
* This will prevent any accidental loss of tokens.
*/
contract CanReclaimToken is Ownable {
using SafeERC20 for ERC20Basic;
/**
* @dev Reclaim all ERC20Basic compatible tokens
* @param token ERC20Basic The address of the token contract
*/
function reclaimToken(ERC20Basic token) external onlyOwner {
uint256 balance = token.balanceOf(this);
token.safeTransfer(owner, balance);
}
}
/// @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 Metadata extension to ERC-721 interface
/// @author William Entriken (https://phor.net)
/// @dev Specification at https://github.com/ethereum/EIPs/pull/841 (DRAFT)
interface ERC721Metadata {
/// @dev ERC-165 (draft) interface signature for ERC721
// bytes4 internal constant INTERFACE_SIGNATURE_ERC721Metadata = // 0x2a786f11
// bytes4(keccak256('name()')) ^
// bytes4(keccak256('symbol()')) ^
// bytes4(keccak256('deedUri(uint256)'));
/// @notice A descriptive name for a collection of deeds managed by this
/// contract
/// @dev Wallets and exchanges MAY display this to the end user.
function name() public pure returns (string _deedName);
/// @notice An abbreviated name for deeds managed by this contract
/// @dev Wallets and exchanges MAY display this to the end user.
function symbol() public pure returns (string _deedSymbol);
/// @notice A distinct URI (RFC 3986) for a given token.
/// @dev If:
/// * The URI is a URL
/// * The URL is accessible
/// * The URL points to a valid JSON file format (ECMA-404 2nd ed.)
/// * The JSON base element is an object
/// then these names of the base element SHALL have special meaning:
/// * "name": A string identifying the item to which `_deedId` grants
/// ownership
/// * "description": A string detailing the item to which `_deedId` grants
/// ownership
/// * "image": A URI pointing to a file of image/* mime type representing
/// the item to which `_deedId` grants ownership
/// Wallets and exchanges MAY display this to the end user.
/// Consider making any images at a width between 320 and 1080 pixels and
/// aspect ratio between 1.91:1 and 4:5 inclusive.
function deedUri(uint256 _deedId) external pure returns (string _uri);
}
/// @dev Implements access control to the DWorld contract.
contract DWorldAccessControl is Claimable, Pausable, CanReclaimToken {
address public cfoAddress;
function DWorldAccessControl() public {
// The creator of the contract is the initial CFO.
cfoAddress = msg.sender;
}
/// @dev Access modifier for CFO-only functionality.
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
/// @dev Assigns a new address to act as the CFO. Only available to the current contract owner.
/// @param _newCFO The address of the new CFO.
function setCFO(address _newCFO) external onlyOwner {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
}
/// @dev Defines base data structures for DWorld.
contract DWorldBase is DWorldAccessControl {
using SafeMath for uint256;
/// @dev All minted plots (array of plot identifiers). There are
/// 2^16 * 2^16 possible plots (covering the entire world), thus
/// 32 bits are required. This fits in a uint32. Storing
/// the identifiers as uint32 instead of uint256 makes storage
/// cheaper. (The impact of this in mappings is less noticeable,
/// and using uint32 in the mappings below actually *increases*
/// gas cost for minting).
uint32[] public plots;
mapping (uint256 => address) identifierToOwner;
mapping (uint256 => address) identifierToApproved;
mapping (address => uint256) ownershipDeedCount;
// Boolean indicating whether the plot was bought before the migration.
mapping (uint256 => bool) public identifierIsOriginal;
/// @dev Event fired when a plot's data are changed. The plot
/// data are not stored in the contract directly, instead the
/// data are logged to the block. This gives significant
/// reductions in gas requirements (~75k for minting with data
/// instead of ~180k). However, it also means plot data are
/// not available from *within* other contracts.
event SetData(uint256 indexed deedId, string name, string description, string imageUrl, string infoUrl);
/// @notice Get all minted plots.
function getAllPlots() external view returns(uint32[]) {
return plots;
}
/// @dev Represent a 2D coordinate as a single uint.
/// @param x The x-coordinate.
/// @param y The y-coordinate.
function coordinateToIdentifier(uint256 x, uint256 y) public pure returns(uint256) {
require(validCoordinate(x, y));
return (y << 16) + x;
}
/// @dev Turn a single uint representation of a coordinate into its x and y parts.
/// @param identifier The uint representation of a coordinate.
function identifierToCoordinate(uint256 identifier) public pure returns(uint256 x, uint256 y) {
require(validIdentifier(identifier));
y = identifier >> 16;
x = identifier - (y << 16);
}
/// @dev Test whether the coordinate is valid.
/// @param x The x-part of the coordinate to test.
/// @param y The y-part of the coordinate to test.
function validCoordinate(uint256 x, uint256 y) public pure returns(bool) {
return x < 65536 && y < 65536; // 2^16
}
/// @dev Test whether an identifier is valid.
/// @param identifier The identifier to test.
function validIdentifier(uint256 identifier) public pure returns(bool) {
return identifier < 4294967296; // 2^16 * 2^16
}
/// @dev Set a plot's data.
/// @param identifier The identifier of the plot to set data for.
function _setPlotData(uint256 identifier, string name, string description, string imageUrl, string infoUrl) internal {
SetData(identifier, name, description, imageUrl, infoUrl);
}
}
/// @dev Holds deed functionality such as approving and transferring. Implements ERC721.
contract DWorldDeed is DWorldBase, ERC721, ERC721Metadata {
/// @notice Name of the collection of deeds (non-fungible token), as defined in ERC721Metadata.
function name() public pure returns (string _deedName) {
_deedName = "DWorld Plots";
}
/// @notice Symbol of the collection of deeds (non-fungible token), as defined in ERC721Metadata.
function symbol() public pure returns (string _deedSymbol) {
_deedSymbol = "DWP";
}
/// @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)'));
/// @dev ERC-165 (draft) interface signature for ERC721
bytes4 internal constant INTERFACE_SIGNATURE_ERC721Metadata = // 0x2a786f11
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('deedUri(uint256)'));
/// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
/// Returns true for any standardized interfaces implemented by this contract.
/// (ERC-165 and ERC-721.)
function supportsInterface(bytes4 _interfaceID) external pure returns (bool) {
return (
(_interfaceID == INTERFACE_SIGNATURE_ERC165)
|| (_interfaceID == INTERFACE_SIGNATURE_ERC721)
|| (_interfaceID == INTERFACE_SIGNATURE_ERC721Metadata)
);
}
/// @dev Checks if a given address owns a particular plot.
/// @param _owner The address of the owner to check for.
/// @param _deedId The plot identifier to check for.
function _owns(address _owner, uint256 _deedId) internal view returns (bool) {
return identifierToOwner[_deedId] == _owner;
}
/// @dev Approve a given address to take ownership of a deed.
/// @param _from The address approving taking ownership.
/// @param _to The address to approve taking ownership.
/// @param _deedId The identifier of the deed to give approval for.
function _approve(address _from, address _to, uint256 _deedId) internal {
identifierToApproved[_deedId] = _to;
// Emit event.
Approval(_from, _to, _deedId);
}
/// @dev Checks if a given address has approval to take ownership of a deed.
/// @param _claimant The address of the claimant to check for.
/// @param _deedId The identifier of the deed to check for.
function _approvedFor(address _claimant, uint256 _deedId) internal view returns (bool) {
return identifierToApproved[_deedId] == _claimant;
}
/// @dev Assigns ownership of a specific deed to an address.
/// @param _from The address to transfer the deed from.
/// @param _to The address to transfer the deed to.
/// @param _deedId The identifier of the deed to transfer.
function _transfer(address _from, address _to, uint256 _deedId) internal {
// The number of plots is capped at 2^16 * 2^16, so this cannot
// be overflowed.
ownershipDeedCount[_to]++;
// Transfer ownership.
identifierToOwner[_deedId] = _to;
// When a new deed is minted, the _from address is 0x0, but we
// do not track deed ownership of 0x0.
if (_from != address(0)) {
ownershipDeedCount[_from]--;
// Clear taking ownership approval.
delete identifierToApproved[_deedId];
}
// Emit the transfer event.
Transfer(_from, _to, _deedId);
}
// ERC 721 implementation
/// @notice Returns the total number of deeds currently in existence.
/// @dev Required for ERC-721 compliance.
function countOfDeeds() public view returns (uint256) {
return plots.length;
}
/// @notice Returns the number of deeds owned by a specific address.
/// @param _owner The owner address to check.
/// @dev Required for ERC-721 compliance
function countOfDeedsByOwner(address _owner) public view returns (uint256) {
return ownershipDeedCount[_owner];
}
/// @notice Returns the address currently assigned ownership of a given deed.
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _deedId) external view returns (address _owner) {
_owner = identifierToOwner[_deedId];
require(_owner != address(0));
}
/// @notice Approve a given address to take ownership of a deed.
/// @param _to The address to approve taking owernship.
/// @param _deedId The identifier of the deed to give approval for.
/// @dev Required for ERC-721 compliance.
function approve(address _to, uint256 _deedId) external whenNotPaused {
uint256[] memory _deedIds = new uint256[](1);
_deedIds[0] = _deedId;
approveMultiple(_to, _deedIds);
}
/// @notice Approve a given address to take ownership of multiple deeds.
/// @param _to The address to approve taking ownership.
/// @param _deedIds The identifiers of the deeds to give approval for.
function approveMultiple(address _to, uint256[] _deedIds) public whenNotPaused {
// Ensure the sender is not approving themselves.
require(msg.sender != _to);
for (uint256 i = 0; i < _deedIds.length; i++) {
uint256 _deedId = _deedIds[i];
// Require the sender is the owner of the deed.
require(_owns(msg.sender, _deedId));
// Perform the approval.
_approve(msg.sender, _to, _deedId);
}
}
/// @notice Transfer a deed to another address. If transferring to a smart
/// contract be VERY CAREFUL to ensure that it is aware of ERC-721, or your
/// deed may be lost forever.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _deedId The identifier of the deed to transfer.
/// @dev Required for ERC-721 compliance.
function transfer(address _to, uint256 _deedId) external whenNotPaused {
uint256[] memory _deedIds = new uint256[](1);
_deedIds[0] = _deedId;
transferMultiple(_to, _deedIds);
}
/// @notice Transfers multiple deeds to another address. If transferring to
/// a smart contract be VERY CAREFUL to ensure that it is aware of ERC-721,
/// or your deeds may be lost forever.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _deedIds The identifiers of the deeds to transfer.
function transferMultiple(address _to, uint256[] _deedIds) public whenNotPaused {
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
require(_to != address(this));
for (uint256 i = 0; i < _deedIds.length; i++) {
uint256 _deedId = _deedIds[i];
// One can only transfer their own plots.
require(_owns(msg.sender, _deedId));
// Transfer ownership
_transfer(msg.sender, _to, _deedId);
}
}
/// @notice Transfer a deed owned by another address, for which the calling
/// address has previously been granted transfer approval by the owner.
/// @param _deedId The identifier of the deed to be transferred.
/// @dev Required for ERC-721 compliance.
function takeOwnership(uint256 _deedId) external whenNotPaused {
uint256[] memory _deedIds = new uint256[](1);
_deedIds[0] = _deedId;
takeOwnershipMultiple(_deedIds);
}
/// @notice Transfer multiple deeds owned by another address, for which the
/// calling address has previously been granted transfer approval by the owner.
/// @param _deedIds The identifier of the deed to be transferred.
function takeOwnershipMultiple(uint256[] _deedIds) public whenNotPaused {
for (uint256 i = 0; i < _deedIds.length; i++) {
uint256 _deedId = _deedIds[i];
address _from = identifierToOwner[_deedId];
// Check for transfer approval
require(_approvedFor(msg.sender, _deedId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transfer(_from, msg.sender, _deedId);
}
}
/// @notice Returns a list of all deed identifiers assigned to an address.
/// @param _owner The owner whose deeds we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. It's very
/// expensive and is not supported in contract-to-contract calls as it returns
/// a dynamic array (only supported for web3 calls).
function deedsOfOwner(address _owner) external view returns(uint256[]) {
uint256 deedCount = countOfDeedsByOwner(_owner);
if (deedCount == 0) {
// Return an empty array.
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](deedCount);
uint256 totalDeeds = countOfDeeds();
uint256 resultIndex = 0;
for (uint256 deedNumber = 0; deedNumber < totalDeeds; deedNumber++) {
uint256 identifier = plots[deedNumber];
if (identifierToOwner[identifier] == _owner) {
result[resultIndex] = identifier;
resultIndex++;
}
}
return result;
}
}
/// @notice Returns a deed identifier of the owner at the given index.
/// @param _owner The address of the owner we want to get a deed for.
/// @param _index The index of the deed we want.
function deedOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256) {
// The index should be valid.
require(_index < countOfDeedsByOwner(_owner));
// Loop through all plots, accounting the number of plots of the owner we've seen.
uint256 seen = 0;
uint256 totalDeeds = countOfDeeds();
for (uint256 deedNumber = 0; deedNumber < totalDeeds; deedNumber++) {
uint256 identifier = plots[deedNumber];
if (identifierToOwner[identifier] == _owner) {
if (seen == _index) {
return identifier;
}
seen++;
}
}
}
/// @notice Returns an (off-chain) metadata url for the given deed.
/// @param _deedId The identifier of the deed to get the metadata
/// url for.
/// @dev Implementation of optional ERC-721 functionality.
function deedUri(uint256 _deedId) external pure returns (string uri) {
require(validIdentifier(_deedId));
var (x, y) = identifierToCoordinate(_deedId);
// Maximum coordinate length in decimals is 5 (65535)
uri = "https://dworld.io/plot/xxxxx/xxxxx";
bytes memory _uri = bytes(uri);
for (uint256 i = 0; i < 5; i++) {
_uri[27 - i] = byte(48 + (x / 10 ** i) % 10);
_uri[33 - i] = byte(48 + (y / 10 ** i) % 10);
}
}
}
/// @dev Holds functionality for finance related to plots.
contract DWorldFinance is DWorldDeed {
/// 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;
/// Base price for unclaimed plots.
uint256 public unclaimedPlotPrice = 0.0125 ether;
/// Dividend per plot surrounding a new claim, in 1/1000th of percentages
/// of the base unclaimed plot price.
uint256 public claimDividendPercentage = 50000;
/// Percentage of the buyout price that goes towards dividends.
uint256 public buyoutDividendPercentage = 5000;
/// Buyout fee in 1/1000th of a percentage.
uint256 public buyoutFeePercentage = 3500;
/// Number of free claims per address.
mapping (address => uint256) freeClaimAllowance;
/// Initial price paid for a plot.
mapping (uint256 => uint256) public initialPricePaid;
/// Current plot price.
mapping (uint256 => uint256) public identifierToBuyoutPrice;
/// Boolean indicating whether the plot has been bought out at least once.
mapping (uint256 => bool) identifierToBoughtOutOnce;
/// @dev Event fired when dividend is paid for a new plot claim.
event ClaimDividend(address indexed from, address indexed to, uint256 deedIdFrom, uint256 indexed deedIdTo, uint256 dividend);
/// @dev Event fired when a buyout is performed.
event Buyout(address indexed buyer, address indexed seller, uint256 indexed deedId, uint256 winnings, uint256 totalCost, uint256 newPrice);
/// @dev Event fired when dividend is paid for a buyout.
event BuyoutDividend(address indexed from, address indexed to, uint256 deedIdFrom, uint256 indexed deedIdTo, uint256 dividend);
/// @dev Event fired when the buyout price is manually changed for a plot.
event SetBuyoutPrice(uint256 indexed deedId, uint256 newPrice);
/// @dev The time after which buyouts will be enabled. Set in the DWorldCore constructor.
uint256 public buyoutsEnabledFromTimestamp;
/// @notice Sets the new price for unclaimed plots.
/// @param _unclaimedPlotPrice The new price for unclaimed plots.
function setUnclaimedPlotPrice(uint256 _unclaimedPlotPrice) external onlyCFO {
unclaimedPlotPrice = _unclaimedPlotPrice;
}
/// @notice Sets the new dividend percentage for unclaimed plots.
/// @param _claimDividendPercentage The new dividend percentage for unclaimed plots.
function setClaimDividendPercentage(uint256 _claimDividendPercentage) external onlyCFO {
// Claim dividend percentage must be 10% at the least.
// Claim dividend percentage may be 100% at the most.
require(10000 <= _claimDividendPercentage && _claimDividendPercentage <= 100000);
claimDividendPercentage = _claimDividendPercentage;
}
/// @notice Sets the new dividend percentage for buyouts.
/// @param _buyoutDividendPercentage The new dividend percentage for buyouts.
function setBuyoutDividendPercentage(uint256 _buyoutDividendPercentage) external onlyCFO {
// Buyout dividend must be 2% at the least.
// Buyout dividend percentage may be 12.5% at the most.
require(2000 <= _buyoutDividendPercentage && _buyoutDividendPercentage <= 12500);
buyoutDividendPercentage = _buyoutDividendPercentage;
}
/// @notice Sets the new fee percentage for buyouts.
/// @param _buyoutFeePercentage The new fee percentage for buyouts.
function setBuyoutFeePercentage(uint256 _buyoutFeePercentage) external onlyCFO {
// Buyout fee may be 5% at the most.
require(0 <= _buyoutFeePercentage && _buyoutFeePercentage <= 5000);
buyoutFeePercentage = _buyoutFeePercentage;
}
/// @notice The claim dividend to be paid for each adjacent plot, and
/// as a flat dividend for each buyout.
function claimDividend() public view returns (uint256) {
return unclaimedPlotPrice.mul(claimDividendPercentage).div(100000);
}
/// @notice Set the free claim allowance for an address.
/// @param addr The address to set the free claim allowance for.
/// @param allowance The free claim allowance to set.
function setFreeClaimAllowance(address addr, uint256 allowance) external onlyCFO {
freeClaimAllowance[addr] = allowance;
}
/// @notice Get the free claim allowance of an address.
/// @param addr The address to get the free claim allowance of.
function freeClaimAllowanceOf(address addr) external view returns (uint256) {
return freeClaimAllowance[addr];
}
/// @dev Assign balance to an account.
/// @param addr The address to assign balance to.
/// @param amount The amount to assign.
function _assignBalance(address addr, uint256 amount) internal {
addressToEtherOwed[addr] = addressToEtherOwed[addr].add(amount);
outstandingEther = outstandingEther.add(amount);
}
/// @dev Find the _claimed_ plots surrounding a plot.
/// @param _deedId The identifier of the plot to get the surrounding plots for.
function _claimedSurroundingPlots(uint256 _deedId) internal view returns (uint256[] memory) {
var (x, y) = identifierToCoordinate(_deedId);
// Find all claimed surrounding plots.
uint256 claimed = 0;
// Create memory buffer capable of holding all plots.
uint256[] memory _plots = new uint256[](8);
// Loop through all neighbors.
for (int256 dx = -1; dx <= 1; dx++) {
for (int256 dy = -1; dy <= 1; dy++) {
if (dx == 0 && dy == 0) {
// Skip the center (i.e., the plot itself).
continue;
}
// Get the coordinates of this neighboring identifier.
uint256 neighborIdentifier = coordinateToIdentifier(
uint256(int256(x) + dx) % 65536,
uint256(int256(y) + dy) % 65536
);
if (identifierToOwner[neighborIdentifier] != 0x0) {
_plots[claimed] = neighborIdentifier;
claimed++;
}
}
}
// Memory arrays cannot be resized, so copy all
// plots from the buffer to the plot array.
uint256[] memory plots = new uint256[](claimed);
for (uint256 i = 0; i < claimed; i++) {
plots[i] = _plots[i];
}
return plots;
}
/// @dev Assign claim dividend to an address.
/// @param _from The address who paid the dividend.
/// @param _to The dividend beneficiary.
/// @param _deedIdFrom The identifier of the deed the dividend is being paid for.
/// @param _deedIdTo The identifier of the deed the dividend is being paid to.
function _assignClaimDividend(address _from, address _to, uint256 _deedIdFrom, uint256 _deedIdTo) internal {
uint256 _claimDividend = claimDividend();
// Trigger event.
ClaimDividend(_from, _to, _deedIdFrom, _deedIdTo, _claimDividend);
// Assign the dividend.
_assignBalance(_to, _claimDividend);
}
/// @dev Calculate and assign the dividend payable for the new plot claim.
/// A new claim pays dividends to all existing surrounding plots.
/// @param _deedId The identifier of the new plot to calculate and assign dividends for.
/// Assumed to be valid.
function _calculateAndAssignClaimDividends(uint256 _deedId)
internal
returns (uint256 totalClaimDividend)
{
// Get existing surrounding plots.
uint256[] memory claimedSurroundingPlots = _claimedSurroundingPlots(_deedId);
// Keep track of the claim dividend.
uint256 _claimDividend = claimDividend();
totalClaimDividend = 0;
// Assign claim dividend.
for (uint256 i = 0; i < claimedSurroundingPlots.length; i++) {
if (identifierToOwner[claimedSurroundingPlots[i]] != msg.sender) {
totalClaimDividend = totalClaimDividend.add(_claimDividend);
_assignClaimDividend(msg.sender, identifierToOwner[claimedSurroundingPlots[i]], _deedId, claimedSurroundingPlots[i]);
}
}
}
/// @dev Calculate the next buyout price given the current total buyout cost.
/// @param totalCost The current total buyout cost.
function nextBuyoutPrice(uint256 totalCost) public pure returns (uint256) {
if (totalCost < 0.05 ether) {
return totalCost * 2;
} else if (totalCost < 0.2 ether) {
return totalCost * 170 / 100; // * 1.7
} else if (totalCost < 0.5 ether) {
return totalCost * 150 / 100; // * 1.5
} else {
return totalCost.mul(125).div(100); // * 1.25
}
}
/// @notice Get the buyout cost for a given plot.
/// @param _deedId The identifier of the plot to get the buyout cost for.
function buyoutCost(uint256 _deedId) external view returns (uint256) {
// The current buyout price.
uint256 price = identifierToBuyoutPrice[_deedId];
// Get existing surrounding plots.
uint256[] memory claimedSurroundingPlots = _claimedSurroundingPlots(_deedId);
// The total cost is the price plus flat rate dividends based on claim dividends.
uint256 flatDividends = claimDividend().mul(claimedSurroundingPlots.length);
return price.add(flatDividends);
}
/// @dev Assign the proceeds of the buyout.
/// @param _deedId The identifier of the plot that is being bought out.
function _assignBuyoutProceeds(
address currentOwner,
uint256 _deedId,
uint256[] memory claimedSurroundingPlots,
uint256 currentOwnerWinnings,
uint256 totalDividendPerBeneficiary,
uint256 totalCost
)
internal
{
// Calculate and assign the current owner's winnings.
Buyout(msg.sender, currentOwner, _deedId, currentOwnerWinnings, totalCost, nextBuyoutPrice(totalCost));
_assignBalance(currentOwner, currentOwnerWinnings);
// Assign dividends to owners of surrounding plots.
for (uint256 i = 0; i < claimedSurroundingPlots.length; i++) {
address beneficiary = identifierToOwner[claimedSurroundingPlots[i]];
BuyoutDividend(msg.sender, beneficiary, _deedId, claimedSurroundingPlots[i], totalDividendPerBeneficiary);
_assignBalance(beneficiary, totalDividendPerBeneficiary);
}
}
/// @dev Calculate and assign the proceeds from the buyout.
/// @param currentOwner The current owner of the plot that is being bought out.
/// @param _deedId The identifier of the plot that is being bought out.
/// @param claimedSurroundingPlots The surrounding plots that have been claimed.
function _calculateAndAssignBuyoutProceeds(address currentOwner, uint256 _deedId, uint256[] memory claimedSurroundingPlots)
internal
returns (uint256 totalCost)
{
// The current price.
uint256 price = identifierToBuyoutPrice[_deedId];
// The total cost is the price plus flat rate dividends based on claim dividends.
uint256 flatDividends = claimDividend().mul(claimedSurroundingPlots.length);
totalCost = price.add(flatDividends);
// Calculate the variable dividends based on the buyout price
// (only to be paid if there are surrounding plots).
uint256 variableDividends = price.mul(buyoutDividendPercentage).div(100000);
// Calculate fees.
uint256 fee = price.mul(buyoutFeePercentage).div(100000);
// Calculate and assign buyout proceeds.
uint256 currentOwnerWinnings = price.sub(fee);
uint256 totalDividendPerBeneficiary;
if (claimedSurroundingPlots.length > 0) {
// If there are surrounding plots, variable dividend is to be paid
// based on the buyout price..
currentOwnerWinnings = currentOwnerWinnings.sub(variableDividends);
// Calculate the dividend per surrounding plot.
totalDividendPerBeneficiary = flatDividends.add(variableDividends) / claimedSurroundingPlots.length;
}
_assignBuyoutProceeds(
currentOwner,
_deedId,
claimedSurroundingPlots,
currentOwnerWinnings,
totalDividendPerBeneficiary,
totalCost
);
}
/// @notice Buy the current owner out of the plot.
function buyout(uint256 _deedId) external payable whenNotPaused {
buyoutWithData(_deedId, "", "", "", "");
}
/// @notice Buy the current owner out of the plot.
function buyoutWithData(uint256 _deedId, string name, string description, string imageUrl, string infoUrl)
public
payable
whenNotPaused
{
// Buyouts must be enabled.
require(buyoutsEnabledFromTimestamp <= block.timestamp);
address currentOwner = identifierToOwner[_deedId];
// The plot must be owned before it can be bought out.
require(currentOwner != 0x0);
// Get existing surrounding plots.
uint256[] memory claimedSurroundingPlots = _claimedSurroundingPlots(_deedId);
// Assign the buyout proceeds and retrieve the total cost.
uint256 totalCost = _calculateAndAssignBuyoutProceeds(currentOwner, _deedId, claimedSurroundingPlots);
// Ensure the message has enough value.
require(msg.value >= totalCost);
// Transfer the plot.
_transfer(currentOwner, msg.sender, _deedId);
// Set the plot data
SetData(_deedId, name, description, imageUrl, infoUrl);
// Calculate and set the new plot price.
identifierToBuyoutPrice[_deedId] = nextBuyoutPrice(totalCost);
// Indicate the plot has been bought out at least once
if (!identifierToBoughtOutOnce[_deedId]) {
identifierToBoughtOutOnce[_deedId] = true;
}
// Calculate the excess Ether sent.
// msg.value is greater than or equal to totalCost,
// so this cannot underflow.
uint256 excess = msg.value - totalCost;
if (excess > 0) {
// Refund any excess Ether (not susceptible to re-entry attack, as
// the owner is assigned before the transfer takes place).
msg.sender.transfer(excess);
}
}
/// @notice Calculate the maximum initial buyout price for a plot.
/// @param _deedId The identifier of the plot to get the maximum initial buyout price for.
function maximumInitialBuyoutPrice(uint256 _deedId) public view returns (uint256) {
// The initial buyout price can be set to 4x the initial plot price
// (or 100x for the original pre-migration plots).
uint256 mul = 4;
if (identifierIsOriginal[_deedId]) {
mul = 100;
}
return initialPricePaid[_deedId].mul(mul);
}
/// @notice Test whether a buyout price is valid.
/// @param _deedId The identifier of the plot to test the buyout price for.
/// @param price The buyout price to test.
function validInitialBuyoutPrice(uint256 _deedId, uint256 price) public view returns (bool) {
return (price >= unclaimedPlotPrice && price <= maximumInitialBuyoutPrice(_deedId));
}
/// @notice Manually set the initial buyout price of a plot.
/// @param _deedId The identifier of the plot to set the buyout price for.
/// @param price The value to set the buyout price to.
function setInitialBuyoutPrice(uint256 _deedId, uint256 price) public whenNotPaused {
// One can only set the buyout price of their own plots.
require(_owns(msg.sender, _deedId));
// The initial buyout price can only be set if the plot has never been bought out before.
require(!identifierToBoughtOutOnce[_deedId]);
// The buyout price must be valid.
require(validInitialBuyoutPrice(_deedId, price));
// Set the buyout price.
identifierToBuyoutPrice[_deedId] = price;
// Trigger the buyout price event.
SetBuyoutPrice(_deedId, price);
}
}
/// @dev Holds functionality for minting new plot deeds.
contract DWorldMinting is DWorldFinance {
/// @notice Buy an unclaimed plot.
/// @param _deedId The unclaimed plot to buy.
/// @param _buyoutPrice The initial buyout price to set on the plot.
function claimPlot(uint256 _deedId, uint256 _buyoutPrice) external payable whenNotPaused {
claimPlotWithData(_deedId, _buyoutPrice, "", "", "", "");
}
/// @notice Buy an unclaimed plot.
/// @param _deedId The unclaimed plot to buy.
/// @param _buyoutPrice The initial buyout price to set on the plot.
/// @param name The name to give the plot.
/// @param description The description to add to the plot.
/// @param imageUrl The image url for the plot.
/// @param infoUrl The info url for the plot.
function claimPlotWithData(uint256 _deedId, uint256 _buyoutPrice, string name, string description, string imageUrl, string infoUrl) public payable whenNotPaused {
uint256[] memory _deedIds = new uint256[](1);
_deedIds[0] = _deedId;
claimPlotMultipleWithData(_deedIds, _buyoutPrice, name, description, imageUrl, infoUrl);
}
/// @notice Buy unclaimed plots.
/// @param _deedIds The unclaimed plots to buy.
/// @param _buyoutPrice The initial buyout price to set on the plot.
function claimPlotMultiple(uint256[] _deedIds, uint256 _buyoutPrice) external payable whenNotPaused {
claimPlotMultipleWithData(_deedIds, _buyoutPrice, "", "", "", "");
}
/// @notice Buy unclaimed plots.
/// @param _deedIds The unclaimed plots to buy.
/// @param _buyoutPrice The initial buyout price to set on the plot.
/// @param name The name to give the plots.
/// @param description The description to add to the plots.
/// @param imageUrl The image url for the plots.
/// @param infoUrl The info url for the plots.
function claimPlotMultipleWithData(uint256[] _deedIds, uint256 _buyoutPrice, string name, string description, string imageUrl, string infoUrl) public payable whenNotPaused {
uint256 buyAmount = _deedIds.length;
uint256 etherRequired;
if (freeClaimAllowance[msg.sender] > 0) {
// The sender has a free claim allowance.
if (freeClaimAllowance[msg.sender] > buyAmount) {
// Subtract from allowance.
freeClaimAllowance[msg.sender] -= buyAmount;
// No ether is required.
etherRequired = 0;
} else {
uint256 freeAmount = freeClaimAllowance[msg.sender];
// The full allowance has been used.
delete freeClaimAllowance[msg.sender];
// The subtraction cannot underflow, as freeAmount <= buyAmount.
etherRequired = unclaimedPlotPrice.mul(buyAmount - freeAmount);
}
} else {
// The sender does not have a free claim allowance.
etherRequired = unclaimedPlotPrice.mul(buyAmount);
}
uint256 offset = plots.length;
// Allocate additional memory for the plots array
// (this is more efficient than .push-ing each individual
// plot, as that requires multiple dynamic allocations).
plots.length = plots.length.add(_deedIds.length);
for (uint256 i = 0; i < _deedIds.length; i++) {
uint256 _deedId = _deedIds[i];
require(validIdentifier(_deedId));
// The plot must be unowned (a plot deed cannot be transferred to
// 0x0, so once a plot is claimed it will always be owned by a
// non-zero address).
require(identifierToOwner[_deedId] == address(0));
// Create the plot
plots[offset + i] = uint32(_deedId);
// Transfer the new plot to the sender.
_transfer(address(0), msg.sender, _deedId);
// Set the plot data.
_setPlotData(_deedId, name, description, imageUrl, infoUrl);
// Calculate and assign claim dividends.
uint256 claimDividends = _calculateAndAssignClaimDividends(_deedId);
etherRequired = etherRequired.add(claimDividends);
// Set the initial price paid for the plot.
initialPricePaid[_deedId] = unclaimedPlotPrice.add(claimDividends);
// Set the initial buyout price. Throws if it does not succeed.
setInitialBuyoutPrice(_deedId, _buyoutPrice);
}
// Ensure enough ether is supplied.
require(msg.value >= etherRequired);
// Calculate the excess ether sent
// msg.value is greater than or equal to etherRequired,
// so this cannot underflow.
uint256 excess = msg.value - etherRequired;
if (excess > 0) {
// Refund any excess ether (not susceptible to re-entry attack, as
// the owner is assigned before the transfer takes place).
msg.sender.transfer(excess);
}
}
}
/// @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);
}
}
/// @dev Defines base data structures for DWorld.
contract OriginalDWorldBase is DWorldAccessControl {
using SafeMath for uint256;
/// @dev All minted plots (array of plot identifiers). There are
/// 2^16 * 2^16 possible plots (covering the entire world), thus
/// 32 bits are required. This fits in a uint32. Storing
/// the identifiers as uint32 instead of uint256 makes storage
/// cheaper. (The impact of this in mappings is less noticeable,
/// and using uint32 in the mappings below actually *increases*
/// gas cost for minting).
uint32[] public plots;
mapping (uint256 => address) identifierToOwner;
mapping (uint256 => address) identifierToApproved;
mapping (address => uint256) ownershipDeedCount;
/// @dev Event fired when a plot's data are changed. The plot
/// data are not stored in the contract directly, instead the
/// data are logged to the block. This gives significant
/// reductions in gas requirements (~75k for minting with data
/// instead of ~180k). However, it also means plot data are
/// not available from *within* other contracts.
event SetData(uint256 indexed deedId, string name, string description, string imageUrl, string infoUrl);
/// @notice Get all minted plots.
function getAllPlots() external view returns(uint32[]) {
return plots;
}
/// @dev Represent a 2D coordinate as a single uint.
/// @param x The x-coordinate.
/// @param y The y-coordinate.
function coordinateToIdentifier(uint256 x, uint256 y) public pure returns(uint256) {
require(validCoordinate(x, y));
return (y << 16) + x;
}
/// @dev Turn a single uint representation of a coordinate into its x and y parts.
/// @param identifier The uint representation of a coordinate.
function identifierToCoordinate(uint256 identifier) public pure returns(uint256 x, uint256 y) {
require(validIdentifier(identifier));
y = identifier >> 16;
x = identifier - (y << 16);
}
/// @dev Test whether the coordinate is valid.
/// @param x The x-part of the coordinate to test.
/// @param y The y-part of the coordinate to test.
function validCoordinate(uint256 x, uint256 y) public pure returns(bool) {
return x < 65536 && y < 65536; // 2^16
}
/// @dev Test whether an identifier is valid.
/// @param identifier The identifier to test.
function validIdentifier(uint256 identifier) public pure returns(bool) {
return identifier < 4294967296; // 2^16 * 2^16
}
/// @dev Set a plot's data.
/// @param identifier The identifier of the plot to set data for.
function _setPlotData(uint256 identifier, string name, string description, string imageUrl, string infoUrl) internal {
SetData(identifier, name, description, imageUrl, infoUrl);
}
}
/// @dev Holds deed functionality such as approving and transferring. Implements ERC721.
contract OriginalDWorldDeed is OriginalDWorldBase, ERC721, ERC721Metadata {
/// @notice Name of the collection of deeds (non-fungible token), as defined in ERC721Metadata.
function name() public pure returns (string _deedName) {
_deedName = "DWorld Plots";
}
/// @notice Symbol of the collection of deeds (non-fungible token), as defined in ERC721Metadata.
function symbol() public pure returns (string _deedSymbol) {
_deedSymbol = "DWP";
}
/// @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)'));
/// @dev ERC-165 (draft) interface signature for ERC721
bytes4 internal constant INTERFACE_SIGNATURE_ERC721Metadata = // 0x2a786f11
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('deedUri(uint256)'));
/// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
/// Returns true for any standardized interfaces implemented by this contract.
/// (ERC-165 and ERC-721.)
function supportsInterface(bytes4 _interfaceID) external pure returns (bool) {
return (
(_interfaceID == INTERFACE_SIGNATURE_ERC165)
|| (_interfaceID == INTERFACE_SIGNATURE_ERC721)
|| (_interfaceID == INTERFACE_SIGNATURE_ERC721Metadata)
);
}
/// @dev Checks if a given address owns a particular plot.
/// @param _owner The address of the owner to check for.
/// @param _deedId The plot identifier to check for.
function _owns(address _owner, uint256 _deedId) internal view returns (bool) {
return identifierToOwner[_deedId] == _owner;
}
/// @dev Approve a given address to take ownership of a deed.
/// @param _from The address approving taking ownership.
/// @param _to The address to approve taking ownership.
/// @param _deedId The identifier of the deed to give approval for.
function _approve(address _from, address _to, uint256 _deedId) internal {
identifierToApproved[_deedId] = _to;
// Emit event.
Approval(_from, _to, _deedId);
}
/// @dev Checks if a given address has approval to take ownership of a deed.
/// @param _claimant The address of the claimant to check for.
/// @param _deedId The identifier of the deed to check for.
function _approvedFor(address _claimant, uint256 _deedId) internal view returns (bool) {
return identifierToApproved[_deedId] == _claimant;
}
/// @dev Assigns ownership of a specific deed to an address.
/// @param _from The address to transfer the deed from.
/// @param _to The address to transfer the deed to.
/// @param _deedId The identifier of the deed to transfer.
function _transfer(address _from, address _to, uint256 _deedId) internal {
// The number of plots is capped at 2^16 * 2^16, so this cannot
// be overflowed.
ownershipDeedCount[_to]++;
// Transfer ownership.
identifierToOwner[_deedId] = _to;
// When a new deed is minted, the _from address is 0x0, but we
// do not track deed ownership of 0x0.
if (_from != address(0)) {
ownershipDeedCount[_from]--;
// Clear taking ownership approval.
delete identifierToApproved[_deedId];
}
// Emit the transfer event.
Transfer(_from, _to, _deedId);
}
// ERC 721 implementation
/// @notice Returns the total number of deeds currently in existence.
/// @dev Required for ERC-721 compliance.
function countOfDeeds() public view returns (uint256) {
return plots.length;
}
/// @notice Returns the number of deeds owned by a specific address.
/// @param _owner The owner address to check.
/// @dev Required for ERC-721 compliance
function countOfDeedsByOwner(address _owner) public view returns (uint256) {
return ownershipDeedCount[_owner];
}
/// @notice Returns the address currently assigned ownership of a given deed.
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _deedId) external view returns (address _owner) {
_owner = identifierToOwner[_deedId];
require(_owner != address(0));
}
/// @notice Approve a given address to take ownership of a deed.
/// @param _to The address to approve taking owernship.
/// @param _deedId The identifier of the deed to give approval for.
/// @dev Required for ERC-721 compliance.
function approve(address _to, uint256 _deedId) external whenNotPaused {
uint256[] memory _deedIds = new uint256[](1);
_deedIds[0] = _deedId;
approveMultiple(_to, _deedIds);
}
/// @notice Approve a given address to take ownership of multiple deeds.
/// @param _to The address to approve taking ownership.
/// @param _deedIds The identifiers of the deeds to give approval for.
function approveMultiple(address _to, uint256[] _deedIds) public whenNotPaused {
// Ensure the sender is not approving themselves.
require(msg.sender != _to);
for (uint256 i = 0; i < _deedIds.length; i++) {
uint256 _deedId = _deedIds[i];
// Require the sender is the owner of the deed.
require(_owns(msg.sender, _deedId));
// Perform the approval.
_approve(msg.sender, _to, _deedId);
}
}
/// @notice Transfer a deed to another address. If transferring to a smart
/// contract be VERY CAREFUL to ensure that it is aware of ERC-721, or your
/// deed may be lost forever.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _deedId The identifier of the deed to transfer.
/// @dev Required for ERC-721 compliance.
function transfer(address _to, uint256 _deedId) external whenNotPaused {
uint256[] memory _deedIds = new uint256[](1);
_deedIds[0] = _deedId;
transferMultiple(_to, _deedIds);
}
/// @notice Transfers multiple deeds to another address. If transferring to
/// a smart contract be VERY CAREFUL to ensure that it is aware of ERC-721,
/// or your deeds may be lost forever.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _deedIds The identifiers of the deeds to transfer.
function transferMultiple(address _to, uint256[] _deedIds) public whenNotPaused {
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
require(_to != address(this));
for (uint256 i = 0; i < _deedIds.length; i++) {
uint256 _deedId = _deedIds[i];
// One can only transfer their own plots.
require(_owns(msg.sender, _deedId));
// Transfer ownership
_transfer(msg.sender, _to, _deedId);
}
}
/// @notice Transfer a deed owned by another address, for which the calling
/// address has previously been granted transfer approval by the owner.
/// @param _deedId The identifier of the deed to be transferred.
/// @dev Required for ERC-721 compliance.
function takeOwnership(uint256 _deedId) external whenNotPaused {
uint256[] memory _deedIds = new uint256[](1);
_deedIds[0] = _deedId;
takeOwnershipMultiple(_deedIds);
}
/// @notice Transfer multiple deeds owned by another address, for which the
/// calling address has previously been granted transfer approval by the owner.
/// @param _deedIds The identifier of the deed to be transferred.
function takeOwnershipMultiple(uint256[] _deedIds) public whenNotPaused {
for (uint256 i = 0; i < _deedIds.length; i++) {
uint256 _deedId = _deedIds[i];
address _from = identifierToOwner[_deedId];
// Check for transfer approval
require(_approvedFor(msg.sender, _deedId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transfer(_from, msg.sender, _deedId);
}
}
/// @notice Returns a list of all deed identifiers assigned to an address.
/// @param _owner The owner whose deeds we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. It's very
/// expensive and is not supported in contract-to-contract calls as it returns
/// a dynamic array (only supported for web3 calls).
function deedsOfOwner(address _owner) external view returns(uint256[]) {
uint256 deedCount = countOfDeedsByOwner(_owner);
if (deedCount == 0) {
// Return an empty array.
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](deedCount);
uint256 totalDeeds = countOfDeeds();
uint256 resultIndex = 0;
for (uint256 deedNumber = 0; deedNumber < totalDeeds; deedNumber++) {
uint256 identifier = plots[deedNumber];
if (identifierToOwner[identifier] == _owner) {
result[resultIndex] = identifier;
resultIndex++;
}
}
return result;
}
}
/// @notice Returns a deed identifier of the owner at the given index.
/// @param _owner The address of the owner we want to get a deed for.
/// @param _index The index of the deed we want.
function deedOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256) {
// The index should be valid.
require(_index < countOfDeedsByOwner(_owner));
// Loop through all plots, accounting the number of plots of the owner we've seen.
uint256 seen = 0;
uint256 totalDeeds = countOfDeeds();
for (uint256 deedNumber = 0; deedNumber < totalDeeds; deedNumber++) {
uint256 identifier = plots[deedNumber];
if (identifierToOwner[identifier] == _owner) {
if (seen == _index) {
return identifier;
}
seen++;
}
}
}
/// @notice Returns an (off-chain) metadata url for the given deed.
/// @param _deedId The identifier of the deed to get the metadata
/// url for.
/// @dev Implementation of optional ERC-721 functionality.
function deedUri(uint256 _deedId) external pure returns (string uri) {
require(validIdentifier(_deedId));
var (x, y) = identifierToCoordinate(_deedId);
// Maximum coordinate length in decimals is 5 (65535)
uri = "https://dworld.io/plot/xxxxx/xxxxx";
bytes memory _uri = bytes(uri);
for (uint256 i = 0; i < 5; i++) {
_uri[27 - i] = byte(48 + (x / 10 ** i) % 10);
_uri[33 - i] = byte(48 + (y / 10 ** i) % 10);
}
}
}
/// @dev Migrate original data from the old contract.
contract DWorldUpgrade is DWorldMinting {
OriginalDWorldDeed originalContract;
ClockAuction originalSaleAuction;
ClockAuction originalRentAuction;
/// @notice Keep track of whether we have finished migrating.
bool public migrationFinished = false;
/// @dev Keep track of how many plots have been transferred so far.
uint256 migrationNumPlotsTransferred = 0;
function DWorldUpgrade(
address originalContractAddress,
address originalSaleAuctionAddress,
address originalRentAuctionAddress
)
public
{
if (originalContractAddress != 0) {
_startMigration(originalContractAddress, originalSaleAuctionAddress, originalRentAuctionAddress);
} else {
migrationFinished = true;
}
}
/// @dev Migrate data from the original contract. Assumes the original
/// contract is paused, and remains paused for the duration of the
/// migration.
/// @param originalContractAddress The address of the original contract.
function _startMigration(
address originalContractAddress,
address originalSaleAuctionAddress,
address originalRentAuctionAddress
)
internal
{
// Set contracts.
originalContract = OriginalDWorldDeed(originalContractAddress);
originalSaleAuction = ClockAuction(originalSaleAuctionAddress);
originalRentAuction = ClockAuction(originalRentAuctionAddress);
// Start paused.
paused = true;
// Get count of original plots.
uint256 numPlots = originalContract.countOfDeeds();
// Allocate storage for the plots array (this is more
// efficient than .push-ing each individual plot, as
// that requires multiple dynamic allocations).
plots.length = numPlots;
}
function migrationStep(uint256 numPlotsTransfer) external onlyOwner whenPaused {
// Migration must not be finished yet.
require(!migrationFinished);
// Get count of original plots.
uint256 numPlots = originalContract.countOfDeeds();
// Loop through plots and assign to original owner.
uint256 i;
for (i = migrationNumPlotsTransferred; i < numPlots && i < migrationNumPlotsTransferred + numPlotsTransfer; i++) {
uint32 _deedId = originalContract.plots(i);
// Set plot.
plots[i] = _deedId;
// Get the original owner and transfer.
address owner = originalContract.ownerOf(_deedId);
// If the owner of the plot is an auction contract,
// get the actual owner of the plot.
address seller;
if (owner == address(originalSaleAuction)) {
(seller, ) = originalSaleAuction.getAuction(_deedId);
owner = seller;
} else if (owner == address(originalRentAuction)) {
(seller, ) = originalRentAuction.getAuction(_deedId);
owner = seller;
}
_transfer(address(0), owner, _deedId);
// Set the initial price paid for the plot.
initialPricePaid[_deedId] = 0.0125 ether;
// The initial buyout price.
uint256 _initialBuyoutPrice = 0.050 ether;
// Set the initial buyout price.
identifierToBuyoutPrice[_deedId] = _initialBuyoutPrice;
// Trigger the buyout price event.
SetBuyoutPrice(_deedId, _initialBuyoutPrice);
// Mark the plot as being an original.
identifierIsOriginal[_deedId] = true;
}
migrationNumPlotsTransferred += i;
// Finished migration.
if (i == numPlots) {
migrationFinished = true;
}
}
}
/// @dev Implements highest-level DWorld functionality.
contract DWorldCore is DWorldUpgrade {
/// If this contract is broken, this will be used to publish the address at which an upgraded contract can be found
address public upgradedContractAddress;
event ContractUpgrade(address upgradedContractAddress);
function DWorldCore(
address originalContractAddress,
address originalSaleAuctionAddress,
address originalRentAuctionAddress,
uint256 buyoutsEnabledAfterHours
)
DWorldUpgrade(originalContractAddress, originalSaleAuctionAddress, originalRentAuctionAddress)
public
{
buyoutsEnabledFromTimestamp = block.timestamp + buyoutsEnabledAfterHours * 3600;
}
/// @notice Only to be used when this contract is significantly broken,
/// and an upgrade is required.
function setUpgradedContractAddress(address _upgradedContractAddress) external onlyOwner whenPaused {
upgradedContractAddress = _upgradedContractAddress;
ContractUpgrade(_upgradedContractAddress);
}
/// @notice Set the data associated with a plot.
function setPlotData(uint256 _deedId, string name, string description, string imageUrl, string infoUrl)
public
whenNotPaused
{
// The sender requesting the data update should be
// the owner.
require(_owns(msg.sender, _deedId));
// Set the data
_setPlotData(_deedId, name, description, imageUrl, infoUrl);
}
/// @notice Set the data associated with multiple plots.
function setPlotDataMultiple(uint256[] _deedIds, string name, string description, string imageUrl, string infoUrl)
external
whenNotPaused
{
for (uint256 i = 0; i < _deedIds.length; i++) {
uint256 _deedId = _deedIds[i];
setPlotData(_deedId, name, description, imageUrl, infoUrl);
}
}
/// @notice Withdraw Ether owed to the sender.
function withdrawBalance() external {
uint256 etherOwed = addressToEtherOwed[msg.sender];
// Ensure Ether is owed to the sender.
require(etherOwed > 0);
// Set Ether owed to 0.
delete addressToEtherOwed[msg.sender];
// 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 sender (not susceptible to re-entry
// attack, as the Ether owed is set to 0 before the transfer takes place).
msg.sender.transfer(etherOwed);
}
/// @notice Withdraw (unowed) contract balance.
function withdrawFreeBalance() external onlyCFO {
// 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;
cfoAddress.transfer(freeBalance);
}
}
|
Calculate and assign the dividend payable for the new plot claim. A new claim pays dividends to all existing surrounding plots. _deedId The identifier of the new plot to calculate and assign dividends for. Assumed to be valid. Get existing surrounding plots. Keep track of the claim dividend. Assign claim dividend.
|
function _calculateAndAssignClaimDividends(uint256 _deedId)
internal
returns (uint256 totalClaimDividend)
{
uint256[] memory claimedSurroundingPlots = _claimedSurroundingPlots(_deedId);
uint256 _claimDividend = claimDividend();
totalClaimDividend = 0;
for (uint256 i = 0; i < claimedSurroundingPlots.length; i++) {
if (identifierToOwner[claimedSurroundingPlots[i]] != msg.sender) {
totalClaimDividend = totalClaimDividend.add(_claimDividend);
_assignClaimDividend(msg.sender, identifierToOwner[claimedSurroundingPlots[i]], _deedId, claimedSurroundingPlots[i]);
}
}
}
| 15,801,551
|
// SPDX-License-Identifier: CC-BY-4.0
pragma solidity >=0.4.22 <0.9.0;
/**
* Migrated from https://github.com/skfarhat/ethbnb
*/
import "../common/Version.sol";
import "../common/Frozen.sol";
contract BlockchainBNB is Version, Frozen {
bytes32 constant private ZERO_BYTES = bytes32(0);
address constant private ZERO_ADDRESS = address(0);
uint constant private SECONDS_PER_DAY = 3600 * 24;
uint constant private HEAD = 0;
uint constant private JUNK = 2^256-1; // We assume there won't be that many bookings
int public constant NOT_FOUND = -1;
int public constant BOOK_CONFLICT = -2;
enum Country {
AF, AX, AL, DZ, AS, AD, AO, AI, AG, AR, AM, AW, AU, AT, AZ, BS, BH,
BD, BB, BY, BE, BZ, BJ, BM, BT, BO, BA, BW, BV, BR, VG, BN, BG, BF,
BI, TC, KH, CM, CA, CV, KY, CF, TD, CL, CN, CX, CC, CO, KM, CG, CD,
CK, CR, CI, HR, CU, CY, CZ, DK, DJ, DM, DO, EC, EG, SV, GB, GQ, ER,
EE, ET, EU, FK, FO, FJ, FI, FR, GF, PF, TF, GA, GM, GE, DE, GH, GI,
GR, GL, GD, GP, GU, GT, GW, GN, GY, HT, HM, HN, HK, HU, IS, IN, IO,
ID, IR, IQ, IE, IL, IT, JM, JP, JO, KZ, KE, KI, KW, KG, LA, LV, LB,
LS, LR, LY, LI, LT, LU, MO, MK, MG, MW, MY, MV, ML, MT, MH, MQ, MR,
MU, YT, MX, FM, MD, MC, MN, ME, MS, MA, MZ, NA, NR, NP, AN, NL, NC,
PG, NZ, NI, NE, NG, NU, NF, KP, MP, NO, OM, PK, PW, PS, PA, PY, PE,
PH, PN, PL, PT, PR, QA, RE, RO, RU, RW, SH, KN, LC, PM, VC, WS, SM,
GS, ST, SA, SN, CS, RS, SC, SL, SG, SK, SI, SB, SO, ZA, KR, ES, LK,
SD, SR, SJ, SZ, SE, CH, SY, TW, TJ, TZ, TH, TL, TG, TK, TO, TT, TN,
TR, TM, TV, UG, UA, AE, US, UY, UM, VI, UZ, VU, VA, VE, VN, WF, EH,
YE, ZM, ZW
}
struct Node {
/// Booking's start date in seconds
uint fromDate;
/// Booking's end date in seconds
uint toDate;
uint bid;
uint next;
}
struct Listing {
uint lid;
address owner;
Country country;
string location;
uint price;
uint balance;
string imageCID;
string imageCIDSource;
address booker;
}
struct Account {
address payable owner;
string name;
uint dateCreated;
/**
* Account's average rating (out of 5) can be computed as
* totalScore / totalRatings
*/
uint totalScore;
uint nRatings;
}
struct Booking {
uint bid;
uint lid;
address guestAddr;
address hostAddr;
/**
* Rating assigned to the owner by the guest
* defaults to 0 which means nothing was set
*/
uint ownerRating;
/**
* Rating assigned to the guest by the owner
* defaults to 0 which means nothing was set
*/
uint guestRating;
/**
* When a booking is made, the listing balance (staked by the host)
* along with the value staked by the guest are added to the balance here.
* The listing balance is obviously decreased.
*/
uint256 balance;
}
// =======================================================================
// MEMBER VARIABLES
// =======================================================================
event Log(string functionName, string msg);
event Error(int code);
// Account events
event CreateAccountEvent(address from);
event UpdateAccountEvent(address from);
event DeleteAccountEvent(address from);
// Listing events
event CreateListingEvent(address from, uint lid);
event UpdateListingEvent(address from, uint lid);
event DeleteListingEvent(address from, uint lid);
// Booking events
event BookingComplete(address from, uint bid);
event BookingCancelled(address from, uint bid);
event RatingComplete(address from, uint bid, uint stars);
event Booked(uint bid);
event Cancelled(uint bid);
event Log(uint, uint);
struct BlockchainBNBStorage {
uint nextPos;
/**
* Listings will have incrementing Ids starting from 1
*/
uint nextListingId;
/**
* Bookings will have incrementing Ids starting from 1
*/
uint nextBookingId;
mapping (uint => Node) nodes;
/** Store all created listings */
mapping(uint => Listing) listings;
/** Stores accounts */
mapping(address => Account) accounts;
/** Stores bookings */
mapping(uint => Booking) bookings;
}
BlockchainBNBStorage bnbStorage;
constructor() {
blockchainBNBStorage().nextPos = 1;
blockchainBNBStorage().nextListingId = 1;
blockchainBNBStorage().nextBookingId = 1;
blockchainBNBStorage().nodes[HEAD].next = HEAD; // (implicit since HEAD = 0)
blockchainBNBStorage().nodes[JUNK].next = JUNK;
}
function blockchainBNBStorage()
internal
pure
returns (BlockchainBNBStorage storage ds)
{
bytes32 position = keccak256("BlockchainBNB.storage");
assembly {
ds.slot := position
}
}
// =======================================================================
// FUNCTIONS
// =======================================================================
modifier accountExists() {
require(blockchainBNBStorage().accounts[msg.sender].owner == msg.sender, 'Invalid account address');
_;
}
modifier validBooking(uint bid) {
require(blockchainBNBStorage().bookings[bid].bid == bid, 'Invalid booking identifier');
_;
}
modifier listingExists(uint lid) {
require(blockchainBNBStorage().accounts[msg.sender].owner == msg.sender, 'Invalid account address');
require(blockchainBNBStorage().listings[lid].lid == lid, 'Invalid listing identifier');
_;
}
modifier onlyListingHost(uint lid) {
require(blockchainBNBStorage().listings[lid].owner == msg.sender, 'Only listing host can change it');
_;
}
function createAccount(string memory name) public {
blockchainBNBStorage().accounts[msg.sender] = Account({
owner : payable(msg.sender),
name : name,
dateCreated : block.timestamp,
totalScore: 0,
nRatings: 0
});
emit CreateAccountEvent(msg.sender);
}
function hasAccount() public view returns (bool) {
return blockchainBNBStorage().accounts[msg.sender].owner == msg.sender;
}
function getAccountAll(address owner) public view
returns (string memory name, uint dateCreated, uint totalScore, uint nRatings) {
require(blockchainBNBStorage().accounts[owner].owner == owner, 'Invalid account address');
Account memory account = blockchainBNBStorage().accounts[owner];
return (account.name, account.dateCreated, account.totalScore, account.nRatings);
}
function getListingAll(uint lid) public listingExists(lid) view
returns (address owner, uint price, string memory location, Country country, uint256 balance,
string memory imageCID, string memory imageCIDSource) {
Listing storage l = blockchainBNBStorage().listings[lid];
return (l.owner, l.price, l.location, l.country, l.balance, l.imageCID, l.imageCIDSource);
}
/**
* Creates a new listing for the message sender
* and returns the Id of the created listing
*
* When the listing create the smart-contract will have had the 2xprice amount
* added to its balance.
*/
function createListing(Country country, string memory location, uint price)
public payable accountExists() {
// Note: enforce a maximum number of listings per user?
blockchainBNBStorage().listings[blockchainBNBStorage().nextListingId] = Listing({
lid : blockchainBNBStorage().nextListingId,
owner: msg.sender,
country: country,
location: location,
price: price,
balance: msg.value,
imageCID: '',
imageCIDSource: '',
booker: msg.sender
});
emit CreateListingEvent(msg.sender, blockchainBNBStorage().nextListingId++);
}
/**
* Book a listing
*
* @param lid id of the listing to be booked
* @param fromDate start date of the booking in seconds
* @param nbOfDays number of days for which the booking will be made
*/
function bookListing(uint lid, uint fromDate, uint nbOfDays)
public payable listingExists(lid) {
// TODO: cap the number of booked days to 30 or so
Listing storage listing = blockchainBNBStorage().listings[lid];
address payable guest = payable(msg.sender);
uint256 stake = 2 * listing.price * nbOfDays;
uint toDate = fromDate + nbOfDays * SECONDS_PER_DAY;
require(listing.owner != guest, 'Owner cannot book their own listing');
// Ensure both guest and host have staked the same
require(msg.value >= stake, 'Guest must stake twice the price');
require(listing.balance >= stake, 'Listing must have stake amount in its balance');
// Try to book.
// If successful, create a booking event with the balance amount
// If unsuccessful, refund the stake to guest
int res = book(blockchainBNBStorage().nextBookingId++, fromDate, toDate);
if (res >= 0) {
uint bid = uint(res);
// Save the booking
blockchainBNBStorage().bookings[bid] = Booking({
bid: bid,
lid: lid,
hostAddr: blockchainBNBStorage().listings[lid].owner,
guestAddr: guest,
ownerRating: 0,
guestRating: 0,
// Add the amounts staked by the guest
// and by the host to the booking balance
balance: 2 * stake
});
// Decrement the listing balance
listing.balance -= stake;
// Refund any excess to the guest
guest.transfer(msg.value - stake);
emit BookingComplete(msg.sender, bid);
} else {
// Refund all Ether provided if the booking failed
guest.transfer(msg.value);
}
}
function setListing(uint lid, uint price, string memory location, Country country)
public listingExists(lid) onlyListingHost(lid) {
Listing storage listing = blockchainBNBStorage().listings[lid];
listing.location = location;
listing.price = price;
listing.country = country;
emit UpdateListingEvent(msg.sender, lid);
}
function setListingImage(uint lid, string memory cid, string memory cidSource)
public listingExists(lid) onlyListingHost(lid) {
Listing storage listing = blockchainBNBStorage().listings[lid];
listing.imageCID = cid;
listing.imageCIDSource = cidSource;
emit UpdateListingEvent(msg.sender, lid);
}
/**
* Returns the listing balance to its owner and deletes the listing
*
* Only if there are no active bookings.
*
* @param lid id of the listing to be deleted
*/
function deleteListing(uint lid) public listingExists(lid) onlyListingHost(lid) {
// Check that there are no active bookings before we proceed
Listing storage listing = blockchainBNBStorage().listings[lid];
require(false == hasActiveBookings(), 'Cannot delete listing with active bookings');
// Return listing balance to its owner
uint toReturn = listing.balance;
listing.balance = 0;
blockchainBNBStorage().accounts[listing.owner].owner.transfer(toReturn);
// Delete listing's storage
delete blockchainBNBStorage().listings[lid];
emit DeleteListingEvent(msg.sender, lid);
}
function depositIntoListing(uint lid)
public payable
listingExists(lid)
onlyListingHost(lid)
{
Listing storage listing = blockchainBNBStorage().listings[lid];
listing.balance += msg.value;
}
function withdrawFromListing(uint lid, uint amount)
public
listingExists(lid)
onlyListingHost(lid)
{
Listing storage listing = blockchainBNBStorage().listings[lid];
require(amount <= listing.balance, 'Cannot withdraw more than listing balance');
listing.balance -= amount;
blockchainBNBStorage().accounts[blockchainBNBStorage().listings[lid].owner].owner.transfer(amount);
}
/**
* Invoked by the guest of a booking after the booking end,
* confirming the host fulfilled their obligations, and
* releasing funds held in escrow.
*
* @param bid id of the booking
*/
function fulfilBooking(uint bid) public validBooking(bid) {
Booking storage booking = blockchainBNBStorage().bookings[bid];
uint lid = booking.lid;
address guest = booking.guestAddr;
address host = booking.hostAddr;
(, uint toDate) = getBookingDates(bid);
require(msg.sender == guest, 'Only guest can call fulfilBooking');
require(toDate <= block.timestamp, 'Cannot fulfil booking before end date');
// Fund Release:
// Guest receives: booking.balance
// Listing receives: 2 x booking.balance
// Owner: booking.balance
//
uint256 amount = booking.balance / 4;
booking.balance = 0;
blockchainBNBStorage().listings[lid].balance += amount * 2;
blockchainBNBStorage().accounts[host].owner.transfer(amount);
blockchainBNBStorage().accounts[guest].owner.transfer(amount);
}
/**
* Rate the booking 1-5 stars
*
* The function checks the msg.sender and validates
* they were either owner or guest in the booking.
*
* If they were not, a PermissionDenied event is emitted.
*
* @param bid the identifier for their booking, this
* coupled with msg.sender is enough to determine
* the person being rated
* @param stars unsigned integer between 1 and 5, anything else
* will emit an error
*/
function rate(uint bid, uint stars) public validBooking(bid) {
require(stars >= 1 && stars <= 5, 'Stars arg must be in [1,5]');
Booking storage booking = blockchainBNBStorage().bookings[bid];
require(booking.guestAddr == msg.sender || booking.hostAddr == msg.sender, 'Sender not participated in booking');
(, uint toDate) = getBookingDates(bid);
require(toDate <= block.timestamp, 'Cannot rate a booking before it ends');
if (booking.guestAddr == msg.sender) {
// The guest is rating the owner
require(booking.ownerRating == 0, 'Owner already rated, cannot re-rate');
// Assign the rating and adjust their account
booking.ownerRating = stars;
blockchainBNBStorage().accounts[booking.hostAddr].totalScore += stars;
blockchainBNBStorage().accounts[booking.hostAddr].nRatings++;
}
else if (booking.hostAddr == msg.sender) {
// The owner is rating the guest
require(booking.guestRating == 0, 'Guest already rated, cannot re-rate');
// Adding the rating and adjust their account
booking.guestRating = stars;
blockchainBNBStorage().accounts[booking.guestAddr].totalScore += stars;
blockchainBNBStorage().accounts[booking.guestAddr].nRatings++;
}
emit RatingComplete(msg.sender, bid, stars);
}
/**
* Cancel a booking
*
* @param bid id of the booking to be cancelled
*/
function cancelBooking(uint bid) public validBooking(bid) {
Booking storage booking = blockchainBNBStorage().bookings[bid];
require(
msg.sender == booking.hostAddr ||
msg.sender == booking.guestAddr,
'Only Guest or Host can cancel a booking'
);
int res = cancel(bid);
if (res >= 0) {
delete blockchainBNBStorage().bookings[bid];
emit BookingCancelled(msg.sender, bid);
}
}
function getBookingAll(uint bid) public view
validBooking(bid)
returns (uint lid, address guest, address host, uint fromDate, uint toDate)
{
Booking storage booking = blockchainBNBStorage().bookings[bid];
(uint fromDate1, uint toDate1) = getDates(bid);
return (booking.lid, booking.guestAddr, booking.hostAddr, fromDate1, toDate1);
}
function getBookingDates(uint bid) public view
validBooking(bid)
returns (uint fromDate, uint toDate)
{
return getDates(bid);
}
function getNextPos() public view returns (uint)
{
return blockchainBNBStorage().nextPos;
}
function setNextPos(uint pos) public
{
blockchainBNBStorage().nextPos = pos;
}
function getListingId(uint pos) public view returns (Node memory)
{
return blockchainBNBStorage().nodes[pos];
}
/// The list is empty if the HEAD node points to itself
function isEmpty() public view returns (bool)
{
return blockchainBNBStorage().nodes[HEAD].next == HEAD;
}
function createLink(uint fromNode, uint toNode) private
{
blockchainBNBStorage().nodes[fromNode].next = toNode;
}
function _printAll() public
{
uint curr = blockchainBNBStorage().nodes[HEAD].next;
while (curr != HEAD) {
emit Log(blockchainBNBStorage().nodes[curr].fromDate, blockchainBNBStorage().nodes[curr].toDate);
curr = blockchainBNBStorage().nodes[curr].next;
}
}
function _printJunk() public
{
if (!junkIsEmpty()) {
uint curr = blockchainBNBStorage().nodes[JUNK].next;
while (curr != JUNK) {
emit Log(blockchainBNBStorage().nodes[curr].fromDate, blockchainBNBStorage().nodes[curr].toDate);
curr = blockchainBNBStorage().nodes[curr].next;
}
}
}
/// Returns true if junk is initialised: if it points to itself
function junkNotInitialised() private view returns (bool)
{
return blockchainBNBStorage().nodes[JUNK].next == 0;
}
function junkIsEmpty() private view returns (bool)
{
return junkNotInitialised() || blockchainBNBStorage().nodes[JUNK].next == JUNK;
}
// Adds the provided node to junk
function addJunk(uint node) private
{
require(node != JUNK, 'Cannot add provided node to Junk');
if (junkNotInitialised()) {
blockchainBNBStorage().nodes[JUNK].next = JUNK;
}
createLink(node, blockchainBNBStorage().nodes[JUNK].next);
createLink(JUNK, node);
}
/// Pops the junk node at head of list and returns its index
function popJunk() private returns (uint)
{
uint ret = blockchainBNBStorage().nodes[JUNK].next;
createLink(JUNK, blockchainBNBStorage().nodes[ret].next);
return ret;
}
/// Free all junk storage kept for reuse
function freeJunk() public
{
while (!junkIsEmpty()) {
uint idx = popJunk();
delete blockchainBNBStorage().nodes[idx];
}
}
/// Removes node from the list. Requires the prevNode be provided.
function removeNode(uint node, uint prevNode) private
{
createLink(prevNode, blockchainBNBStorage().nodes[node].next);
addJunk(node);
}
/// Returns the next available position and updates it
function useNextPos() public returns (uint pos)
{
if (junkIsEmpty()) {
return blockchainBNBStorage().nextPos++;
} else {
// Recycle node
return popJunk();
}
}
function newNode(uint prevNode, uint nextNode, uint bid, uint fromDate, uint toDate) private
{
uint nextPos = useNextPos();
Node memory n = Node({
fromDate: fromDate,
toDate: toDate,
bid: bid,
next: nextNode
});
createLink(prevNode, nextPos);
createLink(nextPos, nextNode); // redundant, but there for readability
blockchainBNBStorage().nodes[nextPos] = n;
}
/// Called by book function
///
/// - Creates a new LinkedList node
/// - Emits Booking event
/// - Updates nextBid
function newBook(uint prevNode, uint nextNode, uint bid, uint fromDate, uint toDate)
private returns (uint)
{
require(toDate > fromDate, 'fromDate must be less than toDate');
newNode(prevNode, nextNode, bid, fromDate, toDate);
emit Booked(bid);
return bid;
}
function book(uint bid, uint fromDate, uint toDate) public returns (int)
{
require(fromDate < toDate, 'Invalid dates provided');
uint prev = HEAD;
uint curr = blockchainBNBStorage().nodes[HEAD].next;
while (curr != HEAD) {
uint currFrom = blockchainBNBStorage().nodes[curr].fromDate;
uint currTo = blockchainBNBStorage().nodes[curr].toDate;
if (fromDate >= currTo) {
return int(newBook(prev, curr, bid, fromDate, toDate));
} else if (toDate <= currFrom) {
prev = curr;
curr = blockchainBNBStorage().nodes[curr].next;
} else {
return BOOK_CONFLICT;
}
}
return int(newBook(prev, HEAD, bid, fromDate, toDate));
}
function cancel(uint bid) public returns (int)
{
uint prev = HEAD;
uint curr = blockchainBNBStorage().nodes[prev].next;
// Find node with matching bid, then remove it
while (curr != HEAD) {
if (blockchainBNBStorage().nodes[curr].bid == bid) {
removeNode(curr, prev);
emit Cancelled(bid);
return int(bid);
}
prev = curr;
curr = blockchainBNBStorage().nodes[curr].next;
}
return NOT_FOUND;
}
function cancelPastBookings() public
{
uint curr = blockchainBNBStorage().nodes[HEAD].next;
while (curr != HEAD) {
if (blockchainBNBStorage().nodes[curr].toDate < block.timestamp) {
break;
}
curr = blockchainBNBStorage().nodes[curr].next;
}
// Add all bookings starting from curr to junk
while (curr != HEAD) {
addJunk(curr);
curr = blockchainBNBStorage().nodes[curr].next;
}
}
/// Return index of found id
function find(uint id) public view returns (int) {
uint curr = blockchainBNBStorage().nodes[HEAD].next;
while (curr != HEAD) {
if (blockchainBNBStorage().nodes[curr].bid == id) {
return int(curr);
}
curr = blockchainBNBStorage().nodes[curr].next;
}
return NOT_FOUND;
}
function hasActiveBookings() public view returns (bool)
{
uint first = blockchainBNBStorage().nodes[HEAD].next;
return blockchainBNBStorage().nodes[first].toDate >= block.timestamp;
}
function getDates(uint id) public view returns (uint fromDate, uint toDate) {
int idx = find(id);
require(idx != NOT_FOUND, 'Entry not found');
Node memory node = blockchainBNBStorage().nodes[uint(idx)];
return (node.fromDate, node.toDate);
}
}
|
Creates a new listing for the message sender and returns the Id of the created listing When the listing create the smart-contract will have had the 2xprice amount added to its balance./ Note: enforce a maximum number of listings per user?
|
function createListing(Country country, string memory location, uint price)
public payable accountExists() {
blockchainBNBStorage().listings[blockchainBNBStorage().nextListingId] = Listing({
lid : blockchainBNBStorage().nextListingId,
owner: msg.sender,
country: country,
location: location,
price: price,
balance: msg.value,
imageCID: '',
imageCIDSource: '',
booker: msg.sender
});
emit CreateListingEvent(msg.sender, blockchainBNBStorage().nextListingId++);
}
| 14,068,342
|
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title Enum - Collection of enums
/// @author Richard Meissner - <[email protected]>
contract Enum {
enum Operation {Call, DelegateCall}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @notice More details at https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/introspection/IERC165.sol
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: LGPL-3.0-only
/// @title Module Interface - A contract that can pass messages to a Module Manager contract if enabled by that contract.
pragma solidity >=0.7.0 <0.9.0;
import "../interfaces/IAvatar.sol";
import "../factory/FactoryFriendly.sol";
import "../guard/Guardable.sol";
abstract contract Module is FactoryFriendly, Guardable {
/// @dev Emitted each time the avatar is set.
event AvatarSet(address indexed previousAvatar, address indexed newAvatar);
/// @dev Emitted each time the Target is set.
event TargetSet(address indexed previousTarget, address indexed newTarget);
/// @dev Address that will ultimately execute function calls.
address public avatar;
/// @dev Address that this module will pass transactions to.
address public target;
/// @dev Sets the avatar to a new avatar (`newAvatar`).
/// @notice Can only be called by the current owner.
function setAvatar(address _avatar) public onlyOwner {
address previousAvatar = avatar;
avatar = _avatar;
emit AvatarSet(previousAvatar, _avatar);
}
/// @dev Sets the target to a new target (`newTarget`).
/// @notice Can only be called by the current owner.
function setTarget(address _target) public onlyOwner {
address previousTarget = target;
target = _target;
emit TargetSet(previousTarget, _target);
}
/// @dev Passes a transaction to be executed by the avatar.
/// @notice Can only be called by this contract.
/// @param to Destination address of module transaction.
/// @param value Ether value of module transaction.
/// @param data Data payload of module transaction.
/// @param operation Operation type of module transaction: 0 == call, 1 == delegate call.
function exec(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation
) internal returns (bool success) {
/// check if a transactioon guard is enabled.
if (guard != address(0)) {
IGuard(guard).checkTransaction(
/// Transaction info used by module transactions
to,
value,
data,
operation,
/// Zero out the redundant transaction information only used for Safe multisig transctions
0,
0,
0,
address(0),
payable(0),
bytes("0x"),
address(0)
);
}
success = IAvatar(target).execTransactionFromModule(
to,
value,
data,
operation
);
if (guard != address(0)) {
IGuard(guard).checkAfterExecution(bytes32("0x"), success);
}
return success;
}
/// @dev Passes a transaction to be executed by the target and returns data.
/// @notice Can only be called by this contract.
/// @param to Destination address of module transaction.
/// @param value Ether value of module transaction.
/// @param data Data payload of module transaction.
/// @param operation Operation type of module transaction: 0 == call, 1 == delegate call.
function execAndReturnData(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation
) internal returns (bool success, bytes memory returnData) {
/// check if a transactioon guard is enabled.
if (guard != address(0)) {
IGuard(guard).checkTransaction(
/// Transaction info used by module transactions
to,
value,
data,
operation,
/// Zero out the redundant transaction information only used for Safe multisig transctions
0,
0,
0,
address(0),
payable(0),
bytes("0x"),
address(0)
);
}
(success, returnData) = IAvatar(target)
.execTransactionFromModuleReturnData(to, value, data, operation);
if (guard != address(0)) {
IGuard(guard).checkAfterExecution(bytes32("0x"), success);
}
return (success, returnData);
}
}
// SPDX-License-Identifier: LGPL-3.0-only
/// @title Zodiac FactoryFriendly - A contract that allows other contracts to be initializable and pass bytes as arguments to define contract state
pragma solidity >=0.7.0 <0.9.0;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
abstract contract FactoryFriendly is OwnableUpgradeable {
function setUp(bytes memory initializeParams) public virtual;
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
import "@gnosis.pm/safe-contracts/contracts/common/Enum.sol";
import "@gnosis.pm/safe-contracts/contracts/interfaces/IERC165.sol";
import "../interfaces/IGuard.sol";
abstract contract BaseGuard is IERC165 {
function supportsInterface(bytes4 interfaceId)
external
pure
override
returns (bool)
{
return
interfaceId == type(IGuard).interfaceId || // 0xe6d7a83a
interfaceId == type(IERC165).interfaceId; // 0x01ffc9a7
}
/// Module transactions only use the first four parameters: to, value, data, and operation.
/// Module.sol hardcodes the remaining parameters as 0 since they are not used for module transactions.
/// This interface is used to maintain compatibilty with Gnosis Safe transaction guards.
function checkTransaction(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation,
uint256 safeTxGas,
uint256 baseGas,
uint256 gasPrice,
address gasToken,
address payable refundReceiver,
bytes memory signatures,
address msgSender
) external virtual;
function checkAfterExecution(bytes32 txHash, bool success) external virtual;
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
import "@gnosis.pm/safe-contracts/contracts/common/Enum.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@gnosis.pm/safe-contracts/contracts/interfaces/IERC165.sol";
import "./BaseGuard.sol";
/// @title Guardable - A contract that manages fallback calls made to this contract
contract Guardable is OwnableUpgradeable {
event ChangedGuard(address guard);
address public guard;
/// @dev Set a guard that checks transactions before execution
/// @param _guard The address of the guard to be used or the 0 address to disable the guard
function setGuard(address _guard) external onlyOwner {
if (_guard != address(0)) {
require(
BaseGuard(_guard).supportsInterface(type(IGuard).interfaceId),
"Guard does not implement IERC165"
);
}
guard = _guard;
emit ChangedGuard(guard);
}
function getGuard() external view returns (address _guard) {
return guard;
}
}
// SPDX-License-Identifier: LGPL-3.0-only
/// @title Zodiac Avatar - A contract that manages modules that can execute transactions via this contract.
pragma solidity >=0.7.0 <0.9.0;
import "@gnosis.pm/safe-contracts/contracts/common/Enum.sol";
interface IAvatar {
/// @dev Enables a module on the avatar.
/// @notice Can only be called by the avatar.
/// @notice Modules should be stored as a linked list.
/// @notice Must emit EnabledModule(address module) if successful.
/// @param module Module to be enabled.
function enableModule(address module) external;
/// @dev Disables a module on the avatar.
/// @notice Can only be called by the avatar.
/// @notice Must emit DisabledModule(address module) if successful.
/// @param prevModule Address that pointed to the module to be removed in the linked list
/// @param module Module to be removed.
function disableModule(address prevModule, address module) external;
/// @dev Allows a Module to execute a transaction.
/// @notice Can only be called by an enabled module.
/// @notice Must emit ExecutionFromModuleSuccess(address module) if successful.
/// @notice Must emit ExecutionFromModuleFailure(address module) if unsuccessful.
/// @param to Destination address of module transaction.
/// @param value Ether value of module transaction.
/// @param data Data payload of module transaction.
/// @param operation Operation type of module transaction: 0 == call, 1 == delegate call.
function execTransactionFromModule(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation
) external returns (bool success);
/// @dev Allows a Module to execute a transaction and return data
/// @notice Can only be called by an enabled module.
/// @notice Must emit ExecutionFromModuleSuccess(address module) if successful.
/// @notice Must emit ExecutionFromModuleFailure(address module) if unsuccessful.
/// @param to Destination address of module transaction.
/// @param value Ether value of module transaction.
/// @param data Data payload of module transaction.
/// @param operation Operation type of module transaction: 0 == call, 1 == delegate call.
function execTransactionFromModuleReturnData(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation
) external returns (bool success, bytes memory returnData);
/// @dev Returns if an module is enabled
/// @return True if the module is enabled
function isModuleEnabled(address module) external view returns (bool);
/// @dev Returns array of modules.
/// @param start Start of the page.
/// @param pageSize Maximum number of modules that should be returned.
/// @return array Array of modules.
/// @return next Start of the next page.
function getModulesPaginated(address start, uint256 pageSize)
external
view
returns (address[] memory array, address next);
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
import "@gnosis.pm/safe-contracts/contracts/common/Enum.sol";
interface IGuard {
function checkTransaction(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation,
uint256 safeTxGas,
uint256 baseGas,
uint256 gasPrice,
address gasToken,
address payable refundReceiver,
bytes memory signatures,
address msgSender
) external;
function checkAfterExecution(bytes32 txHash, bool success) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/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 {
_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);
}
uint256[49] private __gap;
}
// 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;
import "../proxy/utils/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 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;
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.8.0;
import "@gnosis.pm/zodiac/contracts/core/Module.sol";
import "./interfaces/RealitioV3.sol";
abstract contract RealityModule is Module {
bytes32 public constant INVALIDATED =
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
bytes32 public constant DOMAIN_SEPARATOR_TYPEHASH =
0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218;
// keccak256(
// "EIP712Domain(uint256 chainId,address verifyingContract)"
// );
bytes32 public constant TRANSACTION_TYPEHASH =
0x72e9670a7ee00f5fbf1049b8c38e3f22fab7e9b85029e85cf9412f17fdd5c2ad;
// keccak256(
// "Transaction(address to,uint256 value,bytes data,uint8 operation,uint256 nonce)"
// );
event ProposalQuestionCreated(
bytes32 indexed questionId,
string indexed proposalId
);
event RealityModuleSetup(
address indexed initiator,
address indexed owner,
address indexed avatar,
address target
);
RealitioV3 public oracle;
uint256 public template;
uint32 public questionTimeout;
uint32 public questionCooldown;
uint32 public answerExpiration;
address public questionArbitrator;
uint256 public minimumBond;
// Mapping of question hash to question id. Special case: INVALIDATED for question hashes that have been invalidated
mapping(bytes32 => bytes32) public questionIds;
// Mapping of questionHash to transactionHash to execution state
mapping(bytes32 => mapping(bytes32 => bool))
public executedProposalTransactions;
/// @param _owner Address of the owner
/// @param _avatar Address of the avatar (e.g. a Safe)
/// @param _target Address of the contract that will call exec function
/// @param _oracle Address of the oracle (e.g. Realitio)
/// @param timeout Timeout in seconds that should be required for the oracle
/// @param cooldown Cooldown in seconds that should be required after a oracle provided answer
/// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever)
/// @param bond Minimum bond that is required for an answer to be accepted
/// @param templateId ID of the template that should be used for proposal questions (see https://github.com/realitio/realitio-dapp#structuring-and-fetching-information)
/// @notice There need to be at least 60 seconds between end of cooldown and expiration
constructor(
address _owner,
address _avatar,
address _target,
RealitioV3 _oracle,
uint32 timeout,
uint32 cooldown,
uint32 expiration,
uint256 bond,
uint256 templateId
) {
bytes memory initParams = abi.encode(
_owner,
_avatar,
_target,
_oracle,
timeout,
cooldown,
expiration,
bond,
templateId
);
setUp(initParams);
}
function setUp(bytes memory initParams) public override {
(
address _owner,
address _avatar,
address _target,
RealitioV3 _oracle,
uint32 timeout,
uint32 cooldown,
uint32 expiration,
uint256 bond,
uint256 templateId
) = abi.decode(
initParams,
(
address,
address,
address,
RealitioV3,
uint32,
uint32,
uint32,
uint256,
uint256
)
);
__Ownable_init();
require(_avatar != address(0), "Avatar can not be zero address");
require(_target != address(0), "Target can not be zero address");
require(timeout > 0, "Timeout has to be greater 0");
require(
expiration == 0 || expiration - cooldown >= 60,
"There need to be at least 60s between end of cooldown and expiration"
);
avatar = _avatar;
target = _target;
oracle = _oracle;
answerExpiration = expiration;
questionTimeout = timeout;
questionCooldown = cooldown;
questionArbitrator = address(oracle);
minimumBond = bond;
template = templateId;
transferOwnership(_owner);
emit RealityModuleSetup(msg.sender, _owner, avatar, target);
}
/// @notice This can only be called by the owner
function setQuestionTimeout(uint32 timeout) public onlyOwner {
require(timeout > 0, "Timeout has to be greater 0");
questionTimeout = timeout;
}
/// @dev Sets the cooldown before an answer is usable.
/// @param cooldown Cooldown in seconds that should be required after a oracle provided answer
/// @notice This can only be called by the owner
/// @notice There need to be at least 60 seconds between end of cooldown and expiration
function setQuestionCooldown(uint32 cooldown) public onlyOwner {
uint32 expiration = answerExpiration;
require(
expiration == 0 || expiration - cooldown >= 60,
"There need to be at least 60s between end of cooldown and expiration"
);
questionCooldown = cooldown;
}
/// @dev Sets the duration for which a positive answer is valid.
/// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever)
/// @notice A proposal with an expired answer is the same as a proposal that has been marked invalid
/// @notice There need to be at least 60 seconds between end of cooldown and expiration
/// @notice This can only be called by the owner
function setAnswerExpiration(uint32 expiration) public onlyOwner {
require(
expiration == 0 || expiration - questionCooldown >= 60,
"There need to be at least 60s between end of cooldown and expiration"
);
answerExpiration = expiration;
}
/// @dev Sets the question arbitrator that will be used for future questions.
/// @param arbitrator Address of the arbitrator
/// @notice This can only be called by the owner
function setArbitrator(address arbitrator) public onlyOwner {
questionArbitrator = arbitrator;
}
/// @dev Sets the minimum bond that is required for an answer to be accepted.
/// @param bond Minimum bond that is required for an answer to be accepted
/// @notice This can only be called by the owner
function setMinimumBond(uint256 bond) public onlyOwner {
minimumBond = bond;
}
/// @dev Sets the template that should be used for future questions.
/// @param templateId ID of the template that should be used for proposal questions
/// @notice Check https://github.com/realitio/realitio-dapp#structuring-and-fetching-information for more information
/// @notice This can only be called by the owner
function setTemplate(uint256 templateId) public onlyOwner {
template = templateId;
}
/// @dev Function to add a proposal that should be considered for execution
/// @param proposalId Id that should identify the proposal uniquely
/// @param txHashes EIP-712 hashes of the transactions that should be executed
/// @notice The nonce used for the question by this function is always 0
function addProposal(string memory proposalId, bytes32[] memory txHashes)
public
{
addProposalWithNonce(proposalId, txHashes, 0);
}
/// @dev Function to add a proposal that should be considered for execution
/// @param proposalId Id that should identify the proposal uniquely
/// @param txHashes EIP-712 hashes of the transactions that should be executed
/// @param nonce Nonce that should be used when asking the question on the oracle
function addProposalWithNonce(
string memory proposalId,
bytes32[] memory txHashes,
uint256 nonce
) public {
// We generate the question string used for the oracle
string memory question = buildQuestion(proposalId, txHashes);
bytes32 questionHash = keccak256(bytes(question));
if (nonce > 0) {
// Previous nonce must have been invalidated by the oracle.
// However, if the proposal was internally invalidated, it should not be possible to ask it again.
bytes32 currentQuestionId = questionIds[questionHash];
require(
currentQuestionId != INVALIDATED,
"This proposal has been marked as invalid"
);
require(
oracle.resultFor(currentQuestionId) == INVALIDATED,
"Previous proposal was not invalidated"
);
} else {
require(
questionIds[questionHash] == bytes32(0),
"Proposal has already been submitted"
);
}
bytes32 expectedQuestionId = getQuestionId(question, nonce);
// Set the question hash for this question id
questionIds[questionHash] = expectedQuestionId;
bytes32 questionId = askQuestion(question, nonce);
require(expectedQuestionId == questionId, "Unexpected question id");
emit ProposalQuestionCreated(questionId, proposalId);
}
function askQuestion(string memory question, uint256 nonce)
internal
virtual
returns (bytes32);
/// @dev Marks a proposal as invalid, preventing execution of the connected transactions
/// @param proposalId Id that should identify the proposal uniquely
/// @param txHashes EIP-712 hashes of the transactions that should be executed
/// @notice This can only be called by the owner
function markProposalAsInvalid(
string memory proposalId,
bytes32[] memory txHashes // owner only is checked in markProposalAsInvalidByHash(bytes32)
) public {
string memory question = buildQuestion(proposalId, txHashes);
bytes32 questionHash = keccak256(bytes(question));
markProposalAsInvalidByHash(questionHash);
}
/// @dev Marks a question hash as invalid, preventing execution of the connected transactions
/// @param questionHash Question hash calculated based on the proposal id and txHashes
/// @notice This can only be called by the owner
function markProposalAsInvalidByHash(bytes32 questionHash)
public
onlyOwner
{
questionIds[questionHash] = INVALIDATED;
}
/// @dev Marks a proposal with an expired answer as invalid, preventing execution of the connected transactions
/// @param questionHash Question hash calculated based on the proposal id and txHashes
function markProposalWithExpiredAnswerAsInvalid(bytes32 questionHash)
public
{
uint32 expirationDuration = answerExpiration;
require(expirationDuration > 0, "Answers are valid forever");
bytes32 questionId = questionIds[questionHash];
require(questionId != INVALIDATED, "Proposal is already invalidated");
require(
questionId != bytes32(0),
"No question id set for provided proposal"
);
require(
oracle.resultFor(questionId) == bytes32(uint256(1)),
"Only positive answers can expire"
);
uint32 finalizeTs = oracle.getFinalizeTS(questionId);
require(
finalizeTs + uint256(expirationDuration) < block.timestamp,
"Answer has not expired yet"
);
questionIds[questionHash] = INVALIDATED;
}
/// @dev Executes the transactions of a proposal via the target if accepted
/// @param proposalId Id that should identify the proposal uniquely
/// @param txHashes EIP-712 hashes of the transactions that should be executed
/// @param to Target of the transaction that should be executed
/// @param value Wei value of the transaction that should be executed
/// @param data Data of the transaction that should be executed
/// @param operation Operation (Call or Delegatecall) of the transaction that should be executed
/// @notice The txIndex used by this function is always 0
function executeProposal(
string memory proposalId,
bytes32[] memory txHashes,
address to,
uint256 value,
bytes memory data,
Enum.Operation operation
) public {
executeProposalWithIndex(
proposalId,
txHashes,
to,
value,
data,
operation,
0
);
}
/// @dev Executes the transactions of a proposal via the target if accepted
/// @param proposalId Id that should identify the proposal uniquely
/// @param txHashes EIP-712 hashes of the transactions that should be executed
/// @param to Target of the transaction that should be executed
/// @param value Wei value of the transaction that should be executed
/// @param data Data of the transaction that should be executed
/// @param operation Operation (Call or Delegatecall) of the transaction that should be executed
/// @param txIndex Index of the transaction hash in txHashes. This is used as the nonce for the transaction, to make the tx hash unique
function executeProposalWithIndex(
string memory proposalId,
bytes32[] memory txHashes,
address to,
uint256 value,
bytes memory data,
Enum.Operation operation,
uint256 txIndex
) public {
// We use the hash of the question to check the execution state, as the other parameters might change, but the question not
bytes32 questionHash = keccak256(
bytes(buildQuestion(proposalId, txHashes))
);
// Lookup question id for this proposal
bytes32 questionId = questionIds[questionHash];
// Question hash needs to set to be eligible for execution
require(
questionId != bytes32(0),
"No question id set for provided proposal"
);
require(questionId != INVALIDATED, "Proposal has been invalidated");
bytes32 txHash = getTransactionHash(
to,
value,
data,
operation,
txIndex
);
require(txHashes[txIndex] == txHash, "Unexpected transaction hash");
// Check that the result of the question is 1 (true)
require(
oracle.resultFor(questionId) == bytes32(uint256(1)),
"Transaction was not approved"
);
uint256 minBond = minimumBond;
require(
minBond == 0 || minBond <= oracle.getBond(questionId),
"Bond on question not high enough"
);
uint32 finalizeTs = oracle.getFinalizeTS(questionId);
// The answer is valid in the time after the cooldown and before the expiration time (if set).
require(
finalizeTs + uint256(questionCooldown) < block.timestamp,
"Wait for additional cooldown"
);
uint32 expiration = answerExpiration;
require(
expiration == 0 ||
finalizeTs + uint256(expiration) >= block.timestamp,
"Answer has expired"
);
// Check this is either the first transaction in the list or that the previous question was already approved
require(
txIndex == 0 ||
executedProposalTransactions[questionHash][
txHashes[txIndex - 1]
],
"Previous transaction not executed yet"
);
// Check that this question was not executed yet
require(
!executedProposalTransactions[questionHash][txHash],
"Cannot execute transaction again"
);
// Mark transaction as executed
executedProposalTransactions[questionHash][txHash] = true;
// Execute the transaction via the target.
require(exec(to, value, data, operation), "Module transaction failed");
}
/// @dev Build the question by combining the proposalId and the hex string of the hash of the txHashes
/// @param proposalId Id of the proposal that proposes to execute the transactions represented by the txHashes
/// @param txHashes EIP-712 Hashes of the transactions that should be executed
function buildQuestion(string memory proposalId, bytes32[] memory txHashes)
public
pure
returns (string memory)
{
string memory txsHash = bytes32ToAsciiString(
keccak256(abi.encodePacked(txHashes))
);
return string(abi.encodePacked(proposalId, bytes3(0xe2909f), txsHash));
}
/// @dev Generate the question id.
/// @notice It is required that this is the same as for the oracle implementation used.
function getQuestionId(string memory question, uint256 nonce)
public
view
returns (bytes32)
{
// Ask the question with a starting time of 0, so that it can be immediately answered
bytes32 contentHash = keccak256(
abi.encodePacked(template, uint32(0), question)
);
return
keccak256(
abi.encodePacked(
contentHash,
questionArbitrator,
questionTimeout,
minimumBond,
oracle,
this,
nonce
)
);
}
/// @dev Returns the chain id used by this contract.
function getChainId() public view returns (uint256) {
uint256 id;
// solium-disable-next-line security/no-inline-assembly
assembly {
id := chainid()
}
return id;
}
/// @dev Generates the data for the module transaction hash (required for signing)
function generateTransactionHashData(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation,
uint256 nonce
) public view returns (bytes memory) {
uint256 chainId = getChainId();
bytes32 domainSeparator = keccak256(
abi.encode(DOMAIN_SEPARATOR_TYPEHASH, chainId, this)
);
bytes32 transactionHash = keccak256(
abi.encode(
TRANSACTION_TYPEHASH,
to,
value,
keccak256(data),
operation,
nonce
)
);
return
abi.encodePacked(
bytes1(0x19),
bytes1(0x01),
domainSeparator,
transactionHash
);
}
function getTransactionHash(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation,
uint256 nonce
) public view returns (bytes32) {
return
keccak256(
generateTransactionHashData(to, value, data, operation, nonce)
);
}
function bytes32ToAsciiString(bytes32 _bytes)
internal
pure
returns (string memory)
{
bytes memory s = new bytes(64);
for (uint256 i = 0; i < 32; i++) {
uint8 b = uint8(bytes1(_bytes << (i * 8)));
uint8 hi = uint8(b) / 16;
uint8 lo = uint8(b) % 16;
s[2 * i] = char(hi);
s[2 * i + 1] = char(lo);
}
return string(s);
}
function char(uint8 b) internal pure returns (bytes1 c) {
if (b < 10) return bytes1(b + 0x30);
else return bytes1(b + 0x57);
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.8.0;
import "./RealityModule.sol";
import "./interfaces/RealitioV3.sol";
contract RealityModuleERC20 is RealityModule {
/// @param _owner Address of the owner
/// @param _avatar Address of the avatar (e.g. a Safe)
/// @param _target Address of the contract that will call exec function
/// @param _oracle Address of the oracle (e.g. Realitio)
/// @param timeout Timeout in seconds that should be required for the oracle
/// @param cooldown Cooldown in seconds that should be required after a oracle provided answer
/// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever)
/// @param bond Minimum bond that is required for an answer to be accepted
/// @param templateId ID of the template that should be used for proposal questions (see https://github.com/realitio/realitio-dapp#structuring-and-fetching-information)
/// @notice There need to be at least 60 seconds between end of cooldown and expiration
constructor(
address _owner,
address _avatar,
address _target,
RealitioV3 _oracle,
uint32 timeout,
uint32 cooldown,
uint32 expiration,
uint256 bond,
uint256 templateId
)
RealityModule(
_owner,
_avatar,
_target,
_oracle,
timeout,
cooldown,
expiration,
bond,
templateId
)
{}
function askQuestion(string memory question, uint256 nonce)
internal
override
returns (bytes32)
{
// Ask the question with a starting time of 0, so that it can be immediately answered
return
RealitioV3ERC20(address(oracle)).askQuestionWithMinBondERC20(
template,
question,
questionArbitrator,
questionTimeout,
0,
nonce,
minimumBond,
0
);
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.8.0;
interface RealitioV3 {
/// @notice Report whether the answer to the specified question is finalized
/// @param question_id The ID of the question
/// @return Return true if finalized
function isFinalized(bytes32 question_id) external view returns (bool);
/// @notice Return the final answer to the specified question, or revert if there isn't one
/// @param question_id The ID of the question
/// @return The answer formatted as a bytes32
function resultFor(bytes32 question_id) external view returns (bytes32);
/// @notice Returns the timestamp at which the question will be/was finalized
/// @param question_id The ID of the question
function getFinalizeTS(bytes32 question_id) external view returns (uint32);
/// @notice Returns whether the question is pending arbitration
/// @param question_id The ID of the question
function isPendingArbitration(bytes32 question_id)
external
view
returns (bool);
/// @notice Create a reusable template, which should be a JSON document.
/// Placeholders should use gettext() syntax, eg %s.
/// @dev Template data is only stored in the event logs, but its block number is kept in contract storage.
/// @param content The template content
/// @return The ID of the newly-created template, which is created sequentially.
function createTemplate(string calldata content) external returns (uint256);
/// @notice Returns the highest bond posted so far for a question
/// @param question_id The ID of the question
function getBond(bytes32 question_id) external view returns (uint256);
/// @notice Returns the questions's content hash, identifying the question content
/// @param question_id The ID of the question
function getContentHash(bytes32 question_id)
external
view
returns (bytes32);
}
interface RealitioV3ETH is RealitioV3 {
/// @notice Ask a new question and return the ID
/// @dev Template data is only stored in the event logs, but its block number is kept in contract storage.
/// @param template_id The ID number of the template the question will use
/// @param question A string containing the parameters that will be passed into the template to make the question
/// @param arbitrator The arbitration contract that will have the final word on the answer if there is a dispute
/// @param timeout How long the contract should wait after the answer is changed before finalizing on that answer
/// @param opening_ts If set, the earliest time it should be possible to answer the question.
/// @param nonce A user-specified nonce used in the question ID. Change it to repeat a question.
/// @param min_bond The minimum bond that may be used for an answer.
/// @return The ID of the newly-created question, created deterministically.
function askQuestionWithMinBond(
uint256 template_id,
string memory question,
address arbitrator,
uint32 timeout,
uint32 opening_ts,
uint256 nonce,
uint256 min_bond
) external payable returns (bytes32);
}
interface RealitioV3ERC20 is RealitioV3 {
/// @notice Ask a new question and return the ID
/// @dev Template data is only stored in the event logs, but its block number is kept in contract storage.
/// @param template_id The ID number of the template the question will use
/// @param question A string containing the parameters that will be passed into the template to make the question
/// @param arbitrator The arbitration contract that will have the final word on the answer if there is a dispute
/// @param timeout How long the contract should wait after the answer is changed before finalizing on that answer
/// @param opening_ts If set, the earliest time it should be possible to answer the question.
/// @param nonce A user-specified nonce used in the question ID. Change it to repeat a question.
/// @param min_bond The minimum bond that may be used for an answer.
/// @param tokens Number of tokens sent
/// @return The ID of the newly-created question, created deterministically.
function askQuestionWithMinBondERC20(
uint256 template_id,
string memory question,
address arbitrator,
uint32 timeout,
uint32 opening_ts,
uint256 nonce,
uint256 min_bond,
uint256 tokens
) external returns (bytes32);
}
|
Function to add a proposal that should be considered for execution proposalId Id that should identify the proposal uniquely txHashes EIP-712 hashes of the transactions that should be executed The nonce used for the question by this function is always 0
|
function addProposal(string memory proposalId, bytes32[] memory txHashes)
public
{
addProposalWithNonce(proposalId, txHashes, 0);
}
| 1,390,538
|
./full_match/3/0x666ADE724b3cEc31f249F799e832b930cE8FA3cC/sources/contracts/Marketplace.sol
|
cancel ongoing auction stops the ongoing auction and if bidder exists refund the bidders amount _tokenId TokenId of NFT
|
function cancelAuction(uint256 _tokenId)
public
payable
IsTokenOwner(_tokenId)
{
Auction storage act = TokenAuctions[_tokenId];
act.onAuction = false;
if (act.currentBidder != address(0)) {
address payable currentBidder = payable(act.currentBidder);
currentBidder.transfer(act.currentBidPrice);
}
emit AuctionCancelled(_tokenId);
}
| 8,279,453
|
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "../library/Initializable.sol";
import "../library/ReentrancyGuard.sol";
import "../library/Ownable.sol";
import "../library/ERC20.sol";
import "../library/SafeRatioMath.sol";
import "../interface/IInterestRateModelInterface.sol";
import "./MSDController.sol";
import "./MSD.sol";
/**
* @title dForce's Multi-currency Stable Debt Saving Token
* @author dForce
*/
contract MSDS is Initializable, ReentrancyGuard, Ownable, ERC20 {
using SafeERC20Upgradeable for IERC20Upgradeable;
using SafeRatioMath for uint256;
bytes32 public DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 chainId, uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH =
0x576144ed657c8304561e56ca632e17751956250114636e8c01f64a7f2c6d98cf;
mapping(address => uint256) public nonces;
/**
* @dev The underlying MSD.
*/
address public underlying;
/**
* @dev Initial exchange rate(scaled by 1e18).
*/
uint256 constant initialExchangeRate = 1e18;
/**
* @dev The exchange rate between MSDS and underlying MSD(scaled by 1e18).
*/
uint256 internal exchangeRate;
/**
* @dev Current interest rate model contract.
*/
IInterestRateModelInterface public interestRateModel;
/**
* @dev Block number that interest was last accrued at.
*/
uint256 public accrualBlockNumber;
/**
* @dev MSD Controller to mint MSD token and to inform when accruing interest
*/
MSDController public msdController;
event NewInterestRateModel(
IInterestRateModelInterface oldInterestRateModel,
IInterestRateModelInterface newInterestRateModel
);
event NewMSDController(
MSDController oldMSDController,
MSDController newMSDController
);
/**
* @notice Expects to call only once to initialize the MSD token.
* @param _name Token name.
* @param _symbol Token symbol.
*/
function initialize(
string memory _name,
string memory _symbol,
address _underlying,
IInterestRateModelInterface _interestRateModel,
MSDController _msdController
) external initializer {
require(
address(_msdController) != address(0),
"initialize: MSD controller address should not be zero address!"
);
require(
address(_interestRateModel) != address(0),
"initialize: interest model address should not be zero address!"
);
__Ownable_init();
__ERC20_init(_name, _symbol, ERC20(_underlying).decimals());
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
),
keccak256(bytes(_name)),
keccak256(bytes("1")),
_getChainId(),
address(this)
)
);
underlying = _underlying;
exchangeRate = initialExchangeRate;
interestRateModel = _interestRateModel;
msdController = _msdController;
}
/**
* @dev Sets a new interest rate model.
* @param _newInterestRateModel The new interest rate model.
*/
function _setInterestRateModel(
IInterestRateModelInterface _newInterestRateModel
) external onlyOwner {
// Gets current interest rate model.
IInterestRateModelInterface _oldInterestRateModel = interestRateModel;
// Ensures the input address is the interest model contract.
require(
_newInterestRateModel.isInterestRateModel(),
"_setInterestRateModel: This is not the rate model contract!"
);
// Set to the new interest rate model.
interestRateModel = _newInterestRateModel;
emit NewInterestRateModel(_oldInterestRateModel, _newInterestRateModel);
}
/**
* @dev Sets a new MSD controller.
* @param _newMSDController The new MSD controller
*/
function _setMSDController(MSDController _newMSDController)
external
onlyOwner
{
MSDController _oldMSDController = msdController;
// Ensures the input address is a MSDController contract.
require(
_newMSDController.isMSDController(),
"_setMSDController: This is not MSD controller contract!"
);
msdController = _newMSDController;
emit NewMSDController(_oldMSDController, _newMSDController);
}
function _updateInterest() internal {
// When more calls in the same block, only the first one takes effect, so for the
// following calls, nothing updates.
if (block.number != accrualBlockNumber) {
// Start accumulating interest after first mint
if (totalSupply != 0) {
// Calculates the number of blocks elapsed since the last accrual.
uint256 _blockDelta = block.number.sub(accrualBlockNumber);
// Gets the current supply interest rate.
uint256 _interestRate =
interestRateModel.getSupplyRate(0, 0, 0, 0);
/*
* Calculates the interest accumulated and the new exchange rate:
* simpleInterestFactor = interestRate * blockDelta
* exchangeRate = exchangeRate + simpleInterestFactor * exchangeRate
*/
uint256 _simpleInterestFactor = _interestRate.mul(_blockDelta);
uint256 _exchangeRateInc =
exchangeRate.rmul(_simpleInterestFactor);
uint256 _interestAccured = totalSupply.rmul(_exchangeRateInc);
// Notify the MSD controller to update debt
if (_interestAccured > 0) {
msdController.addDebt(underlying, _interestAccured);
}
exchangeRate = exchangeRate.add(_exchangeRateInc);
// Emits an `UpdateInterest` event.
// emit UpdateInterest(block.number, exchangeRate);
}
accrualBlockNumber = block.number;
}
}
/**
* @dev Calculates interest and update exchange rate.
*/
modifier settleInterest() {
_updateInterest();
_;
}
/**
* @notice Supposed to transfer underlying token into this contract
* @dev MSDS burns the amount of underlying rather than transfering.
*/
function _doTransferIn(address _sender, uint256 _amount)
internal
returns (uint256)
{
MSD(underlying).burn(_sender, _amount);
return _amount;
}
/**
* @notice Supposed to transfer underlying token to `_recipient`
* @dev MSDS mint the amount of underlying rather than transfering.
* this can be called by `borrow()` and `_withdrawReserves()`
*/
function _doTransferOut(address payable _recipient, uint256 _amount)
internal
{
msdController.mintMSD(underlying, _recipient, _amount);
}
/**
* @notice Mint MSDS `amount` underlying MSD token into `account`.
* @param _account the address to mint MSDS to.
* @param _amount The amount of underlying MSD to mint.
*/
function mint(address _account, uint256 _amount)
external
nonReentrant
settleInterest
{
uint256 _amountIn = _doTransferIn(msg.sender, _amount);
_mint(_account, _amountIn.rdiv(exchangeRate));
}
/**
* @notice Redeem MSDS `amount` MSDS token from `account` and return corresponding underlying MSD.
* @param _account the address to redeem MSDS from.
* @param _amount The amount of MSDS to redeem.
*/
function redeem(address _account, uint256 _amount)
external
nonReentrant
settleInterest
{
_burnFrom(_account, _amount);
_doTransferOut(msg.sender, _amount.rmul(exchangeRate));
}
/**
* @notice Redeem `amount` of underlying MSD token from `account`.
* @param _account the address to redeem MSDS from.
* @param _underlyingAmount The amount of underlying MSD to redeem.
*/
function redeemUnderlying(address _account, uint256 _underlyingAmount)
external
nonReentrant
settleInterest
{
_burnFrom(_account, _underlyingAmount.rdivup(exchangeRate));
_doTransferOut(msg.sender, _underlyingAmount);
}
/**
* @notice Calculates interest and update exchange rate.
* @dev Updates exchange rate with any accumulated interest.
*/
function updateInterest() external returns (bool) {
_updateInterest();
return true;
}
/**
* @dev Gets the underlying balance of user without accruing interest.
*/
function balanceOfUnderlyingStored(address _account)
external
view
returns (uint256)
{
return balanceOf[_account].mul(exchangeRate);
}
/**
* @dev Gets the borrow balance of user with the latest `exchangeRate`.
*/
function balanceOfUnderlyingCurrent(address _account)
external
returns (uint256)
{
return balanceOf[_account].mul(exchangeRateCurrent());
}
/**
* @dev Gets the newest exchange rate by accruing interest.
*/
function exchangeRateCurrent() public settleInterest returns (uint256) {
return exchangeRate;
}
/**
* @dev Gets the newest exchange rate without accruing interest.
*/
function exchangeRateStored() external view returns (uint256) {
return exchangeRate;
}
/**
* @dev Returns the current per-block saving interest rate.
*/
function supplyRatePerBlock() public view returns (uint256) {
return interestRateModel.getSupplyRate(0, 0, 0, 0);
}
function _getChainId() internal pure returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
/**
* @dev EIP2612 permit function. For more details, please look at here:
* https://eips.ethereum.org/EIPS/eip-2612
* @param _owner The owner of the funds.
* @param _spender The spender.
* @param _value The amount.
* @param _deadline The deadline timestamp, type(uint256).max for max deadline.
* @param _v Signature param.
* @param _s Signature param.
* @param _r Signature param.
*/
function permit(
address _owner,
address _spender,
uint256 _value,
uint256 _deadline,
uint8 _v,
bytes32 _r,
bytes32 _s
) external {
require(_deadline >= block.timestamp, "permit: EXPIRED!");
uint256 _currentNonce = nonces[_owner];
bytes32 _digest =
keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
PERMIT_TYPEHASH,
_owner,
_spender,
_getChainId(),
_value,
_currentNonce,
_deadline
)
)
)
);
address _recoveredAddress = ecrecover(_digest, _v, _r, _s);
require(
_recoveredAddress != address(0) && _recoveredAddress == _owner,
"permit: INVALID_SIGNATURE!"
);
nonces[_owner] = _currentNonce.add(1);
_approve(_owner, _spender, _value);
}
}
|
Calculates interest and update exchange rate. Updates exchange rate with any accumulated interest./
|
function updateInterest() external returns (bool) {
_updateInterest();
return true;
}
| 926,661
|
import "@openzeppelin/contracts/ownership/Ownable.sol";
import { RoleManagement } from "./RoleManagement.sol";
pragma solidity ^0.5.0;
/* The Registry contract keeps track of the land registry of the city. Every house should be registered in this contract */
contract Registry is Ownable,RoleManagement{
//address public owner;
/* Data model that allows me to have a stucts with delete and index */
struct Property {
address payable owner;
uint listPointer;
}
//variables
mapping(uint => Property) public properties;
uint[] public propertyList;
//events
event LogNewProperty(uint _pin, address _owner);
event LogDeleteProperty(uint _pin);
event LogUpdateProperty(address _oldOwner,address _newOwner,address sender);
constructor() public{
properties[1].owner = 0xDf7064894A0da6b741b86104af7875647b7767A3;
properties[1].listPointer = propertyList.push(1)-1;
grantPermission(msg.sender,'Admin');
}
/// @dev function that allows to retrieve all the pin
/// @return an array of ints representing the properties
function listProperties() public view returns(uint[] memory ){
return propertyList;
}
function getPropertyOwner(uint pin) public view returns(address payable){
return properties[pin].owner;
}
/// @dev check if a PIN (property identification number) exists
/// @param pin which is the pin
/// @return the owner of this pin if it exists
function isProperty(uint pin) public view returns(address) {
require(propertyList.length>0,"There is no property yet");
if(propertyList[properties[pin].listPointer] == pin) {
return properties[pin].owner;
}else{
return address(0);
}
}
/// @dev Check the number of property on the blockchain
/// @return the number of property on the blockchain
function getPropertyCount() public view returns(uint propertyCount) {
return propertyList.length;
}
/// @dev create a new property on the blockchain
/// @param ownerAddress is the owner of the property
/// @param pin is the corresponding pin
/// @return true to notify everything went well
function newProperty(address payable ownerAddress, uint pin) public returns(bool success) {
require(properties[pin].owner==address(0),"This PIN already exist");
properties[pin].owner = ownerAddress;
properties[pin].listPointer = propertyList.push(pin)-1;
emit LogNewProperty(pin,ownerAddress);
return true;
}
/// @dev allows the owner of the contract to change the owner of a property
/// @param ownerAddress is the new owner of the property
/// @param pin is the corresponding pin
/// @return true to notify everything went well
function updateProperty(address payable ownerAddress, uint pin) public onlyAdmin() returns(bool success) {
require(isProperty(pin)!=address(0),"This PIN doens't exist or no property on the blockchain");
address oldOwner=properties[pin].owner;
properties[pin].owner = ownerAddress;
emit LogUpdateProperty(oldOwner,ownerAddress,msg.sender);
return true;
}
/// @dev allows the owner to delete a property on the blockchain
/// @param pin pin of the property the owner wants to delete
/// @return true to notify everything went well
function deleteProperty(uint pin) public onlyAdmin() returns(bool success) {
require(properties[pin].owner!=address(0),"This PIN doens't exist");
uint rowToDelete = properties[pin].listPointer;
uint keyToMove = propertyList[propertyList.length-1];
properties[pin].owner=address(0);
propertyList[rowToDelete] = keyToMove;
properties[keyToMove].listPointer = rowToDelete;
propertyList.length--;
emit LogDeleteProperty(pin);
return true;
}
}
|
check if a PIN (property identification number) exists pin which is the pin return the owner of this pin if it exists
|
function isProperty(uint pin) public view returns(address) {
require(propertyList.length>0,"There is no property yet");
if(propertyList[properties[pin].listPointer] == pin) {
return properties[pin].owner;
return address(0);
}
}
| 887,902
|
./full_match/1/0x61e0749C835f7Eca584DD83f93358C75712752E6/sources/browser/arb03.sol
|
Transfer contract ownership
|
function transferOwnership (address _manager) external payable OnlyManager{
manager = _manager;
}
| 3,101,801
|
pragma solidity >=0.4.0;
// 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;
// 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);
}
}
pragma solidity >=0.5.0;
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;
}
pragma solidity >=0.5.0;
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;
}
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
pragma solidity >=0.6.2;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
pragma solidity >=0.5.0;
import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol';
import '@uniswap/lib/contracts/libraries/FixedPoint.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;
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.3;
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import "@uniswap/lib/contracts/libraries/FixedPoint.sol";
import "@uniswap/v2-periphery/contracts/libraries/UniswapV2OracleLibrary.sol";
import "./interfaces/IOracleSimple.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 OracleSimple is IOracleSimple {
using FixedPoint for *;
/* solhint-disable var-name-mixedcase */
uint256 public immutable PERIOD;
IUniswapV2Pair public immutable PAIR;
/* solhint-enable */
address public immutable token0;
address public immutable token1;
uint256 public price0CumulativeLast;
uint256 public price1CumulativeLast;
uint32 public blockTimestampLast;
FixedPoint.uq112x112 public price0Average;
FixedPoint.uq112x112 public price1Average;
bool public isStale;
constructor(address _pair, uint256 _period) {
PERIOD = _period;
IUniswapV2Pair pair = IUniswapV2Pair(_pair);
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, "OracleSimple: NO_RESERVES"); // ensure that there's liquidity in the pair
}
function update() external override returns (bool) {
(uint256 price0Cumulative, uint256 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
if (timeElapsed < PERIOD) return false;
// 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;
return true;
}
// note this will always return 0 before update has been called successfully for the first time.
function consult(address token, uint256 amountIn)
external
view
override
returns (uint256 amountOut)
{
if (token == token0) {
amountOut = price0Average.mul(amountIn).decode144();
} else {
require(token == token1, "OracleSimple: INVALID_TOKEN");
amountOut = price1Average.mul(amountIn).decode144();
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "./OracleSimple.sol";
import "./interfaces/ISwapManager.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
contract SwapManager is ISwapManager {
uint256 public constant override N_DEX = 2;
/* solhint-disable */
string[N_DEX] public DEXES = ["UNISWAP", "SUSHISWAP"];
IUniswapV2Router02[N_DEX] public override ROUTERS = [
IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D),
IUniswapV2Router02(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F)
];
IUniswapV2Factory[N_DEX] public FACTORIES = [
IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f),
IUniswapV2Factory(0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac)
];
/* solhint-enable */
address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
function bestOutputFixedInput(
address _from,
address _to,
uint256 _amountIn
)
external
view
override
returns (
address[] memory path,
uint256 amountOut,
uint256 rIdx
)
{
// Iterate through each DEX and evaluate the best output
for (uint256 i = 0; i < N_DEX; i++) {
(address[] memory tPath, uint256 tAmountOut) =
bestPathFixedInput(_from, _to, _amountIn, i);
if (tAmountOut > amountOut) {
path = tPath;
amountOut = tAmountOut;
rIdx = i;
}
}
return (path, amountOut, rIdx);
}
function bestPathFixedInput(
address _from,
address _to,
uint256 _amountIn,
uint256 _i
) public view override returns (address[] memory path, uint256 amountOut) {
path = new address[](2);
path[0] = _from;
path[1] = _to;
if (_from == WETH || _to == WETH) {
amountOut = safeGetAmountsOut(_amountIn, path, _i)[path.length - 1];
return (path, amountOut);
}
address[] memory pathB = new address[](3);
pathB[0] = _from;
pathB[1] = WETH;
pathB[2] = _to;
// is one of these WETH
if (FACTORIES[_i].getPair(_from, _to) == address(0x0)) {
// does a direct liquidity pair not exist?
amountOut = safeGetAmountsOut(_amountIn, pathB, _i)[pathB.length - 1];
path = pathB;
} else {
// if a direct pair exists, we want to know whether pathA or path B is better
(path, amountOut) = comparePathsFixedInput(path, pathB, _amountIn, _i);
}
}
function bestInputFixedOutput(
address _from,
address _to,
uint256 _amountOut
)
external
view
override
returns (
address[] memory path,
uint256 amountIn,
uint256 rIdx
)
{
// Iterate through each DEX and evaluate the best input
for (uint256 i = 0; i < N_DEX; i++) {
(address[] memory tPath, uint256 tAmountIn) =
bestPathFixedOutput(_from, _to, _amountOut, i);
if (amountIn == 0 || tAmountIn < amountIn) {
if (tAmountIn != 0) {
path = tPath;
amountIn = tAmountIn;
rIdx = i;
}
}
}
}
function bestPathFixedOutput(
address _from,
address _to,
uint256 _amountOut,
uint256 _i
) public view override returns (address[] memory path, uint256 amountIn) {
path = new address[](2);
path[0] = _from;
path[1] = _to;
if (_from == WETH || _to == WETH) {
amountIn = safeGetAmountsIn(_amountOut, path, _i)[0];
return (path, amountIn);
}
address[] memory pathB = new address[](3);
pathB[0] = _from;
pathB[1] = WETH;
pathB[2] = _to;
// is one of these WETH
if (FACTORIES[_i].getPair(_from, _to) == address(0x0)) {
// does a direct liquidity pair not exist?
amountIn = safeGetAmountsIn(_amountOut, pathB, _i)[0];
path = pathB;
} else {
// if a direct pair exists, we want to know whether pathA or path B is better
(path, amountIn) = comparePathsFixedOutput(path, pathB, _amountOut, _i);
}
}
// Rather than let the getAmountsOut call fail due to low liquidity, we
// catch the error and return 0 in place of the reversion
// this is useful when we want to proceed with logic
function safeGetAmountsOut(
uint256 _amountIn,
address[] memory _path,
uint256 _i
) public view override returns (uint256[] memory result) {
try ROUTERS[_i].getAmountsOut(_amountIn, _path) returns (uint256[] memory amounts) {
result = amounts;
} catch {
result = new uint256[](_path.length);
result[0] = _amountIn;
}
}
// Just a wrapper for the uniswap call
// This can fail (revert) in two scenarios
// 1. (path.length == 2 && insufficient reserves)
// 2. (path.length > 2 and an intermediate pair has an output amount of 0)
function unsafeGetAmountsOut(
uint256 _amountIn,
address[] memory _path,
uint256 _i
) public view override returns (uint256[] memory result) {
result = ROUTERS[_i].getAmountsOut(_amountIn, _path);
}
// Rather than let the getAmountsIn call fail due to low liquidity, we
// catch the error and return 0 in place of the reversion
// this is useful when we want to proceed with logic (occurs when amountOut is
// greater than avaiable reserve (ds-math-sub-underflow)
function safeGetAmountsIn(
uint256 _amountOut,
address[] memory _path,
uint256 _i
) public view override returns (uint256[] memory result) {
try ROUTERS[_i].getAmountsIn(_amountOut, _path) returns (uint256[] memory amounts) {
result = amounts;
} catch {
result = new uint256[](_path.length);
result[_path.length - 1] = _amountOut;
}
}
// Just a wrapper for the uniswap call
// This can fail (revert) in one scenario
// 1. amountOut provided is greater than reserve for out currency
function unsafeGetAmountsIn(
uint256 _amountOut,
address[] memory _path,
uint256 _i
) public view override returns (uint256[] memory result) {
result = ROUTERS[_i].getAmountsIn(_amountOut, _path);
}
function comparePathsFixedInput(
address[] memory pathA,
address[] memory pathB,
uint256 _amountIn,
uint256 _i
) public view override returns (address[] memory path, uint256 amountOut) {
path = pathA;
amountOut = safeGetAmountsOut(_amountIn, pathA, _i)[pathA.length - 1];
uint256 bAmountOut = safeGetAmountsOut(_amountIn, pathB, _i)[pathB.length - 1];
if (bAmountOut > amountOut) {
path = pathB;
amountOut = bAmountOut;
}
}
function comparePathsFixedOutput(
address[] memory pathA,
address[] memory pathB,
uint256 _amountOut,
uint256 _i
) public view override returns (address[] memory path, uint256 amountIn) {
path = pathA;
amountIn = safeGetAmountsIn(_amountOut, pathA, _i)[0];
uint256 bAmountIn = safeGetAmountsIn(_amountOut, pathB, _i)[0];
if (bAmountIn < amountIn) {
path = pathB;
amountIn = bAmountIn;
}
}
// TWAP Oracle Factory
address[] private _oracles;
mapping(address => bool) private _isOurs;
// Pair -> period -> oracle
mapping(address => mapping(uint256 => address)) private _oraclesByPair;
function ours(address a) external view override returns (bool) {
return _isOurs[a];
}
function oracleCount() external view override returns (uint256) {
return _oracles.length;
}
function oracleAt(uint256 idx) external view override returns (address) {
require(idx < _oracles.length, "Index exceeds list length");
return _oracles[idx];
}
function getOracle(
address _tokenA,
address _tokenB,
uint256 _period,
uint256 _i
) external view override returns (address) {
return _oraclesByPair[FACTORIES[_i].getPair(_tokenA, _tokenB)][_period];
}
function createOrUpdateOracle(
address _tokenA,
address _tokenB,
uint256 _period,
uint256 _i
) external override returns (address oracleAddr) {
address pair = FACTORIES[_i].getPair(_tokenA, _tokenB);
require(pair != address(0), "Nonexistant-pair");
// If the oracle exists, try to update it
if (_oraclesByPair[pair][_period] != address(0)) {
OracleSimple(_oraclesByPair[pair][_period]).update();
oracleAddr = _oraclesByPair[pair][_period];
return oracleAddr;
}
// create new oracle contract
oracleAddr = address(new OracleSimple(pair, _period));
// remember oracle
_oracles.push(oracleAddr);
_isOurs[oracleAddr] = true;
_oraclesByPair[pair][_period] = oracleAddr;
// log creation
emit OracleCreated(msg.sender, oracleAddr, _period);
}
function consultForFree(
address _from,
address _to,
uint256 _amountIn,
uint256 _period,
uint256 _i
) public view override returns (uint256 amountOut, uint256 lastUpdatedAt) {
OracleSimple oracle =
OracleSimple(_oraclesByPair[FACTORIES[_i].getPair(_from, _to)][_period]);
lastUpdatedAt = oracle.blockTimestampLast();
amountOut = oracle.consult(_from, _amountIn);
}
/// get the data we want and pay the gas to update
function consult(
address _from,
address _to,
uint256 _amountIn,
uint256 _period,
uint256 _i
)
public
override
returns (
uint256 amountOut,
uint256 lastUpdatedAt,
bool updated
)
{
OracleSimple oracle =
OracleSimple(_oraclesByPair[FACTORIES[_i].getPair(_from, _to)][_period]);
lastUpdatedAt = oracle.blockTimestampLast();
amountOut = oracle.consult(_from, _amountIn);
try oracle.update() {
updated = true;
} catch {
updated = false;
}
}
function updateOracles() external override returns (uint256 updated, uint256 expected) {
expected = _oracles.length;
for (uint256 i = 0; i < expected; i++) {
if (OracleSimple(_oracles[i]).update()) updated++;
}
}
function updateOracles(address[] memory _oracleAddrs)
external
override
returns (uint256 updated, uint256 expected)
{
expected = _oracleAddrs.length;
for (uint256 i = 0; i < expected; i++) {
if (OracleSimple(_oracleAddrs[i]).update()) updated++;
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.3;
interface IOracleSimple {
function update() external returns (bool);
function consult(address token, uint256 amountIn) external view returns (uint256 amountOut);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
/* solhint-disable func-name-mixedcase */
interface ISwapManager {
event OracleCreated(address indexed _sender, address indexed _newOracle, uint256 _period);
function N_DEX() external view returns (uint256);
function ROUTERS(uint256 i) external view returns (IUniswapV2Router02);
function bestOutputFixedInput(
address _from,
address _to,
uint256 _amountIn
)
external
view
returns (
address[] memory path,
uint256 amountOut,
uint256 rIdx
);
function bestPathFixedInput(
address _from,
address _to,
uint256 _amountIn,
uint256 _i
) external view returns (address[] memory path, uint256 amountOut);
function bestInputFixedOutput(
address _from,
address _to,
uint256 _amountOut
)
external
view
returns (
address[] memory path,
uint256 amountIn,
uint256 rIdx
);
function bestPathFixedOutput(
address _from,
address _to,
uint256 _amountOut,
uint256 _i
) external view returns (address[] memory path, uint256 amountIn);
function safeGetAmountsOut(
uint256 _amountIn,
address[] memory _path,
uint256 _i
) external view returns (uint256[] memory result);
function unsafeGetAmountsOut(
uint256 _amountIn,
address[] memory _path,
uint256 _i
) external view returns (uint256[] memory result);
function safeGetAmountsIn(
uint256 _amountOut,
address[] memory _path,
uint256 _i
) external view returns (uint256[] memory result);
function unsafeGetAmountsIn(
uint256 _amountOut,
address[] memory _path,
uint256 _i
) external view returns (uint256[] memory result);
function comparePathsFixedInput(
address[] memory pathA,
address[] memory pathB,
uint256 _amountIn,
uint256 _i
) external view returns (address[] memory path, uint256 amountOut);
function comparePathsFixedOutput(
address[] memory pathA,
address[] memory pathB,
uint256 _amountOut,
uint256 _i
) external view returns (address[] memory path, uint256 amountIn);
function ours(address a) external view returns (bool);
function oracleCount() external view returns (uint256);
function oracleAt(uint256 idx) external view returns (address);
function getOracle(
address _tokenA,
address _tokenB,
uint256 _period,
uint256 _i
) external view returns (address);
function createOrUpdateOracle(
address _tokenA,
address _tokenB,
uint256 _period,
uint256 _i
) external returns (address oracleAddr);
function consultForFree(
address _from,
address _to,
uint256 _amountIn,
uint256 _period,
uint256 _i
) external view returns (uint256 amountOut, uint256 lastUpdatedAt);
/// get the data we want and pay the gas to update
function consult(
address _from,
address _to,
uint256 _amountIn,
uint256 _period,
uint256 _i
)
external
returns (
uint256 amountOut,
uint256 lastUpdatedAt,
bool updated
);
function updateOracles() external returns (uint256 updated, uint256 expected);
function updateOracles(address[] memory _oracleAddrs)
external
returns (uint256 updated, uint256 expected);
}
|
Iterate through each DEX and evaluate the best input
|
function bestInputFixedOutput(
address _from,
address _to,
uint256 _amountOut
)
external
view
override
returns (
address[] memory path,
uint256 amountIn,
uint256 rIdx
)
{
for (uint256 i = 0; i < N_DEX; i++) {
(address[] memory tPath, uint256 tAmountIn) =
bestPathFixedOutput(_from, _to, _amountOut, i);
if (amountIn == 0 || tAmountIn < amountIn) {
if (tAmountIn != 0) {
path = tPath;
amountIn = tAmountIn;
rIdx = i;
}
}
}
}
| 6,081,087
|
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.7.0;
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./../Ownable.sol";
contract OCCStakingImp is Ownable, ReentrancyGuard {
using SafeMath for uint;
using SafeERC20 for IERC20;
IERC20 public OCC;
mapping(address => uint) public stakes;
uint256 public totalStake;
uint256[] public checkPoints;
uint256[] public rewardPerSecond;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored; // per 1 OCC, i.e. per 10**18 units
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
uint public unstakingFeeRatio;
uint public newUnstakingFeeRatio;
uint public unstakingFeeRatioTimelock;
uint public constant unstakingFeeRatioTimelockPeriod = 600;
uint public constant unstakingFeeDenominator = 10000;
uint public constant OCCUnits = 1e18;
bool public initialized = false;
uint public startingCheckPoint;
event CreateStake(address indexed caller, uint amount);
event RemoveStake(address indexed caller, uint amount);
event TransferStake(address indexed from, address indexed to, uint amount);
event RewardPaid(address indexed user, uint256 reward);
constructor(address _owner) Ownable(_owner) {}
/* function initialize(address _OCC, uint _unstakingFeeRatio, address _owner, uint emissionStart, uint firstCheckPoint, uint _rewardPerSecond) public {
require(initialized == false, "OCCStakingImp: contract has already been initialized.");
OCC = IERC20(_OCC);
unstakingFeeRatio = _unstakingFeeRatio;
newUnstakingFeeRatio = _unstakingFeeRatio;
if (checkPoints.length == 0) {
checkPoints.push(emissionStart);
checkPoints.push(firstCheckPoint);
rewardPerSecond.push(_rewardPerSecond);
}
owner = _owner;
initialized = true;
} */
function createStake(uint stake) public nonReentrant updateReward(msg.sender) {
OCC.safeTransferFrom(msg.sender, address(this), stake);
stakes[msg.sender] = stakes[msg.sender].add(stake);
totalStake = totalStake.add(stake);
emit CreateStake(msg.sender, stake);
}
function createStakeFor(uint stake, address to) public nonReentrant updateReward(to) {
OCC.safeTransferFrom(msg.sender, address(this), stake);
stakes[to] = stakes[to].add(stake);
totalStake = totalStake.add(stake);
emit CreateStake(to, stake);
}
function getRewardThenStake() public nonReentrant updateReward(msg.sender) {
uint256 reward = rewards[msg.sender];
if (reward > 0) {
require(reward < OCC.balanceOf(address(this)).sub(totalStake), "OCCStaking: not enough tokens to pay out reward.");
rewards[msg.sender] = 0;
stakes[msg.sender] = stakes[msg.sender].add(reward);
totalStake = totalStake.add(reward);
emit CreateStake(msg.sender, reward);
emit RewardPaid(msg.sender, reward);
}
}
function removeStake(uint stake, uint maximumFee) public nonReentrant updateReward(msg.sender) {
uint unstakingFee = stake.mul(unstakingFeeRatio).div(unstakingFeeDenominator);
require(unstakingFee <= maximumFee, "OCCStaking: fee too high.");
uint stakeWithoutFee = stake.sub(unstakingFee);
require(stakes[msg.sender] >= stake, "OCCStaking: INSUFFICIENT_STAKE");
stakes[msg.sender] = stakes[msg.sender].sub(stake);
totalStake = totalStake.sub(stake);
OCC.safeTransfer(msg.sender, stakeWithoutFee);
emit RemoveStake(msg.sender, stake);
}
function transferStake(address _recipient, uint _amount) public {
require(_amount <= stakes[msg.sender], "OCCStakingImp: not enough stake to transfer");
_updateReward(msg.sender);
_updateReward(_recipient);
stakes[msg.sender] = stakes[msg.sender].sub(_amount);
stakes[_recipient] = stakes[_recipient].add(_amount);
}
function getReward() public nonReentrant updateReward(msg.sender) {
uint256 reward = rewards[msg.sender];
if (reward > 0) {
require(reward <= OCC.balanceOf(address(this)).sub(totalStake), "OCCStaking: not enough tokens to pay out reward.");
rewards[msg.sender] = 0;
OCC.safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, reward);
}
}
function showPendingReward(address account) public view returns (uint256) {
uint rewardPerTokenStoredActual;
if (totalStake != 0) {
(uint256 totalEmittedTokensSinceLastUpdate, ) = getTotalEmittedTokens(lastUpdateTime, block.timestamp, startingCheckPoint);
rewardPerTokenStoredActual = rewardPerTokenStored.add(totalEmittedTokensSinceLastUpdate.mul(OCCUnits).div(totalStake));
} else {
rewardPerTokenStoredActual = rewardPerTokenStored;
}
return rewards[account].add((rewardPerTokenStoredActual.sub(userRewardPerTokenPaid[account])).mul(stakes[account]).div(OCCUnits));
}
function _updateReward(address account) internal {
if (totalStake != 0) {
(uint256 totalEmittedTokensSinceLastUpdate, uint256 newStartingCheckPoint) = getTotalEmittedTokens(lastUpdateTime, block.timestamp, startingCheckPoint);
startingCheckPoint = newStartingCheckPoint;
rewardPerTokenStored = rewardPerTokenStored.add(totalEmittedTokensSinceLastUpdate.mul(OCCUnits).div(totalStake));
}
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
uint256 _rewardPerTokenStored = rewardPerTokenStored;
rewards[account] = rewards[account].add((_rewardPerTokenStored.sub(userRewardPerTokenPaid[account])).mul(stakes[account]).div(OCCUnits));
userRewardPerTokenPaid[account] = _rewardPerTokenStored;
}
}
modifier updateReward(address account) {
_updateReward(account);
_;
}
function getStake(address user) public view returns (uint) {
return stakes[user];
}
function setNewUnstakingFeeRatio(uint _newUnstakingFeeRatio) public onlyOwner {
require(_newUnstakingFeeRatio <= unstakingFeeDenominator, "OCCStaking: invalid unstaking fee.");
newUnstakingFeeRatio = _newUnstakingFeeRatio;
unstakingFeeRatioTimelock = block.timestamp.add(unstakingFeeRatioTimelockPeriod);
}
function changeUnstakingFeeRatio() public onlyOwner {
require(block.timestamp >= unstakingFeeRatioTimelock, "OCCStaking: too early to change unstaking fee.");
unstakingFeeRatio = newUnstakingFeeRatio;
}
function updateSchedule(uint checkPoint, uint _rewardPerSecond) public onlyOwner {
uint lastCheckPoint = checkPoints[checkPoints.length.sub(1)];
require(checkPoint > Math.max(lastCheckPoint, block.timestamp), "LM: new checkpoint has to be in the future");
if (block.timestamp > lastCheckPoint) {
checkPoints.push(block.timestamp);
rewardPerSecond.push(0);
}
checkPoints.push(checkPoint);
rewardPerSecond.push(_rewardPerSecond);
}
function getCheckPoints() public view returns (uint256[] memory) {
return checkPoints;
}
function getRewardPerSecond() public view returns (uint256[] memory) {
return rewardPerSecond;
}
function lastTimeRewardApplicable() public view returns (uint256) {
return Math.min(block.timestamp, checkPoints[checkPoints.length.sub(1)]);
}
function getTotalEmittedTokens(uint256 _from, uint256 _to, uint256 _startingCheckPoint) public view returns (uint256, uint256) {
require(_to >= _from, "LM: _to has to be greater than _from.");
uint256 totalEmittedTokens = 0;
uint256 workingTime = Math.max(_from, checkPoints[0]);
if (_to <= workingTime) {
return (0, _startingCheckPoint);
}
uint checkPointsLength = checkPoints.length;
for (uint256 i = _startingCheckPoint + 1; i < checkPointsLength; ++i) {
uint256 emissionTime = checkPoints[i];
uint256 emissionRate = rewardPerSecond[i-1];
if (_to < emissionTime) {
totalEmittedTokens = totalEmittedTokens.add(_to.sub(workingTime).mul(emissionRate));
return (totalEmittedTokens, i-1);
} else if (workingTime < emissionTime) {
totalEmittedTokens = totalEmittedTokens.add(emissionTime.sub(workingTime).mul(emissionRate));
workingTime = emissionTime;
}
}
return (totalEmittedTokens, checkPointsLength.sub(1));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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 () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// 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: 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
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.7.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.
*
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the initial owner.
*/
constructor (address _owner) public {
owner = _owner;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner, "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 onlyOwner {
emit OwnershipTransferred(owner, address(0));
owner = address(0);
}
function setNewOwner(address _newOwner) public onlyOwner {
require(_newOwner != address(0), "Ownable: new owner cannot be the zero address");
newOwner = _newOwner;
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership() public {
require(msg.sender == newOwner, "Ownable: caller must be new owner");
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// 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);
}
}
}
}
|
Transfers ownership of the contract to a new account (`newOwner`). Can only be called by the current owner./
|
function transferOwnership() public {
require(msg.sender == newOwner, "Ownable: caller must be new owner");
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
| 1,095,008
|
pragma solidity 0.4.24;
pragma experimental "v0.5.0";
/*
Copyright 2018 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// File: openzeppelin-solidity/contracts/math/Math.sol
/**
* @title Math
* @dev Assorted math operations
*/
library Math {
function max64(uint64 _a, uint64 _b) internal pure returns (uint64) {
return _a >= _b ? _a : _b;
}
function min64(uint64 _a, uint64 _b) internal pure returns (uint64) {
return _a < _b ? _a : _b;
}
function max256(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a >= _b ? _a : _b;
}
function min256(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a < _b ? _a : _b;
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: contracts/lib/AccessControlledBase.sol
/**
* @title AccessControlledBase
* @author dYdX
*
* Base functionality for access control. Requires an implementation to
* provide a way to grant and optionally revoke access
*/
contract AccessControlledBase {
// ============ State Variables ============
mapping (address => bool) public authorized;
// ============ Events ============
event AccessGranted(
address who
);
event AccessRevoked(
address who
);
// ============ Modifiers ============
modifier requiresAuthorization() {
require(
authorized[msg.sender],
"AccessControlledBase#requiresAuthorization: Sender not authorized"
);
_;
}
}
// File: contracts/lib/StaticAccessControlled.sol
/**
* @title StaticAccessControlled
* @author dYdX
*
* Allows for functions to be access controled
* Permissions cannot be changed after a grace period
*/
contract StaticAccessControlled is AccessControlledBase, Ownable {
using SafeMath for uint256;
// ============ State Variables ============
// Timestamp after which no additional access can be granted
uint256 public GRACE_PERIOD_EXPIRATION;
// ============ Constructor ============
constructor(
uint256 gracePeriod
)
public
Ownable()
{
GRACE_PERIOD_EXPIRATION = block.timestamp.add(gracePeriod);
}
// ============ Owner-Only State-Changing Functions ============
function grantAccess(
address who
)
external
onlyOwner
{
require(
block.timestamp < GRACE_PERIOD_EXPIRATION,
"StaticAccessControlled#grantAccess: Cannot grant access after grace period"
);
emit AccessGranted(who);
authorized[who] = true;
}
}
// File: contracts/lib/GeneralERC20.sol
/**
* @title GeneralERC20
* @author dYdX
*
* Interface for using ERC20 Tokens. We have to use a special interface to call ERC20 functions so
* that we dont automatically revert when calling non-compliant tokens that have no return value for
* transfer(), transferFrom(), or approve().
*/
interface GeneralERC20 {
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;
function transferFrom(
address from,
address to,
uint256 value
)
external;
function approve(
address spender,
uint256 value
)
external;
}
// File: contracts/lib/TokenInteract.sol
/**
* @title TokenInteract
* @author dYdX
*
* This library contains functions for interacting with ERC20 tokens
*/
library TokenInteract {
function balanceOf(
address token,
address owner
)
internal
view
returns (uint256)
{
return GeneralERC20(token).balanceOf(owner);
}
function allowance(
address token,
address owner,
address spender
)
internal
view
returns (uint256)
{
return GeneralERC20(token).allowance(owner, spender);
}
function approve(
address token,
address spender,
uint256 amount
)
internal
{
GeneralERC20(token).approve(spender, amount);
require(
checkSuccess(),
"TokenInteract#approve: Approval failed"
);
}
function transfer(
address token,
address to,
uint256 amount
)
internal
{
address from = address(this);
if (
amount == 0
|| from == to
) {
return;
}
GeneralERC20(token).transfer(to, amount);
require(
checkSuccess(),
"TokenInteract#transfer: Transfer failed"
);
}
function transferFrom(
address token,
address from,
address to,
uint256 amount
)
internal
{
if (
amount == 0
|| from == to
) {
return;
}
GeneralERC20(token).transferFrom(from, to, amount);
require(
checkSuccess(),
"TokenInteract#transferFrom: TransferFrom failed"
);
}
// ============ Private Helper-Functions ============
/**
* Checks the return value of the previous function up to 32 bytes. Returns true if the previous
* function returned 0 bytes or 32 bytes that are not all-zero.
*/
function checkSuccess(
)
private
pure
returns (bool)
{
uint256 returnValue = 0;
/* solium-disable-next-line security/no-inline-assembly */
assembly {
// check number of bytes returned from last function call
switch returndatasize
// no bytes returned: assume success
case 0x0 {
returnValue := 1
}
// 32 bytes returned: check if non-zero
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 { }
}
return returnValue != 0;
}
}
// File: contracts/margin/TokenProxy.sol
/**
* @title TokenProxy
* @author dYdX
*
* Used to transfer tokens between addresses which have set allowance on this contract.
*/
contract TokenProxy is StaticAccessControlled {
using SafeMath for uint256;
// ============ Constructor ============
constructor(
uint256 gracePeriod
)
public
StaticAccessControlled(gracePeriod)
{}
// ============ Authorized-Only State Changing Functions ============
/**
* Transfers tokens from an address (that has set allowance on the proxy) to another address.
*
* @param token The address of the ERC20 token
* @param from The address to transfer token from
* @param to The address to transfer tokens to
* @param value The number of tokens to transfer
*/
function transferTokens(
address token,
address from,
address to,
uint256 value
)
external
requiresAuthorization
{
TokenInteract.transferFrom(
token,
from,
to,
value
);
}
// ============ Public Constant Functions ============
/**
* Getter function to get the amount of token that the proxy is able to move for a particular
* address. The minimum of 1) the balance of that address and 2) the allowance given to proxy.
*
* @param who The owner of the tokens
* @param token The address of the ERC20 token
* @return The number of tokens able to be moved by the proxy from the address specified
*/
function available(
address who,
address token
)
external
view
returns (uint256)
{
return Math.min256(
TokenInteract.allowance(token, who, address(this)),
TokenInteract.balanceOf(token, who)
);
}
}
// File: contracts/margin/Vault.sol
/**
* @title Vault
* @author dYdX
*
* Holds and transfers tokens in vaults denominated by id
*
* Vault only supports ERC20 tokens, and will not accept any tokens that require
* a tokenFallback or equivalent function (See ERC223, ERC777, etc.)
*/
contract Vault is StaticAccessControlled
{
using SafeMath for uint256;
// ============ Events ============
event ExcessTokensWithdrawn(
address indexed token,
address indexed to,
address caller
);
// ============ State Variables ============
// Address of the TokenProxy contract. Used for moving tokens.
address public TOKEN_PROXY;
// Map from vault ID to map from token address to amount of that token attributed to the
// particular vault ID.
mapping (bytes32 => mapping (address => uint256)) public balances;
// Map from token address to total amount of that token attributed to some account.
mapping (address => uint256) public totalBalances;
// ============ Constructor ============
constructor(
address proxy,
uint256 gracePeriod
)
public
StaticAccessControlled(gracePeriod)
{
TOKEN_PROXY = proxy;
}
// ============ Owner-Only State-Changing Functions ============
/**
* Allows the owner to withdraw any excess tokens sent to the vault by unconventional means,
* including (but not limited-to) token airdrops. Any tokens moved to the vault by TOKEN_PROXY
* will be accounted for and will not be withdrawable by this function.
*
* @param token ERC20 token address
* @param to Address to transfer tokens to
* @return Amount of tokens withdrawn
*/
function withdrawExcessToken(
address token,
address to
)
external
onlyOwner
returns (uint256)
{
uint256 actualBalance = TokenInteract.balanceOf(token, address(this));
uint256 accountedBalance = totalBalances[token];
uint256 withdrawableBalance = actualBalance.sub(accountedBalance);
require(
withdrawableBalance != 0,
"Vault#withdrawExcessToken: Withdrawable token amount must be non-zero"
);
TokenInteract.transfer(token, to, withdrawableBalance);
emit ExcessTokensWithdrawn(token, to, msg.sender);
return withdrawableBalance;
}
// ============ Authorized-Only State-Changing Functions ============
/**
* Transfers tokens from an address (that has approved the proxy) to the vault.
*
* @param id The vault which will receive the tokens
* @param token ERC20 token address
* @param from Address from which the tokens will be taken
* @param amount Number of the token to be sent
*/
function transferToVault(
bytes32 id,
address token,
address from,
uint256 amount
)
external
requiresAuthorization
{
// First send tokens to this contract
TokenProxy(TOKEN_PROXY).transferTokens(
token,
from,
address(this),
amount
);
// Then increment balances
balances[id][token] = balances[id][token].add(amount);
totalBalances[token] = totalBalances[token].add(amount);
// This should always be true. If not, something is very wrong
assert(totalBalances[token] >= balances[id][token]);
validateBalance(token);
}
/**
* Transfers a certain amount of funds to an address.
*
* @param id The vault from which to send the tokens
* @param token ERC20 token address
* @param to Address to transfer tokens to
* @param amount Number of the token to be sent
*/
function transferFromVault(
bytes32 id,
address token,
address to,
uint256 amount
)
external
requiresAuthorization
{
// Next line also asserts that (balances[id][token] >= amount);
balances[id][token] = balances[id][token].sub(amount);
// Next line also asserts that (totalBalances[token] >= amount);
totalBalances[token] = totalBalances[token].sub(amount);
// This should always be true. If not, something is very wrong
assert(totalBalances[token] >= balances[id][token]);
// Do the sending
TokenInteract.transfer(token, to, amount); // asserts transfer succeeded
// Final validation
validateBalance(token);
}
// ============ Private Helper-Functions ============
/**
* Verifies that this contract is in control of at least as many tokens as accounted for
*
* @param token Address of ERC20 token
*/
function validateBalance(
address token
)
private
view
{
// The actual balance could be greater than totalBalances[token] because anyone
// can send tokens to the contract's address which cannot be accounted for
assert(TokenInteract.balanceOf(token, address(this)) >= totalBalances[token]);
}
}
// File: contracts/lib/ReentrancyGuard.sol
/**
* @title ReentrancyGuard
* @author dYdX
*
* Optimized version of the well-known ReentrancyGuard contract
*/
contract ReentrancyGuard {
uint256 private _guardCounter = 1;
modifier nonReentrant() {
uint256 localCounter = _guardCounter + 1;
_guardCounter = localCounter;
_;
require(
_guardCounter == localCounter,
"Reentrancy check failure"
);
}
}
// File: openzeppelin-solidity/contracts/AddressUtils.sol
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param _addr address to check
* @return whether the target address is a contract
*/
function isContract(address _addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(_addr) }
return size > 0;
}
}
// File: contracts/lib/Fraction.sol
/**
* @title Fraction
* @author dYdX
*
* This library contains implementations for fraction structs.
*/
library Fraction {
struct Fraction128 {
uint128 num;
uint128 den;
}
}
// File: contracts/lib/FractionMath.sol
/**
* @title FractionMath
* @author dYdX
*
* This library contains safe math functions for manipulating fractions.
*/
library FractionMath {
using SafeMath for uint256;
using SafeMath for uint128;
/**
* Returns a Fraction128 that is equal to a + b
*
* @param a The first Fraction128
* @param b The second Fraction128
* @return The result (sum)
*/
function add(
Fraction.Fraction128 memory a,
Fraction.Fraction128 memory b
)
internal
pure
returns (Fraction.Fraction128 memory)
{
uint256 left = a.num.mul(b.den);
uint256 right = b.num.mul(a.den);
uint256 denominator = a.den.mul(b.den);
// if left + right overflows, prevent overflow
if (left + right < left) {
left = left.div(2);
right = right.div(2);
denominator = denominator.div(2);
}
return bound(left.add(right), denominator);
}
/**
* Returns a Fraction128 that is equal to a - (1/2)^d
*
* @param a The Fraction128
* @param d The power of (1/2)
* @return The result
*/
function sub1Over(
Fraction.Fraction128 memory a,
uint128 d
)
internal
pure
returns (Fraction.Fraction128 memory)
{
if (a.den % d == 0) {
return bound(
a.num.sub(a.den.div(d)),
a.den
);
}
return bound(
a.num.mul(d).sub(a.den),
a.den.mul(d)
);
}
/**
* Returns a Fraction128 that is equal to a / d
*
* @param a The first Fraction128
* @param d The divisor
* @return The result (quotient)
*/
function div(
Fraction.Fraction128 memory a,
uint128 d
)
internal
pure
returns (Fraction.Fraction128 memory)
{
if (a.num % d == 0) {
return bound(
a.num.div(d),
a.den
);
}
return bound(
a.num,
a.den.mul(d)
);
}
/**
* Returns a Fraction128 that is equal to a * b.
*
* @param a The first Fraction128
* @param b The second Fraction128
* @return The result (product)
*/
function mul(
Fraction.Fraction128 memory a,
Fraction.Fraction128 memory b
)
internal
pure
returns (Fraction.Fraction128 memory)
{
return bound(
a.num.mul(b.num),
a.den.mul(b.den)
);
}
/**
* Returns a fraction from two uint256's. Fits them into uint128 if necessary.
*
* @param num The numerator
* @param den The denominator
* @return The Fraction128 that matches num/den most closely
*/
/* solium-disable-next-line security/no-assign-params */
function bound(
uint256 num,
uint256 den
)
internal
pure
returns (Fraction.Fraction128 memory)
{
uint256 max = num > den ? num : den;
uint256 first128Bits = (max >> 128);
if (first128Bits != 0) {
first128Bits += 1;
num /= first128Bits;
den /= first128Bits;
}
assert(den != 0); // coverage-enable-line
assert(den < 2**128);
assert(num < 2**128);
return Fraction.Fraction128({
num: uint128(num),
den: uint128(den)
});
}
/**
* Returns an in-memory copy of a Fraction128
*
* @param a The Fraction128 to copy
* @return A copy of the Fraction128
*/
function copy(
Fraction.Fraction128 memory a
)
internal
pure
returns (Fraction.Fraction128 memory)
{
validate(a);
return Fraction.Fraction128({ num: a.num, den: a.den });
}
// ============ Private Helper-Functions ============
/**
* Asserts that a Fraction128 is valid (i.e. the denominator is non-zero)
*
* @param a The Fraction128 to validate
*/
function validate(
Fraction.Fraction128 memory a
)
private
pure
{
assert(a.den != 0); // coverage-enable-line
}
}
// File: contracts/lib/Exponent.sol
/**
* @title Exponent
* @author dYdX
*
* This library contains an implementation for calculating e^X for arbitrary fraction X
*/
library Exponent {
using SafeMath for uint256;
using FractionMath for Fraction.Fraction128;
// ============ Constants ============
// 2**128 - 1
uint128 constant public MAX_NUMERATOR = 340282366920938463463374607431768211455;
// Number of precomputed integers, X, for E^((1/2)^X)
uint256 constant public MAX_PRECOMPUTE_PRECISION = 32;
// Number of precomputed integers, X, for E^X
uint256 constant public NUM_PRECOMPUTED_INTEGERS = 32;
// ============ Public Implementation Functions ============
/**
* Returns e^X for any fraction X
*
* @param X The exponent
* @param precomputePrecision Accuracy of precomputed terms
* @param maclaurinPrecision Accuracy of Maclaurin terms
* @return e^X
*/
function exp(
Fraction.Fraction128 memory X,
uint256 precomputePrecision,
uint256 maclaurinPrecision
)
internal
pure
returns (Fraction.Fraction128 memory)
{
require(
precomputePrecision <= MAX_PRECOMPUTE_PRECISION,
"Exponent#exp: Precompute precision over maximum"
);
Fraction.Fraction128 memory Xcopy = X.copy();
if (Xcopy.num == 0) { // e^0 = 1
return ONE();
}
// get the integer value of the fraction (example: 9/4 is 2.25 so has integerValue of 2)
uint256 integerX = uint256(Xcopy.num).div(Xcopy.den);
// if X is less than 1, then just calculate X
if (integerX == 0) {
return expHybrid(Xcopy, precomputePrecision, maclaurinPrecision);
}
// get e^integerX
Fraction.Fraction128 memory expOfInt =
getPrecomputedEToThe(integerX % NUM_PRECOMPUTED_INTEGERS);
while (integerX >= NUM_PRECOMPUTED_INTEGERS) {
expOfInt = expOfInt.mul(getPrecomputedEToThe(NUM_PRECOMPUTED_INTEGERS));
integerX -= NUM_PRECOMPUTED_INTEGERS;
}
// multiply e^integerX by e^decimalX
Fraction.Fraction128 memory decimalX = Fraction.Fraction128({
num: Xcopy.num % Xcopy.den,
den: Xcopy.den
});
return expHybrid(decimalX, precomputePrecision, maclaurinPrecision).mul(expOfInt);
}
/**
* Returns e^X for any X < 1. Multiplies precomputed values to get close to the real value, then
* Maclaurin Series approximation to reduce error.
*
* @param X Exponent
* @param precomputePrecision Accuracy of precomputed terms
* @param maclaurinPrecision Accuracy of Maclaurin terms
* @return e^X
*/
function expHybrid(
Fraction.Fraction128 memory X,
uint256 precomputePrecision,
uint256 maclaurinPrecision
)
internal
pure
returns (Fraction.Fraction128 memory)
{
assert(precomputePrecision <= MAX_PRECOMPUTE_PRECISION);
assert(X.num < X.den);
// will also throw if precomputePrecision is larger than the array length in getDenominator
Fraction.Fraction128 memory Xtemp = X.copy();
if (Xtemp.num == 0) { // e^0 = 1
return ONE();
}
Fraction.Fraction128 memory result = ONE();
uint256 d = 1; // 2^i
for (uint256 i = 1; i <= precomputePrecision; i++) {
d *= 2;
// if Fraction > 1/d, subtract 1/d and multiply result by precomputed e^(1/d)
if (d.mul(Xtemp.num) >= Xtemp.den) {
Xtemp = Xtemp.sub1Over(uint128(d));
result = result.mul(getPrecomputedEToTheHalfToThe(i));
}
}
return result.mul(expMaclaurin(Xtemp, maclaurinPrecision));
}
/**
* Returns e^X for any X, using Maclaurin Series approximation
*
* e^X = SUM(X^n / n!) for n >= 0
* e^X = 1 + X/1! + X^2/2! + X^3/3! ...
*
* @param X Exponent
* @param precision Accuracy of Maclaurin terms
* @return e^X
*/
function expMaclaurin(
Fraction.Fraction128 memory X,
uint256 precision
)
internal
pure
returns (Fraction.Fraction128 memory)
{
Fraction.Fraction128 memory Xcopy = X.copy();
if (Xcopy.num == 0) { // e^0 = 1
return ONE();
}
Fraction.Fraction128 memory result = ONE();
Fraction.Fraction128 memory Xtemp = ONE();
for (uint256 i = 1; i <= precision; i++) {
Xtemp = Xtemp.mul(Xcopy.div(uint128(i)));
result = result.add(Xtemp);
}
return result;
}
/**
* Returns a fraction roughly equaling E^((1/2)^x) for integer x
*/
function getPrecomputedEToTheHalfToThe(
uint256 x
)
internal
pure
returns (Fraction.Fraction128 memory)
{
assert(x <= MAX_PRECOMPUTE_PRECISION);
uint128 denominator = [
125182886983370532117250726298150828301,
206391688497133195273760705512282642279,
265012173823417992016237332255925138361,
300298134811882980317033350418940119802,
319665700530617779809390163992561606014,
329812979126047300897653247035862915816,
335006777809430963166468914297166288162,
337634268532609249517744113622081347950,
338955731696479810470146282672867036734,
339618401537809365075354109784799900812,
339950222128463181389559457827561204959,
340116253979683015278260491021941090650,
340199300311581465057079429423749235412,
340240831081268226777032180141478221816,
340261598367316729254995498374473399540,
340271982485676106947851156443492415142,
340277174663693808406010255284800906112,
340279770782412691177936847400746725466,
340281068849199706686796915841848278311,
340281717884450116236033378667952410919,
340282042402539547492367191008339680733,
340282204661700319870089970029119685699,
340282285791309720262481214385569134454,
340282326356121674011576912006427792656,
340282346638529464274601981200276914173,
340282356779733812753265346086924801364,
340282361850336100329388676752133324799,
340282364385637272451648746721404212564,
340282365653287865596328444437856608255,
340282366287113163939555716675618384724,
340282366604025813553891209601455838559,
340282366762482138471739420386372790954,
340282366841710300958333641874363209044
][x];
return Fraction.Fraction128({
num: MAX_NUMERATOR,
den: denominator
});
}
/**
* Returns a fraction roughly equaling E^(x) for integer x
*/
function getPrecomputedEToThe(
uint256 x
)
internal
pure
returns (Fraction.Fraction128 memory)
{
assert(x <= NUM_PRECOMPUTED_INTEGERS);
uint128 denominator = [
340282366920938463463374607431768211455,
125182886983370532117250726298150828301,
46052210507670172419625860892627118820,
16941661466271327126146327822211253888,
6232488952727653950957829210887653621,
2292804553036637136093891217529878878,
843475657686456657683449904934172134,
310297353591408453462393329342695980,
114152017036184782947077973323212575,
41994180235864621538772677139808695,
15448795557622704876497742989562086,
5683294276510101335127414470015662,
2090767122455392675095471286328463,
769150240628514374138961856925097,
282954560699298259527814398449860,
104093165666968799599694528310221,
38293735615330848145349245349513,
14087478058534870382224480725096,
5182493555688763339001418388912,
1906532833141383353974257736699,
701374233231058797338605168652,
258021160973090761055471434334,
94920680509187392077350434438,
34919366901332874995585576427,
12846117181722897538509298435,
4725822410035083116489797150,
1738532907279185132707372378,
639570514388029575350057932,
235284843422800231081973821,
86556456714490055457751527,
31842340925906738090071268,
11714142585413118080082437,
4309392228124372433711936
][x];
return Fraction.Fraction128({
num: MAX_NUMERATOR,
den: denominator
});
}
// ============ Private Helper-Functions ============
function ONE()
private
pure
returns (Fraction.Fraction128 memory)
{
return Fraction.Fraction128({ num: 1, den: 1 });
}
}
// File: contracts/lib/MathHelpers.sol
/**
* @title MathHelpers
* @author dYdX
*
* This library helps with common math functions in Solidity
*/
library MathHelpers {
using SafeMath for uint256;
/**
* Calculates partial value given a numerator and denominator.
*
* @param numerator Numerator
* @param denominator Denominator
* @param target Value to calculate partial of
* @return target * numerator / denominator
*/
function getPartialAmount(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256)
{
return numerator.mul(target).div(denominator);
}
/**
* Calculates partial value given a numerator and denominator, rounded up.
*
* @param numerator Numerator
* @param denominator Denominator
* @param target Value to calculate partial of
* @return Rounded-up result of target * numerator / denominator
*/
function getPartialAmountRoundedUp(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256)
{
return divisionRoundedUp(numerator.mul(target), denominator);
}
/**
* Calculates division given a numerator and denominator, rounded up.
*
* @param numerator Numerator.
* @param denominator Denominator.
* @return Rounded-up result of numerator / denominator
*/
function divisionRoundedUp(
uint256 numerator,
uint256 denominator
)
internal
pure
returns (uint256)
{
assert(denominator != 0); // coverage-enable-line
if (numerator == 0) {
return 0;
}
return numerator.sub(1).div(denominator).add(1);
}
/**
* Calculates and returns the maximum value for a uint256 in solidity
*
* @return The maximum value for uint256
*/
function maxUint256(
)
internal
pure
returns (uint256)
{
return 2 ** 256 - 1;
}
/**
* Calculates and returns the maximum value for a uint256 in solidity
*
* @return The maximum value for uint256
*/
function maxUint32(
)
internal
pure
returns (uint32)
{
return 2 ** 32 - 1;
}
/**
* Returns the number of bits in a uint256. That is, the lowest number, x, such that n >> x == 0
*
* @param n The uint256 to get the number of bits in
* @return The number of bits in n
*/
function getNumBits(
uint256 n
)
internal
pure
returns (uint256)
{
uint256 first = 0;
uint256 last = 256;
while (first < last) {
uint256 check = (first + last) / 2;
if ((n >> check) == 0) {
last = check;
} else {
first = check + 1;
}
}
assert(first <= 256);
return first;
}
}
// File: contracts/margin/impl/InterestImpl.sol
/**
* @title InterestImpl
* @author dYdX
*
* A library that calculates continuously compounded interest for principal, time period, and
* interest rate.
*/
library InterestImpl {
using SafeMath for uint256;
using FractionMath for Fraction.Fraction128;
// ============ Constants ============
uint256 constant DEFAULT_PRECOMPUTE_PRECISION = 11;
uint256 constant DEFAULT_MACLAURIN_PRECISION = 5;
uint256 constant MAXIMUM_EXPONENT = 80;
uint128 constant E_TO_MAXIUMUM_EXPONENT = 55406223843935100525711733958316613;
// ============ Public Implementation Functions ============
/**
* Returns total tokens owed after accruing interest. Continuously compounding and accurate to
* roughly 10^18 decimal places. Continuously compounding interest follows the formula:
* I = P * e^(R*T)
*
* @param principal Principal of the interest calculation
* @param interestRate Annual nominal interest percentage times 10**6.
* (example: 5% = 5e6)
* @param secondsOfInterest Number of seconds that interest has been accruing
* @return Total amount of tokens owed. Greater than tokenAmount.
*/
function getCompoundedInterest(
uint256 principal,
uint256 interestRate,
uint256 secondsOfInterest
)
public
pure
returns (uint256)
{
uint256 numerator = interestRate.mul(secondsOfInterest);
uint128 denominator = (10**8) * (365 * 1 days);
// interestRate and secondsOfInterest should both be uint32
assert(numerator < 2**128);
// fraction representing (Rate * Time)
Fraction.Fraction128 memory rt = Fraction.Fraction128({
num: uint128(numerator),
den: denominator
});
// calculate e^(RT)
Fraction.Fraction128 memory eToRT;
if (numerator.div(denominator) >= MAXIMUM_EXPONENT) {
// degenerate case: cap calculation
eToRT = Fraction.Fraction128({
num: E_TO_MAXIUMUM_EXPONENT,
den: 1
});
} else {
// normal case: calculate e^(RT)
eToRT = Exponent.exp(
rt,
DEFAULT_PRECOMPUTE_PRECISION,
DEFAULT_MACLAURIN_PRECISION
);
}
// e^X for positive X should be greater-than or equal to 1
assert(eToRT.num >= eToRT.den);
return safeMultiplyUint256ByFraction(principal, eToRT);
}
// ============ Private Helper-Functions ============
/**
* Returns n * f, trying to prevent overflow as much as possible. Assumes that the numerator
* and denominator of f are less than 2**128.
*/
function safeMultiplyUint256ByFraction(
uint256 n,
Fraction.Fraction128 memory f
)
private
pure
returns (uint256)
{
uint256 term1 = n.div(2 ** 128); // first 128 bits
uint256 term2 = n % (2 ** 128); // second 128 bits
// uncommon scenario, requires n >= 2**128. calculates term1 = term1 * f
if (term1 > 0) {
term1 = term1.mul(f.num);
uint256 numBits = MathHelpers.getNumBits(term1);
// reduce rounding error by shifting all the way to the left before dividing
term1 = MathHelpers.divisionRoundedUp(
term1 << (uint256(256).sub(numBits)),
f.den);
// continue shifting or reduce shifting to get the right number
if (numBits > 128) {
term1 = term1 << (numBits.sub(128));
} else if (numBits < 128) {
term1 = term1 >> (uint256(128).sub(numBits));
}
}
// calculates term2 = term2 * f
term2 = MathHelpers.getPartialAmountRoundedUp(
f.num,
f.den,
term2
);
return term1.add(term2);
}
}
// File: contracts/margin/impl/MarginState.sol
/**
* @title MarginState
* @author dYdX
*
* Contains state for the Margin contract. Also used by libraries that implement Margin functions.
*/
library MarginState {
struct State {
// Address of the Vault contract
address VAULT;
// Address of the TokenProxy contract
address TOKEN_PROXY;
// Mapping from loanHash -> amount, which stores the amount of a loan which has
// already been filled.
mapping (bytes32 => uint256) loanFills;
// Mapping from loanHash -> amount, which stores the amount of a loan which has
// already been canceled.
mapping (bytes32 => uint256) loanCancels;
// Mapping from positionId -> Position, which stores all the open margin positions.
mapping (bytes32 => MarginCommon.Position) positions;
// Mapping from positionId -> bool, which stores whether the position has previously been
// open, but is now closed.
mapping (bytes32 => bool) closedPositions;
// Mapping from positionId -> uint256, which stores the total amount of owedToken that has
// ever been repaid to the lender for each position. Does not reset.
mapping (bytes32 => uint256) totalOwedTokenRepaidToLender;
}
}
// File: contracts/margin/interfaces/lender/LoanOwner.sol
/**
* @title LoanOwner
* @author dYdX
*
* Interface that smart contracts must implement in order to own loans on behalf of other accounts.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface LoanOwner {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to receive ownership of a loan sell via the
* transferLoan function or the atomic-assign to the "owner" field in a loan offering.
*
* @param from Address of the previous owner
* @param positionId Unique ID of the position
* @return This address to keep ownership, a different address to pass-on ownership
*/
function receiveLoanOwnership(
address from,
bytes32 positionId
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/interfaces/owner/PositionOwner.sol
/**
* @title PositionOwner
* @author dYdX
*
* Interface that smart contracts must implement in order to own position on behalf of other
* accounts
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface PositionOwner {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to receive ownership of a position via the
* transferPosition function or the atomic-assign to the "owner" field when opening a position.
*
* @param from Address of the previous owner
* @param positionId Unique ID of the position
* @return This address to keep ownership, a different address to pass-on ownership
*/
function receivePositionOwnership(
address from,
bytes32 positionId
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/impl/TransferInternal.sol
/**
* @title TransferInternal
* @author dYdX
*
* This library contains the implementation for transferring ownership of loans and positions.
*/
library TransferInternal {
// ============ Events ============
/**
* Ownership of a loan was transferred to a new address
*/
event LoanTransferred(
bytes32 indexed positionId,
address indexed from,
address indexed to
);
/**
* Ownership of a postion was transferred to a new address
*/
event PositionTransferred(
bytes32 indexed positionId,
address indexed from,
address indexed to
);
// ============ Internal Implementation Functions ============
/**
* Returns either the address of the new loan owner, or the address to which they wish to
* pass ownership of the loan. This function does not actually set the state of the position
*
* @param positionId The Unique ID of the position
* @param oldOwner The previous owner of the loan
* @param newOwner The intended owner of the loan
* @return The address that the intended owner wishes to assign the loan to (may be
* the same as the intended owner).
*/
function grantLoanOwnership(
bytes32 positionId,
address oldOwner,
address newOwner
)
internal
returns (address)
{
// log event except upon position creation
if (oldOwner != address(0)) {
emit LoanTransferred(positionId, oldOwner, newOwner);
}
if (AddressUtils.isContract(newOwner)) {
address nextOwner =
LoanOwner(newOwner).receiveLoanOwnership(oldOwner, positionId);
if (nextOwner != newOwner) {
return grantLoanOwnership(positionId, newOwner, nextOwner);
}
}
require(
newOwner != address(0),
"TransferInternal#grantLoanOwnership: New owner did not consent to owning loan"
);
return newOwner;
}
/**
* Returns either the address of the new position owner, or the address to which they wish to
* pass ownership of the position. This function does not actually set the state of the position
*
* @param positionId The Unique ID of the position
* @param oldOwner The previous owner of the position
* @param newOwner The intended owner of the position
* @return The address that the intended owner wishes to assign the position to (may
* be the same as the intended owner).
*/
function grantPositionOwnership(
bytes32 positionId,
address oldOwner,
address newOwner
)
internal
returns (address)
{
// log event except upon position creation
if (oldOwner != address(0)) {
emit PositionTransferred(positionId, oldOwner, newOwner);
}
if (AddressUtils.isContract(newOwner)) {
address nextOwner =
PositionOwner(newOwner).receivePositionOwnership(oldOwner, positionId);
if (nextOwner != newOwner) {
return grantPositionOwnership(positionId, newOwner, nextOwner);
}
}
require(
newOwner != address(0),
"TransferInternal#grantPositionOwnership: New owner did not consent to owning position"
);
return newOwner;
}
}
// File: contracts/lib/TimestampHelper.sol
/**
* @title TimestampHelper
* @author dYdX
*
* Helper to get block timestamps in other formats
*/
library TimestampHelper {
function getBlockTimestamp32()
internal
view
returns (uint32)
{
// Should not still be in-use in the year 2106
assert(uint256(uint32(block.timestamp)) == block.timestamp);
assert(block.timestamp > 0);
return uint32(block.timestamp);
}
}
// File: contracts/margin/impl/MarginCommon.sol
/**
* @title MarginCommon
* @author dYdX
*
* This library contains common functions for implementations of public facing Margin functions
*/
library MarginCommon {
using SafeMath for uint256;
// ============ Structs ============
struct Position {
address owedToken; // Immutable
address heldToken; // Immutable
address lender;
address owner;
uint256 principal;
uint256 requiredDeposit;
uint32 callTimeLimit; // Immutable
uint32 startTimestamp; // Immutable, cannot be 0
uint32 callTimestamp;
uint32 maxDuration; // Immutable
uint32 interestRate; // Immutable
uint32 interestPeriod; // Immutable
}
struct LoanOffering {
address owedToken;
address heldToken;
address payer;
address owner;
address taker;
address positionOwner;
address feeRecipient;
address lenderFeeToken;
address takerFeeToken;
LoanRates rates;
uint256 expirationTimestamp;
uint32 callTimeLimit;
uint32 maxDuration;
uint256 salt;
bytes32 loanHash;
bytes signature;
}
struct LoanRates {
uint256 maxAmount;
uint256 minAmount;
uint256 minHeldToken;
uint256 lenderFee;
uint256 takerFee;
uint32 interestRate;
uint32 interestPeriod;
}
// ============ Internal Implementation Functions ============
function storeNewPosition(
MarginState.State storage state,
bytes32 positionId,
Position memory position,
address loanPayer
)
internal
{
assert(!positionHasExisted(state, positionId));
assert(position.owedToken != address(0));
assert(position.heldToken != address(0));
assert(position.owedToken != position.heldToken);
assert(position.owner != address(0));
assert(position.lender != address(0));
assert(position.maxDuration != 0);
assert(position.interestPeriod <= position.maxDuration);
assert(position.callTimestamp == 0);
assert(position.requiredDeposit == 0);
state.positions[positionId].owedToken = position.owedToken;
state.positions[positionId].heldToken = position.heldToken;
state.positions[positionId].principal = position.principal;
state.positions[positionId].callTimeLimit = position.callTimeLimit;
state.positions[positionId].startTimestamp = TimestampHelper.getBlockTimestamp32();
state.positions[positionId].maxDuration = position.maxDuration;
state.positions[positionId].interestRate = position.interestRate;
state.positions[positionId].interestPeriod = position.interestPeriod;
state.positions[positionId].owner = TransferInternal.grantPositionOwnership(
positionId,
(position.owner != msg.sender) ? msg.sender : address(0),
position.owner
);
state.positions[positionId].lender = TransferInternal.grantLoanOwnership(
positionId,
(position.lender != loanPayer) ? loanPayer : address(0),
position.lender
);
}
function getPositionIdFromNonce(
uint256 nonce
)
internal
view
returns (bytes32)
{
return keccak256(abi.encodePacked(msg.sender, nonce));
}
function getUnavailableLoanOfferingAmountImpl(
MarginState.State storage state,
bytes32 loanHash
)
internal
view
returns (uint256)
{
return state.loanFills[loanHash].add(state.loanCancels[loanHash]);
}
function cleanupPosition(
MarginState.State storage state,
bytes32 positionId
)
internal
{
delete state.positions[positionId];
state.closedPositions[positionId] = true;
}
function calculateOwedAmount(
Position storage position,
uint256 closeAmount,
uint256 endTimestamp
)
internal
view
returns (uint256)
{
uint256 timeElapsed = calculateEffectiveTimeElapsed(position, endTimestamp);
return InterestImpl.getCompoundedInterest(
closeAmount,
position.interestRate,
timeElapsed
);
}
/**
* Calculates time elapsed rounded up to the nearest interestPeriod
*/
function calculateEffectiveTimeElapsed(
Position storage position,
uint256 timestamp
)
internal
view
returns (uint256)
{
uint256 elapsed = timestamp.sub(position.startTimestamp);
// round up to interestPeriod
uint256 period = position.interestPeriod;
if (period > 1) {
elapsed = MathHelpers.divisionRoundedUp(elapsed, period).mul(period);
}
// bound by maxDuration
return Math.min256(
elapsed,
position.maxDuration
);
}
function calculateLenderAmountForIncreasePosition(
Position storage position,
uint256 principalToAdd,
uint256 endTimestamp
)
internal
view
returns (uint256)
{
uint256 timeElapsed = calculateEffectiveTimeElapsedForNewLender(position, endTimestamp);
return InterestImpl.getCompoundedInterest(
principalToAdd,
position.interestRate,
timeElapsed
);
}
function getLoanOfferingHash(
LoanOffering loanOffering
)
internal
view
returns (bytes32)
{
return keccak256(
abi.encodePacked(
address(this),
loanOffering.owedToken,
loanOffering.heldToken,
loanOffering.payer,
loanOffering.owner,
loanOffering.taker,
loanOffering.positionOwner,
loanOffering.feeRecipient,
loanOffering.lenderFeeToken,
loanOffering.takerFeeToken,
getValuesHash(loanOffering)
)
);
}
function getPositionBalanceImpl(
MarginState.State storage state,
bytes32 positionId
)
internal
view
returns(uint256)
{
return Vault(state.VAULT).balances(positionId, state.positions[positionId].heldToken);
}
function containsPositionImpl(
MarginState.State storage state,
bytes32 positionId
)
internal
view
returns (bool)
{
return state.positions[positionId].startTimestamp != 0;
}
function positionHasExisted(
MarginState.State storage state,
bytes32 positionId
)
internal
view
returns (bool)
{
return containsPositionImpl(state, positionId) || state.closedPositions[positionId];
}
function getPositionFromStorage(
MarginState.State storage state,
bytes32 positionId
)
internal
view
returns (Position storage)
{
Position storage position = state.positions[positionId];
require(
position.startTimestamp != 0,
"MarginCommon#getPositionFromStorage: The position does not exist"
);
return position;
}
// ============ Private Helper-Functions ============
/**
* Calculates time elapsed rounded down to the nearest interestPeriod
*/
function calculateEffectiveTimeElapsedForNewLender(
Position storage position,
uint256 timestamp
)
private
view
returns (uint256)
{
uint256 elapsed = timestamp.sub(position.startTimestamp);
// round down to interestPeriod
uint256 period = position.interestPeriod;
if (period > 1) {
elapsed = elapsed.div(period).mul(period);
}
// bound by maxDuration
return Math.min256(
elapsed,
position.maxDuration
);
}
function getValuesHash(
LoanOffering loanOffering
)
private
pure
returns (bytes32)
{
return keccak256(
abi.encodePacked(
loanOffering.rates.maxAmount,
loanOffering.rates.minAmount,
loanOffering.rates.minHeldToken,
loanOffering.rates.lenderFee,
loanOffering.rates.takerFee,
loanOffering.expirationTimestamp,
loanOffering.salt,
loanOffering.callTimeLimit,
loanOffering.maxDuration,
loanOffering.rates.interestRate,
loanOffering.rates.interestPeriod
)
);
}
}
// File: contracts/margin/interfaces/PayoutRecipient.sol
/**
* @title PayoutRecipient
* @author dYdX
*
* Interface that smart contracts must implement in order to be the payoutRecipient in a
* closePosition transaction.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface PayoutRecipient {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to receive payout from being the payoutRecipient
* in a closePosition transaction. May redistribute any payout as necessary. Throws on error.
*
* @param positionId Unique ID of the position
* @param closeAmount Amount of the position that was closed
* @param closer Address of the account or contract that closed the position
* @param positionOwner Address of the owner of the position
* @param heldToken Address of the ERC20 heldToken
* @param payout Number of tokens received from the payout
* @param totalHeldToken Total amount of heldToken removed from vault during close
* @param payoutInHeldToken True if payout is in heldToken, false if in owedToken
* @return True if approved by the receiver
*/
function receiveClosePositionPayout(
bytes32 positionId,
uint256 closeAmount,
address closer,
address positionOwner,
address heldToken,
uint256 payout,
uint256 totalHeldToken,
bool payoutInHeldToken
)
external
/* onlyMargin */
returns (bool);
}
// File: contracts/margin/interfaces/lender/CloseLoanDelegator.sol
/**
* @title CloseLoanDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to let other addresses close a loan
* owned by the smart contract.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface CloseLoanDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to let other addresses call
* closeWithoutCounterparty().
*
* NOTE: If not returning zero (or not reverting), this contract must assume that Margin will
* either revert the entire transaction or that (at most) the specified amount of the loan was
* successfully closed.
*
* @param closer Address of the caller of closeWithoutCounterparty()
* @param payoutRecipient Address of the recipient of tokens paid out from closing
* @param positionId Unique ID of the position
* @param requestedAmount Requested principal amount of the loan to close
* @return 1) This address to accept, a different address to ask that contract
* 2) The maximum amount that this contract is allowing
*/
function closeLoanOnBehalfOf(
address closer,
address payoutRecipient,
bytes32 positionId,
uint256 requestedAmount
)
external
/* onlyMargin */
returns (address, uint256);
}
// File: contracts/margin/interfaces/owner/ClosePositionDelegator.sol
/**
* @title ClosePositionDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to let other addresses close a position
* owned by the smart contract, allowing more complex logic to control positions.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface ClosePositionDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to let other addresses call closePosition().
*
* NOTE: If not returning zero (or not reverting), this contract must assume that Margin will
* either revert the entire transaction or that (at-most) the specified amount of the position
* was successfully closed.
*
* @param closer Address of the caller of the closePosition() function
* @param payoutRecipient Address of the recipient of tokens paid out from closing
* @param positionId Unique ID of the position
* @param requestedAmount Requested principal amount of the position to close
* @return 1) This address to accept, a different address to ask that contract
* 2) The maximum amount that this contract is allowing
*/
function closeOnBehalfOf(
address closer,
address payoutRecipient,
bytes32 positionId,
uint256 requestedAmount
)
external
/* onlyMargin */
returns (address, uint256);
}
// File: contracts/margin/impl/ClosePositionShared.sol
/**
* @title ClosePositionShared
* @author dYdX
*
* This library contains shared functionality between ClosePositionImpl and
* CloseWithoutCounterpartyImpl
*/
library ClosePositionShared {
using SafeMath for uint256;
// ============ Structs ============
struct CloseTx {
bytes32 positionId;
uint256 originalPrincipal;
uint256 closeAmount;
uint256 owedTokenOwed;
uint256 startingHeldTokenBalance;
uint256 availableHeldToken;
address payoutRecipient;
address owedToken;
address heldToken;
address positionOwner;
address positionLender;
address exchangeWrapper;
bool payoutInHeldToken;
}
// ============ Internal Implementation Functions ============
function closePositionStateUpdate(
MarginState.State storage state,
CloseTx memory transaction
)
internal
{
// Delete the position, or just decrease the principal
if (transaction.closeAmount == transaction.originalPrincipal) {
MarginCommon.cleanupPosition(state, transaction.positionId);
} else {
assert(
transaction.originalPrincipal == state.positions[transaction.positionId].principal
);
state.positions[transaction.positionId].principal =
transaction.originalPrincipal.sub(transaction.closeAmount);
}
}
function sendTokensToPayoutRecipient(
MarginState.State storage state,
ClosePositionShared.CloseTx memory transaction,
uint256 buybackCostInHeldToken,
uint256 receivedOwedToken
)
internal
returns (uint256)
{
uint256 payout;
if (transaction.payoutInHeldToken) {
// Send remaining heldToken to payoutRecipient
payout = transaction.availableHeldToken.sub(buybackCostInHeldToken);
Vault(state.VAULT).transferFromVault(
transaction.positionId,
transaction.heldToken,
transaction.payoutRecipient,
payout
);
} else {
assert(transaction.exchangeWrapper != address(0));
payout = receivedOwedToken.sub(transaction.owedTokenOwed);
TokenProxy(state.TOKEN_PROXY).transferTokens(
transaction.owedToken,
transaction.exchangeWrapper,
transaction.payoutRecipient,
payout
);
}
if (AddressUtils.isContract(transaction.payoutRecipient)) {
require(
PayoutRecipient(transaction.payoutRecipient).receiveClosePositionPayout(
transaction.positionId,
transaction.closeAmount,
msg.sender,
transaction.positionOwner,
transaction.heldToken,
payout,
transaction.availableHeldToken,
transaction.payoutInHeldToken
),
"ClosePositionShared#sendTokensToPayoutRecipient: Payout recipient does not consent"
);
}
// The ending heldToken balance of the vault should be the starting heldToken balance
// minus the available heldToken amount
assert(
MarginCommon.getPositionBalanceImpl(state, transaction.positionId)
== transaction.startingHeldTokenBalance.sub(transaction.availableHeldToken)
);
return payout;
}
function createCloseTx(
MarginState.State storage state,
bytes32 positionId,
uint256 requestedAmount,
address payoutRecipient,
address exchangeWrapper,
bool payoutInHeldToken,
bool isWithoutCounterparty
)
internal
returns (CloseTx memory)
{
// Validate
require(
payoutRecipient != address(0),
"ClosePositionShared#createCloseTx: Payout recipient cannot be 0"
);
require(
requestedAmount > 0,
"ClosePositionShared#createCloseTx: Requested close amount cannot be 0"
);
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
uint256 closeAmount = getApprovedAmount(
position,
positionId,
requestedAmount,
payoutRecipient,
isWithoutCounterparty
);
return parseCloseTx(
state,
position,
positionId,
closeAmount,
payoutRecipient,
exchangeWrapper,
payoutInHeldToken,
isWithoutCounterparty
);
}
// ============ Private Helper-Functions ============
function getApprovedAmount(
MarginCommon.Position storage position,
bytes32 positionId,
uint256 requestedAmount,
address payoutRecipient,
bool requireLenderApproval
)
private
returns (uint256)
{
// Ensure enough principal
uint256 allowedAmount = Math.min256(requestedAmount, position.principal);
// Ensure owner consent
allowedAmount = closePositionOnBehalfOfRecurse(
position.owner,
msg.sender,
payoutRecipient,
positionId,
allowedAmount
);
// Ensure lender consent
if (requireLenderApproval) {
allowedAmount = closeLoanOnBehalfOfRecurse(
position.lender,
msg.sender,
payoutRecipient,
positionId,
allowedAmount
);
}
assert(allowedAmount > 0);
assert(allowedAmount <= position.principal);
assert(allowedAmount <= requestedAmount);
return allowedAmount;
}
function closePositionOnBehalfOfRecurse(
address contractAddr,
address closer,
address payoutRecipient,
bytes32 positionId,
uint256 closeAmount
)
private
returns (uint256)
{
// no need to ask for permission
if (closer == contractAddr) {
return closeAmount;
}
(
address newContractAddr,
uint256 newCloseAmount
) = ClosePositionDelegator(contractAddr).closeOnBehalfOf(
closer,
payoutRecipient,
positionId,
closeAmount
);
require(
newCloseAmount <= closeAmount,
"ClosePositionShared#closePositionRecurse: newCloseAmount is greater than closeAmount"
);
require(
newCloseAmount > 0,
"ClosePositionShared#closePositionRecurse: newCloseAmount is zero"
);
if (newContractAddr != contractAddr) {
closePositionOnBehalfOfRecurse(
newContractAddr,
closer,
payoutRecipient,
positionId,
newCloseAmount
);
}
return newCloseAmount;
}
function closeLoanOnBehalfOfRecurse(
address contractAddr,
address closer,
address payoutRecipient,
bytes32 positionId,
uint256 closeAmount
)
private
returns (uint256)
{
// no need to ask for permission
if (closer == contractAddr) {
return closeAmount;
}
(
address newContractAddr,
uint256 newCloseAmount
) = CloseLoanDelegator(contractAddr).closeLoanOnBehalfOf(
closer,
payoutRecipient,
positionId,
closeAmount
);
require(
newCloseAmount <= closeAmount,
"ClosePositionShared#closeLoanRecurse: newCloseAmount is greater than closeAmount"
);
require(
newCloseAmount > 0,
"ClosePositionShared#closeLoanRecurse: newCloseAmount is zero"
);
if (newContractAddr != contractAddr) {
closeLoanOnBehalfOfRecurse(
newContractAddr,
closer,
payoutRecipient,
positionId,
newCloseAmount
);
}
return newCloseAmount;
}
// ============ Parsing Functions ============
function parseCloseTx(
MarginState.State storage state,
MarginCommon.Position storage position,
bytes32 positionId,
uint256 closeAmount,
address payoutRecipient,
address exchangeWrapper,
bool payoutInHeldToken,
bool isWithoutCounterparty
)
private
view
returns (CloseTx memory)
{
uint256 startingHeldTokenBalance = MarginCommon.getPositionBalanceImpl(state, positionId);
uint256 availableHeldToken = MathHelpers.getPartialAmount(
closeAmount,
position.principal,
startingHeldTokenBalance
);
uint256 owedTokenOwed = 0;
if (!isWithoutCounterparty) {
owedTokenOwed = MarginCommon.calculateOwedAmount(
position,
closeAmount,
block.timestamp
);
}
return CloseTx({
positionId: positionId,
originalPrincipal: position.principal,
closeAmount: closeAmount,
owedTokenOwed: owedTokenOwed,
startingHeldTokenBalance: startingHeldTokenBalance,
availableHeldToken: availableHeldToken,
payoutRecipient: payoutRecipient,
owedToken: position.owedToken,
heldToken: position.heldToken,
positionOwner: position.owner,
positionLender: position.lender,
exchangeWrapper: exchangeWrapper,
payoutInHeldToken: payoutInHeldToken
});
}
}
// File: contracts/margin/interfaces/ExchangeWrapper.sol
/**
* @title ExchangeWrapper
* @author dYdX
*
* Contract interface that Exchange Wrapper smart contracts must implement in order to interface
* with other smart contracts through a common interface.
*/
interface ExchangeWrapper {
// ============ Public Functions ============
/**
* Exchange some amount of takerToken for makerToken.
*
* @param tradeOriginator Address of the initiator of the trade (however, this value
* cannot always be trusted as it is set at the discretion of the
* msg.sender)
* @param receiver Address to set allowance on once the trade has completed
* @param makerToken Address of makerToken, the token to receive
* @param takerToken Address of takerToken, the token to pay
* @param requestedFillAmount Amount of takerToken being paid
* @param orderData Arbitrary bytes data for any information to pass to the exchange
* @return The amount of makerToken received
*/
function exchange(
address tradeOriginator,
address receiver,
address makerToken,
address takerToken,
uint256 requestedFillAmount,
bytes orderData
)
external
returns (uint256);
/**
* Get amount of takerToken required to buy a certain amount of makerToken for a given trade.
* Should match the takerToken amount used in exchangeForAmount. If the order cannot provide
* exactly desiredMakerToken, then it must return the price to buy the minimum amount greater
* than desiredMakerToken
*
* @param makerToken Address of makerToken, the token to receive
* @param takerToken Address of takerToken, the token to pay
* @param desiredMakerToken Amount of makerToken requested
* @param orderData Arbitrary bytes data for any information to pass to the exchange
* @return Amount of takerToken the needed to complete the transaction
*/
function getExchangeCost(
address makerToken,
address takerToken,
uint256 desiredMakerToken,
bytes orderData
)
external
view
returns (uint256);
}
// File: contracts/margin/impl/ClosePositionImpl.sol
/**
* @title ClosePositionImpl
* @author dYdX
*
* This library contains the implementation for the closePosition function of Margin
*/
library ClosePositionImpl {
using SafeMath for uint256;
// ============ Events ============
/**
* A position was closed or partially closed
*/
event PositionClosed(
bytes32 indexed positionId,
address indexed closer,
address indexed payoutRecipient,
uint256 closeAmount,
uint256 remainingAmount,
uint256 owedTokenPaidToLender,
uint256 payoutAmount,
uint256 buybackCostInHeldToken,
bool payoutInHeldToken
);
// ============ Public Implementation Functions ============
function closePositionImpl(
MarginState.State storage state,
bytes32 positionId,
uint256 requestedCloseAmount,
address payoutRecipient,
address exchangeWrapper,
bool payoutInHeldToken,
bytes memory orderData
)
public
returns (uint256, uint256, uint256)
{
ClosePositionShared.CloseTx memory transaction = ClosePositionShared.createCloseTx(
state,
positionId,
requestedCloseAmount,
payoutRecipient,
exchangeWrapper,
payoutInHeldToken,
false
);
(
uint256 buybackCostInHeldToken,
uint256 receivedOwedToken
) = returnOwedTokensToLender(
state,
transaction,
orderData
);
uint256 payout = ClosePositionShared.sendTokensToPayoutRecipient(
state,
transaction,
buybackCostInHeldToken,
receivedOwedToken
);
ClosePositionShared.closePositionStateUpdate(state, transaction);
logEventOnClose(
transaction,
buybackCostInHeldToken,
payout
);
return (
transaction.closeAmount,
payout,
transaction.owedTokenOwed
);
}
// ============ Private Helper-Functions ============
function returnOwedTokensToLender(
MarginState.State storage state,
ClosePositionShared.CloseTx memory transaction,
bytes memory orderData
)
private
returns (uint256, uint256)
{
uint256 buybackCostInHeldToken = 0;
uint256 receivedOwedToken = 0;
uint256 lenderOwedToken = transaction.owedTokenOwed;
// Setting exchangeWrapper to 0x000... indicates owedToken should be taken directly
// from msg.sender
if (transaction.exchangeWrapper == address(0)) {
require(
transaction.payoutInHeldToken,
"ClosePositionImpl#returnOwedTokensToLender: Cannot payout in owedToken"
);
// No DEX Order; send owedTokens directly from the closer to the lender
TokenProxy(state.TOKEN_PROXY).transferTokens(
transaction.owedToken,
msg.sender,
transaction.positionLender,
lenderOwedToken
);
} else {
// Buy back owedTokens using DEX Order and send to lender
(buybackCostInHeldToken, receivedOwedToken) = buyBackOwedToken(
state,
transaction,
orderData
);
// If no owedToken needed for payout: give lender all owedToken, even if more than owed
if (transaction.payoutInHeldToken) {
assert(receivedOwedToken >= lenderOwedToken);
lenderOwedToken = receivedOwedToken;
}
// Transfer owedToken from the exchange wrapper to the lender
TokenProxy(state.TOKEN_PROXY).transferTokens(
transaction.owedToken,
transaction.exchangeWrapper,
transaction.positionLender,
lenderOwedToken
);
}
state.totalOwedTokenRepaidToLender[transaction.positionId] =
state.totalOwedTokenRepaidToLender[transaction.positionId].add(lenderOwedToken);
return (buybackCostInHeldToken, receivedOwedToken);
}
function buyBackOwedToken(
MarginState.State storage state,
ClosePositionShared.CloseTx transaction,
bytes memory orderData
)
private
returns (uint256, uint256)
{
// Ask the exchange wrapper the cost in heldToken to buy back the close
// amount of owedToken
uint256 buybackCostInHeldToken;
if (transaction.payoutInHeldToken) {
buybackCostInHeldToken = ExchangeWrapper(transaction.exchangeWrapper)
.getExchangeCost(
transaction.owedToken,
transaction.heldToken,
transaction.owedTokenOwed,
orderData
);
// Require enough available heldToken to pay for the buyback
require(
buybackCostInHeldToken <= transaction.availableHeldToken,
"ClosePositionImpl#buyBackOwedToken: Not enough available heldToken"
);
} else {
buybackCostInHeldToken = transaction.availableHeldToken;
}
// Send the requisite heldToken to do the buyback from vault to exchange wrapper
Vault(state.VAULT).transferFromVault(
transaction.positionId,
transaction.heldToken,
transaction.exchangeWrapper,
buybackCostInHeldToken
);
// Trade the heldToken for the owedToken
uint256 receivedOwedToken = ExchangeWrapper(transaction.exchangeWrapper).exchange(
msg.sender,
state.TOKEN_PROXY,
transaction.owedToken,
transaction.heldToken,
buybackCostInHeldToken,
orderData
);
require(
receivedOwedToken >= transaction.owedTokenOwed,
"ClosePositionImpl#buyBackOwedToken: Did not receive enough owedToken"
);
return (buybackCostInHeldToken, receivedOwedToken);
}
function logEventOnClose(
ClosePositionShared.CloseTx transaction,
uint256 buybackCostInHeldToken,
uint256 payout
)
private
{
emit PositionClosed(
transaction.positionId,
msg.sender,
transaction.payoutRecipient,
transaction.closeAmount,
transaction.originalPrincipal.sub(transaction.closeAmount),
transaction.owedTokenOwed,
payout,
buybackCostInHeldToken,
transaction.payoutInHeldToken
);
}
}
// File: contracts/margin/impl/CloseWithoutCounterpartyImpl.sol
/**
* @title CloseWithoutCounterpartyImpl
* @author dYdX
*
* This library contains the implementation for the closeWithoutCounterpartyImpl function of
* Margin
*/
library CloseWithoutCounterpartyImpl {
using SafeMath for uint256;
// ============ Events ============
/**
* A position was closed or partially closed
*/
event PositionClosed(
bytes32 indexed positionId,
address indexed closer,
address indexed payoutRecipient,
uint256 closeAmount,
uint256 remainingAmount,
uint256 owedTokenPaidToLender,
uint256 payoutAmount,
uint256 buybackCostInHeldToken,
bool payoutInHeldToken
);
// ============ Public Implementation Functions ============
function closeWithoutCounterpartyImpl(
MarginState.State storage state,
bytes32 positionId,
uint256 requestedCloseAmount,
address payoutRecipient
)
public
returns (uint256, uint256)
{
ClosePositionShared.CloseTx memory transaction = ClosePositionShared.createCloseTx(
state,
positionId,
requestedCloseAmount,
payoutRecipient,
address(0),
true,
true
);
uint256 heldTokenPayout = ClosePositionShared.sendTokensToPayoutRecipient(
state,
transaction,
0, // No buyback cost
0 // Did not receive any owedToken
);
ClosePositionShared.closePositionStateUpdate(state, transaction);
logEventOnCloseWithoutCounterparty(transaction);
return (
transaction.closeAmount,
heldTokenPayout
);
}
// ============ Private Helper-Functions ============
function logEventOnCloseWithoutCounterparty(
ClosePositionShared.CloseTx transaction
)
private
{
emit PositionClosed(
transaction.positionId,
msg.sender,
transaction.payoutRecipient,
transaction.closeAmount,
transaction.originalPrincipal.sub(transaction.closeAmount),
0,
transaction.availableHeldToken,
0,
true
);
}
}
// File: contracts/margin/interfaces/owner/DepositCollateralDelegator.sol
/**
* @title DepositCollateralDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to let other addresses deposit heldTokens
* into a position owned by the smart contract.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface DepositCollateralDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to let other addresses call depositCollateral().
*
* @param depositor Address of the caller of the depositCollateral() function
* @param positionId Unique ID of the position
* @param amount Requested deposit amount
* @return This address to accept, a different address to ask that contract
*/
function depositCollateralOnBehalfOf(
address depositor,
bytes32 positionId,
uint256 amount
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/impl/DepositCollateralImpl.sol
/**
* @title DepositCollateralImpl
* @author dYdX
*
* This library contains the implementation for the deposit function of Margin
*/
library DepositCollateralImpl {
using SafeMath for uint256;
// ============ Events ============
/**
* Additional collateral for a position was posted by the owner
*/
event AdditionalCollateralDeposited(
bytes32 indexed positionId,
uint256 amount,
address depositor
);
/**
* A margin call was canceled
*/
event MarginCallCanceled(
bytes32 indexed positionId,
address indexed lender,
address indexed owner,
uint256 depositAmount
);
// ============ Public Implementation Functions ============
function depositCollateralImpl(
MarginState.State storage state,
bytes32 positionId,
uint256 depositAmount
)
public
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
require(
depositAmount > 0,
"DepositCollateralImpl#depositCollateralImpl: Deposit amount cannot be 0"
);
// Ensure owner consent
depositCollateralOnBehalfOfRecurse(
position.owner,
msg.sender,
positionId,
depositAmount
);
Vault(state.VAULT).transferToVault(
positionId,
position.heldToken,
msg.sender,
depositAmount
);
// cancel margin call if applicable
bool marginCallCanceled = false;
uint256 requiredDeposit = position.requiredDeposit;
if (position.callTimestamp > 0 && requiredDeposit > 0) {
if (depositAmount >= requiredDeposit) {
position.requiredDeposit = 0;
position.callTimestamp = 0;
marginCallCanceled = true;
} else {
position.requiredDeposit = position.requiredDeposit.sub(depositAmount);
}
}
emit AdditionalCollateralDeposited(
positionId,
depositAmount,
msg.sender
);
if (marginCallCanceled) {
emit MarginCallCanceled(
positionId,
position.lender,
msg.sender,
depositAmount
);
}
}
// ============ Private Helper-Functions ============
function depositCollateralOnBehalfOfRecurse(
address contractAddr,
address depositor,
bytes32 positionId,
uint256 amount
)
private
{
// no need to ask for permission
if (depositor == contractAddr) {
return;
}
address newContractAddr =
DepositCollateralDelegator(contractAddr).depositCollateralOnBehalfOf(
depositor,
positionId,
amount
);
// if not equal, recurse
if (newContractAddr != contractAddr) {
depositCollateralOnBehalfOfRecurse(
newContractAddr,
depositor,
positionId,
amount
);
}
}
}
// File: contracts/margin/interfaces/lender/ForceRecoverCollateralDelegator.sol
/**
* @title ForceRecoverCollateralDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to let other addresses
* forceRecoverCollateral() a loan owned by the smart contract.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface ForceRecoverCollateralDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to let other addresses call
* forceRecoverCollateral().
*
* NOTE: If not returning zero address (or not reverting), this contract must assume that Margin
* will either revert the entire transaction or that the collateral was forcibly recovered.
*
* @param recoverer Address of the caller of the forceRecoverCollateral() function
* @param positionId Unique ID of the position
* @param recipient Address to send the recovered tokens to
* @return This address to accept, a different address to ask that contract
*/
function forceRecoverCollateralOnBehalfOf(
address recoverer,
bytes32 positionId,
address recipient
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/impl/ForceRecoverCollateralImpl.sol
/**
* @title ForceRecoverCollateralImpl
* @author dYdX
*
* This library contains the implementation for the forceRecoverCollateral function of Margin
*/
library ForceRecoverCollateralImpl {
using SafeMath for uint256;
// ============ Events ============
/**
* Collateral for a position was forcibly recovered
*/
event CollateralForceRecovered(
bytes32 indexed positionId,
address indexed recipient,
uint256 amount
);
// ============ Public Implementation Functions ============
function forceRecoverCollateralImpl(
MarginState.State storage state,
bytes32 positionId,
address recipient
)
public
returns (uint256)
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
// Can only force recover after either:
// 1) The loan was called and the call period has elapsed
// 2) The maxDuration of the position has elapsed
require( /* solium-disable-next-line */
(
position.callTimestamp > 0
&& block.timestamp >= uint256(position.callTimestamp).add(position.callTimeLimit)
) || (
block.timestamp >= uint256(position.startTimestamp).add(position.maxDuration)
),
"ForceRecoverCollateralImpl#forceRecoverCollateralImpl: Cannot recover yet"
);
// Ensure lender consent
forceRecoverCollateralOnBehalfOfRecurse(
position.lender,
msg.sender,
positionId,
recipient
);
// Send the tokens
uint256 heldTokenRecovered = MarginCommon.getPositionBalanceImpl(state, positionId);
Vault(state.VAULT).transferFromVault(
positionId,
position.heldToken,
recipient,
heldTokenRecovered
);
// Delete the position
// NOTE: Since position is a storage pointer, this will also set all fields on
// the position variable to 0
MarginCommon.cleanupPosition(
state,
positionId
);
// Log an event
emit CollateralForceRecovered(
positionId,
recipient,
heldTokenRecovered
);
return heldTokenRecovered;
}
// ============ Private Helper-Functions ============
function forceRecoverCollateralOnBehalfOfRecurse(
address contractAddr,
address recoverer,
bytes32 positionId,
address recipient
)
private
{
// no need to ask for permission
if (recoverer == contractAddr) {
return;
}
address newContractAddr =
ForceRecoverCollateralDelegator(contractAddr).forceRecoverCollateralOnBehalfOf(
recoverer,
positionId,
recipient
);
if (newContractAddr != contractAddr) {
forceRecoverCollateralOnBehalfOfRecurse(
newContractAddr,
recoverer,
positionId,
recipient
);
}
}
}
// File: contracts/lib/TypedSignature.sol
/**
* @title TypedSignature
* @author dYdX
*
* Allows for ecrecovery of signed hashes with three different prepended messages:
* 1) ""
* 2) "\x19Ethereum Signed Message:\n32"
* 3) "\x19Ethereum Signed Message:\n\x20"
*/
library TypedSignature {
// Solidity does not offer guarantees about enum values, so we define them explicitly
uint8 private constant SIGTYPE_INVALID = 0;
uint8 private constant SIGTYPE_ECRECOVER_DEC = 1;
uint8 private constant SIGTYPE_ECRECOVER_HEX = 2;
uint8 private constant SIGTYPE_UNSUPPORTED = 3;
// prepended message with the length of the signed hash in hexadecimal
bytes constant private PREPEND_HEX = "\x19Ethereum Signed Message:\n\x20";
// prepended message with the length of the signed hash in decimal
bytes constant private PREPEND_DEC = "\x19Ethereum Signed Message:\n32";
/**
* Gives the address of the signer of a hash. Allows for three common prepended strings.
*
* @param hash Hash that was signed (does not include prepended message)
* @param signatureWithType Type and ECDSA signature with structure: {1:type}{1:v}{32:r}{32:s}
* @return address of the signer of the hash
*/
function recover(
bytes32 hash,
bytes signatureWithType
)
internal
pure
returns (address)
{
require(
signatureWithType.length == 66,
"SignatureValidator#validateSignature: invalid signature length"
);
uint8 sigType = uint8(signatureWithType[0]);
require(
sigType > uint8(SIGTYPE_INVALID),
"SignatureValidator#validateSignature: invalid signature type"
);
require(
sigType < uint8(SIGTYPE_UNSUPPORTED),
"SignatureValidator#validateSignature: unsupported signature type"
);
uint8 v = uint8(signatureWithType[1]);
bytes32 r;
bytes32 s;
/* solium-disable-next-line security/no-inline-assembly */
assembly {
r := mload(add(signatureWithType, 34))
s := mload(add(signatureWithType, 66))
}
bytes32 signedHash;
if (sigType == SIGTYPE_ECRECOVER_DEC) {
signedHash = keccak256(abi.encodePacked(PREPEND_DEC, hash));
} else {
assert(sigType == SIGTYPE_ECRECOVER_HEX);
signedHash = keccak256(abi.encodePacked(PREPEND_HEX, hash));
}
return ecrecover(
signedHash,
v,
r,
s
);
}
}
// File: contracts/margin/interfaces/LoanOfferingVerifier.sol
/**
* @title LoanOfferingVerifier
* @author dYdX
*
* Interface that smart contracts must implement to be able to make off-chain generated
* loan offerings.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface LoanOfferingVerifier {
/**
* Function a smart contract must implement to be able to consent to a loan. The loan offering
* will be generated off-chain. The "loan owner" address will own the loan-side of the resulting
* position.
*
* If true is returned, and no errors are thrown by the Margin contract, the loan will have
* occurred. This means that verifyLoanOffering can also be used to update internal contract
* state on a loan.
*
* @param addresses Array of addresses:
*
* [0] = owedToken
* [1] = heldToken
* [2] = loan payer
* [3] = loan owner
* [4] = loan taker
* [5] = loan positionOwner
* [6] = loan fee recipient
* [7] = loan lender fee token
* [8] = loan taker fee token
*
* @param values256 Values corresponding to:
*
* [0] = loan maximum amount
* [1] = loan minimum amount
* [2] = loan minimum heldToken
* [3] = loan lender fee
* [4] = loan taker fee
* [5] = loan expiration timestamp (in seconds)
* [6] = loan salt
*
* @param values32 Values corresponding to:
*
* [0] = loan call time limit (in seconds)
* [1] = loan maxDuration (in seconds)
* [2] = loan interest rate (annual nominal percentage times 10**6)
* [3] = loan interest update period (in seconds)
*
* @param positionId Unique ID of the position
* @param signature Arbitrary bytes; may or may not be an ECDSA signature
* @return This address to accept, a different address to ask that contract
*/
function verifyLoanOffering(
address[9] addresses,
uint256[7] values256,
uint32[4] values32,
bytes32 positionId,
bytes signature
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/impl/BorrowShared.sol
/**
* @title BorrowShared
* @author dYdX
*
* This library contains shared functionality between OpenPositionImpl and IncreasePositionImpl.
* Both use a Loan Offering and a DEX Order to open or increase a position.
*/
library BorrowShared {
using SafeMath for uint256;
// ============ Structs ============
struct Tx {
bytes32 positionId;
address owner;
uint256 principal;
uint256 lenderAmount;
MarginCommon.LoanOffering loanOffering;
address exchangeWrapper;
bool depositInHeldToken;
uint256 depositAmount;
uint256 collateralAmount;
uint256 heldTokenFromSell;
}
// ============ Internal Implementation Functions ============
/**
* Validate the transaction before exchanging heldToken for owedToken
*/
function validateTxPreSell(
MarginState.State storage state,
Tx memory transaction
)
internal
{
assert(transaction.lenderAmount >= transaction.principal);
require(
transaction.principal > 0,
"BorrowShared#validateTxPreSell: Positions with 0 principal are not allowed"
);
// If the taker is 0x0 then any address can take it. Otherwise only the taker can use it.
if (transaction.loanOffering.taker != address(0)) {
require(
msg.sender == transaction.loanOffering.taker,
"BorrowShared#validateTxPreSell: Invalid loan offering taker"
);
}
// If the positionOwner is 0x0 then any address can be set as the position owner.
// Otherwise only the specified positionOwner can be set as the position owner.
if (transaction.loanOffering.positionOwner != address(0)) {
require(
transaction.owner == transaction.loanOffering.positionOwner,
"BorrowShared#validateTxPreSell: Invalid position owner"
);
}
// Require the loan offering to be approved by the payer
if (AddressUtils.isContract(transaction.loanOffering.payer)) {
getConsentFromSmartContractLender(transaction);
} else {
require(
transaction.loanOffering.payer == TypedSignature.recover(
transaction.loanOffering.loanHash,
transaction.loanOffering.signature
),
"BorrowShared#validateTxPreSell: Invalid loan offering signature"
);
}
// Validate the amount is <= than max and >= min
uint256 unavailable = MarginCommon.getUnavailableLoanOfferingAmountImpl(
state,
transaction.loanOffering.loanHash
);
require(
transaction.lenderAmount.add(unavailable) <= transaction.loanOffering.rates.maxAmount,
"BorrowShared#validateTxPreSell: Loan offering does not have enough available"
);
require(
transaction.lenderAmount >= transaction.loanOffering.rates.minAmount,
"BorrowShared#validateTxPreSell: Lender amount is below loan offering minimum amount"
);
require(
transaction.loanOffering.owedToken != transaction.loanOffering.heldToken,
"BorrowShared#validateTxPreSell: owedToken cannot be equal to heldToken"
);
require(
transaction.owner != address(0),
"BorrowShared#validateTxPreSell: Position owner cannot be 0"
);
require(
transaction.loanOffering.owner != address(0),
"BorrowShared#validateTxPreSell: Loan owner cannot be 0"
);
require(
transaction.loanOffering.expirationTimestamp > block.timestamp,
"BorrowShared#validateTxPreSell: Loan offering is expired"
);
require(
transaction.loanOffering.maxDuration > 0,
"BorrowShared#validateTxPreSell: Loan offering has 0 maximum duration"
);
require(
transaction.loanOffering.rates.interestPeriod <= transaction.loanOffering.maxDuration,
"BorrowShared#validateTxPreSell: Loan offering interestPeriod > maxDuration"
);
// The minimum heldToken is validated after executing the sell
// Position and loan ownership is validated in TransferInternal
}
/**
* Validate the transaction after exchanging heldToken for owedToken, pay out fees, and store
* how much of the loan was used.
*/
function doPostSell(
MarginState.State storage state,
Tx memory transaction
)
internal
{
validateTxPostSell(transaction);
// Transfer feeTokens from trader and lender
transferLoanFees(state, transaction);
// Update global amounts for the loan
state.loanFills[transaction.loanOffering.loanHash] =
state.loanFills[transaction.loanOffering.loanHash].add(transaction.lenderAmount);
}
/**
* Sells the owedToken from the lender (and from the deposit if in owedToken) using the
* exchangeWrapper, then puts the resulting heldToken into the vault. Only trades for
* maxHeldTokenToBuy of heldTokens at most.
*/
function doSell(
MarginState.State storage state,
Tx transaction,
bytes orderData,
uint256 maxHeldTokenToBuy
)
internal
returns (uint256)
{
// Move owedTokens from lender to exchange wrapper
pullOwedTokensFromLender(state, transaction);
// Sell just the lender's owedToken (if trader deposit is in heldToken)
// Otherwise sell both the lender's owedToken and the trader's deposit in owedToken
uint256 sellAmount = transaction.depositInHeldToken ?
transaction.lenderAmount :
transaction.lenderAmount.add(transaction.depositAmount);
// Do the trade, taking only the maxHeldTokenToBuy if more is returned
uint256 heldTokenFromSell = Math.min256(
maxHeldTokenToBuy,
ExchangeWrapper(transaction.exchangeWrapper).exchange(
msg.sender,
state.TOKEN_PROXY,
transaction.loanOffering.heldToken,
transaction.loanOffering.owedToken,
sellAmount,
orderData
)
);
// Move the tokens to the vault
Vault(state.VAULT).transferToVault(
transaction.positionId,
transaction.loanOffering.heldToken,
transaction.exchangeWrapper,
heldTokenFromSell
);
// Update collateral amount
transaction.collateralAmount = transaction.collateralAmount.add(heldTokenFromSell);
return heldTokenFromSell;
}
/**
* Take the owedToken deposit from the trader and give it to the exchange wrapper so that it can
* be sold for heldToken.
*/
function doDepositOwedToken(
MarginState.State storage state,
Tx transaction
)
internal
{
TokenProxy(state.TOKEN_PROXY).transferTokens(
transaction.loanOffering.owedToken,
msg.sender,
transaction.exchangeWrapper,
transaction.depositAmount
);
}
/**
* Take the heldToken deposit from the trader and move it to the vault.
*/
function doDepositHeldToken(
MarginState.State storage state,
Tx transaction
)
internal
{
Vault(state.VAULT).transferToVault(
transaction.positionId,
transaction.loanOffering.heldToken,
msg.sender,
transaction.depositAmount
);
// Update collateral amount
transaction.collateralAmount = transaction.collateralAmount.add(transaction.depositAmount);
}
// ============ Private Helper-Functions ============
function validateTxPostSell(
Tx transaction
)
private
pure
{
uint256 expectedCollateral = transaction.depositInHeldToken ?
transaction.heldTokenFromSell.add(transaction.depositAmount) :
transaction.heldTokenFromSell;
assert(transaction.collateralAmount == expectedCollateral);
uint256 loanOfferingMinimumHeldToken = MathHelpers.getPartialAmountRoundedUp(
transaction.lenderAmount,
transaction.loanOffering.rates.maxAmount,
transaction.loanOffering.rates.minHeldToken
);
require(
transaction.collateralAmount >= loanOfferingMinimumHeldToken,
"BorrowShared#validateTxPostSell: Loan offering minimum held token not met"
);
}
function getConsentFromSmartContractLender(
Tx transaction
)
private
{
verifyLoanOfferingRecurse(
transaction.loanOffering.payer,
getLoanOfferingAddresses(transaction),
getLoanOfferingValues256(transaction),
getLoanOfferingValues32(transaction),
transaction.positionId,
transaction.loanOffering.signature
);
}
function verifyLoanOfferingRecurse(
address contractAddr,
address[9] addresses,
uint256[7] values256,
uint32[4] values32,
bytes32 positionId,
bytes signature
)
private
{
address newContractAddr = LoanOfferingVerifier(contractAddr).verifyLoanOffering(
addresses,
values256,
values32,
positionId,
signature
);
if (newContractAddr != contractAddr) {
verifyLoanOfferingRecurse(
newContractAddr,
addresses,
values256,
values32,
positionId,
signature
);
}
}
function pullOwedTokensFromLender(
MarginState.State storage state,
Tx transaction
)
private
{
// Transfer owedToken to the exchange wrapper
TokenProxy(state.TOKEN_PROXY).transferTokens(
transaction.loanOffering.owedToken,
transaction.loanOffering.payer,
transaction.exchangeWrapper,
transaction.lenderAmount
);
}
function transferLoanFees(
MarginState.State storage state,
Tx transaction
)
private
{
// 0 fee address indicates no fees
if (transaction.loanOffering.feeRecipient == address(0)) {
return;
}
TokenProxy proxy = TokenProxy(state.TOKEN_PROXY);
uint256 lenderFee = MathHelpers.getPartialAmount(
transaction.lenderAmount,
transaction.loanOffering.rates.maxAmount,
transaction.loanOffering.rates.lenderFee
);
uint256 takerFee = MathHelpers.getPartialAmount(
transaction.lenderAmount,
transaction.loanOffering.rates.maxAmount,
transaction.loanOffering.rates.takerFee
);
if (lenderFee > 0) {
proxy.transferTokens(
transaction.loanOffering.lenderFeeToken,
transaction.loanOffering.payer,
transaction.loanOffering.feeRecipient,
lenderFee
);
}
if (takerFee > 0) {
proxy.transferTokens(
transaction.loanOffering.takerFeeToken,
msg.sender,
transaction.loanOffering.feeRecipient,
takerFee
);
}
}
function getLoanOfferingAddresses(
Tx transaction
)
private
pure
returns (address[9])
{
return [
transaction.loanOffering.owedToken,
transaction.loanOffering.heldToken,
transaction.loanOffering.payer,
transaction.loanOffering.owner,
transaction.loanOffering.taker,
transaction.loanOffering.positionOwner,
transaction.loanOffering.feeRecipient,
transaction.loanOffering.lenderFeeToken,
transaction.loanOffering.takerFeeToken
];
}
function getLoanOfferingValues256(
Tx transaction
)
private
pure
returns (uint256[7])
{
return [
transaction.loanOffering.rates.maxAmount,
transaction.loanOffering.rates.minAmount,
transaction.loanOffering.rates.minHeldToken,
transaction.loanOffering.rates.lenderFee,
transaction.loanOffering.rates.takerFee,
transaction.loanOffering.expirationTimestamp,
transaction.loanOffering.salt
];
}
function getLoanOfferingValues32(
Tx transaction
)
private
pure
returns (uint32[4])
{
return [
transaction.loanOffering.callTimeLimit,
transaction.loanOffering.maxDuration,
transaction.loanOffering.rates.interestRate,
transaction.loanOffering.rates.interestPeriod
];
}
}
// File: contracts/margin/interfaces/lender/IncreaseLoanDelegator.sol
/**
* @title IncreaseLoanDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to own loans on behalf of other accounts.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface IncreaseLoanDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to allow additional value to be added onto
* an owned loan. Margin will call this on the owner of a loan during increasePosition().
*
* NOTE: If not returning zero (or not reverting), this contract must assume that Margin will
* either revert the entire transaction or that the loan size was successfully increased.
*
* @param payer Lender adding additional funds to the position
* @param positionId Unique ID of the position
* @param principalAdded Principal amount to be added to the position
* @param lentAmount Amount of owedToken lent by the lender (principal plus interest, or
* zero if increaseWithoutCounterparty() is used).
* @return This address to accept, a different address to ask that contract
*/
function increaseLoanOnBehalfOf(
address payer,
bytes32 positionId,
uint256 principalAdded,
uint256 lentAmount
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/interfaces/owner/IncreasePositionDelegator.sol
/**
* @title IncreasePositionDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to own position on behalf of other
* accounts
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface IncreasePositionDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to allow additional value to be added onto
* an owned position. Margin will call this on the owner of a position during increasePosition()
*
* NOTE: If not returning zero (or not reverting), this contract must assume that Margin will
* either revert the entire transaction or that the position size was successfully increased.
*
* @param trader Address initiating the addition of funds to the position
* @param positionId Unique ID of the position
* @param principalAdded Amount of principal to be added to the position
* @return This address to accept, a different address to ask that contract
*/
function increasePositionOnBehalfOf(
address trader,
bytes32 positionId,
uint256 principalAdded
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/impl/IncreasePositionImpl.sol
/**
* @title IncreasePositionImpl
* @author dYdX
*
* This library contains the implementation for the increasePosition function of Margin
*/
library IncreasePositionImpl {
using SafeMath for uint256;
// ============ Events ============
/*
* A position was increased
*/
event PositionIncreased(
bytes32 indexed positionId,
address indexed trader,
address indexed lender,
address positionOwner,
address loanOwner,
bytes32 loanHash,
address loanFeeRecipient,
uint256 amountBorrowed,
uint256 principalAdded,
uint256 heldTokenFromSell,
uint256 depositAmount,
bool depositInHeldToken
);
// ============ Public Implementation Functions ============
function increasePositionImpl(
MarginState.State storage state,
bytes32 positionId,
address[7] addresses,
uint256[8] values256,
uint32[2] values32,
bool depositInHeldToken,
bytes signature,
bytes orderData
)
public
returns (uint256)
{
// Also ensures that the position exists
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
BorrowShared.Tx memory transaction = parseIncreasePositionTx(
position,
positionId,
addresses,
values256,
values32,
depositInHeldToken,
signature
);
validateIncrease(state, transaction, position);
doBorrowAndSell(state, transaction, orderData);
updateState(
position,
transaction.positionId,
transaction.principal,
transaction.lenderAmount,
transaction.loanOffering.payer
);
// LOG EVENT
recordPositionIncreased(transaction, position);
return transaction.lenderAmount;
}
function increaseWithoutCounterpartyImpl(
MarginState.State storage state,
bytes32 positionId,
uint256 principalToAdd
)
public
returns (uint256)
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
// Disallow adding 0 principal
require(
principalToAdd > 0,
"IncreasePositionImpl#increaseWithoutCounterpartyImpl: Cannot add 0 principal"
);
// Disallow additions after maximum duration
require(
block.timestamp < uint256(position.startTimestamp).add(position.maxDuration),
"IncreasePositionImpl#increaseWithoutCounterpartyImpl: Cannot increase after maxDuration"
);
uint256 heldTokenAmount = getCollateralNeededForAddedPrincipal(
state,
position,
positionId,
principalToAdd
);
Vault(state.VAULT).transferToVault(
positionId,
position.heldToken,
msg.sender,
heldTokenAmount
);
updateState(
position,
positionId,
principalToAdd,
0, // lent amount
msg.sender
);
emit PositionIncreased(
positionId,
msg.sender,
msg.sender,
position.owner,
position.lender,
"",
address(0),
0,
principalToAdd,
0,
heldTokenAmount,
true
);
return heldTokenAmount;
}
// ============ Private Helper-Functions ============
function doBorrowAndSell(
MarginState.State storage state,
BorrowShared.Tx memory transaction,
bytes orderData
)
private
{
// Calculate the number of heldTokens to add
uint256 collateralToAdd = getCollateralNeededForAddedPrincipal(
state,
state.positions[transaction.positionId],
transaction.positionId,
transaction.principal
);
// Do pre-exchange validations
BorrowShared.validateTxPreSell(state, transaction);
// Calculate and deposit owedToken
uint256 maxHeldTokenFromSell = MathHelpers.maxUint256();
if (!transaction.depositInHeldToken) {
transaction.depositAmount =
getOwedTokenDeposit(transaction, collateralToAdd, orderData);
BorrowShared.doDepositOwedToken(state, transaction);
maxHeldTokenFromSell = collateralToAdd;
}
// Sell owedToken for heldToken using the exchange wrapper
transaction.heldTokenFromSell = BorrowShared.doSell(
state,
transaction,
orderData,
maxHeldTokenFromSell
);
// Calculate and deposit heldToken
if (transaction.depositInHeldToken) {
require(
transaction.heldTokenFromSell <= collateralToAdd,
"IncreasePositionImpl#doBorrowAndSell: DEX order gives too much heldToken"
);
transaction.depositAmount = collateralToAdd.sub(transaction.heldTokenFromSell);
BorrowShared.doDepositHeldToken(state, transaction);
}
// Make sure the actual added collateral is what is expected
assert(transaction.collateralAmount == collateralToAdd);
// Do post-exchange validations
BorrowShared.doPostSell(state, transaction);
}
function getOwedTokenDeposit(
BorrowShared.Tx transaction,
uint256 collateralToAdd,
bytes orderData
)
private
view
returns (uint256)
{
uint256 totalOwedToken = ExchangeWrapper(transaction.exchangeWrapper).getExchangeCost(
transaction.loanOffering.heldToken,
transaction.loanOffering.owedToken,
collateralToAdd,
orderData
);
require(
transaction.lenderAmount <= totalOwedToken,
"IncreasePositionImpl#getOwedTokenDeposit: Lender amount is more than required"
);
return totalOwedToken.sub(transaction.lenderAmount);
}
function validateIncrease(
MarginState.State storage state,
BorrowShared.Tx transaction,
MarginCommon.Position storage position
)
private
view
{
assert(MarginCommon.containsPositionImpl(state, transaction.positionId));
require(
position.callTimeLimit <= transaction.loanOffering.callTimeLimit,
"IncreasePositionImpl#validateIncrease: Loan callTimeLimit is less than the position"
);
// require the position to end no later than the loanOffering's maximum acceptable end time
uint256 positionEndTimestamp = uint256(position.startTimestamp).add(position.maxDuration);
uint256 offeringEndTimestamp = block.timestamp.add(transaction.loanOffering.maxDuration);
require(
positionEndTimestamp <= offeringEndTimestamp,
"IncreasePositionImpl#validateIncrease: Loan end timestamp is less than the position"
);
require(
block.timestamp < positionEndTimestamp,
"IncreasePositionImpl#validateIncrease: Position has passed its maximum duration"
);
}
function getCollateralNeededForAddedPrincipal(
MarginState.State storage state,
MarginCommon.Position storage position,
bytes32 positionId,
uint256 principalToAdd
)
private
view
returns (uint256)
{
uint256 heldTokenBalance = MarginCommon.getPositionBalanceImpl(state, positionId);
return MathHelpers.getPartialAmountRoundedUp(
principalToAdd,
position.principal,
heldTokenBalance
);
}
function updateState(
MarginCommon.Position storage position,
bytes32 positionId,
uint256 principalAdded,
uint256 owedTokenLent,
address loanPayer
)
private
{
position.principal = position.principal.add(principalAdded);
address owner = position.owner;
address lender = position.lender;
// Ensure owner consent
increasePositionOnBehalfOfRecurse(
owner,
msg.sender,
positionId,
principalAdded
);
// Ensure lender consent
increaseLoanOnBehalfOfRecurse(
lender,
loanPayer,
positionId,
principalAdded,
owedTokenLent
);
}
function increasePositionOnBehalfOfRecurse(
address contractAddr,
address trader,
bytes32 positionId,
uint256 principalAdded
)
private
{
// Assume owner approval if not a smart contract and they increased their own position
if (trader == contractAddr && !AddressUtils.isContract(contractAddr)) {
return;
}
address newContractAddr =
IncreasePositionDelegator(contractAddr).increasePositionOnBehalfOf(
trader,
positionId,
principalAdded
);
if (newContractAddr != contractAddr) {
increasePositionOnBehalfOfRecurse(
newContractAddr,
trader,
positionId,
principalAdded
);
}
}
function increaseLoanOnBehalfOfRecurse(
address contractAddr,
address payer,
bytes32 positionId,
uint256 principalAdded,
uint256 amountLent
)
private
{
// Assume lender approval if not a smart contract and they increased their own loan
if (payer == contractAddr && !AddressUtils.isContract(contractAddr)) {
return;
}
address newContractAddr =
IncreaseLoanDelegator(contractAddr).increaseLoanOnBehalfOf(
payer,
positionId,
principalAdded,
amountLent
);
if (newContractAddr != contractAddr) {
increaseLoanOnBehalfOfRecurse(
newContractAddr,
payer,
positionId,
principalAdded,
amountLent
);
}
}
function recordPositionIncreased(
BorrowShared.Tx transaction,
MarginCommon.Position storage position
)
private
{
emit PositionIncreased(
transaction.positionId,
msg.sender,
transaction.loanOffering.payer,
position.owner,
position.lender,
transaction.loanOffering.loanHash,
transaction.loanOffering.feeRecipient,
transaction.lenderAmount,
transaction.principal,
transaction.heldTokenFromSell,
transaction.depositAmount,
transaction.depositInHeldToken
);
}
// ============ Parsing Functions ============
function parseIncreasePositionTx(
MarginCommon.Position storage position,
bytes32 positionId,
address[7] addresses,
uint256[8] values256,
uint32[2] values32,
bool depositInHeldToken,
bytes signature
)
private
view
returns (BorrowShared.Tx memory)
{
uint256 principal = values256[7];
uint256 lenderAmount = MarginCommon.calculateLenderAmountForIncreasePosition(
position,
principal,
block.timestamp
);
assert(lenderAmount >= principal);
BorrowShared.Tx memory transaction = BorrowShared.Tx({
positionId: positionId,
owner: position.owner,
principal: principal,
lenderAmount: lenderAmount,
loanOffering: parseLoanOfferingFromIncreasePositionTx(
position,
addresses,
values256,
values32,
signature
),
exchangeWrapper: addresses[6],
depositInHeldToken: depositInHeldToken,
depositAmount: 0, // set later
collateralAmount: 0, // set later
heldTokenFromSell: 0 // set later
});
return transaction;
}
function parseLoanOfferingFromIncreasePositionTx(
MarginCommon.Position storage position,
address[7] addresses,
uint256[8] values256,
uint32[2] values32,
bytes signature
)
private
view
returns (MarginCommon.LoanOffering memory)
{
MarginCommon.LoanOffering memory loanOffering = MarginCommon.LoanOffering({
owedToken: position.owedToken,
heldToken: position.heldToken,
payer: addresses[0],
owner: position.lender,
taker: addresses[1],
positionOwner: addresses[2],
feeRecipient: addresses[3],
lenderFeeToken: addresses[4],
takerFeeToken: addresses[5],
rates: parseLoanOfferingRatesFromIncreasePositionTx(position, values256),
expirationTimestamp: values256[5],
callTimeLimit: values32[0],
maxDuration: values32[1],
salt: values256[6],
loanHash: 0,
signature: signature
});
loanOffering.loanHash = MarginCommon.getLoanOfferingHash(loanOffering);
return loanOffering;
}
function parseLoanOfferingRatesFromIncreasePositionTx(
MarginCommon.Position storage position,
uint256[8] values256
)
private
view
returns (MarginCommon.LoanRates memory)
{
MarginCommon.LoanRates memory rates = MarginCommon.LoanRates({
maxAmount: values256[0],
minAmount: values256[1],
minHeldToken: values256[2],
lenderFee: values256[3],
takerFee: values256[4],
interestRate: position.interestRate,
interestPeriod: position.interestPeriod
});
return rates;
}
}
// File: contracts/margin/impl/MarginStorage.sol
/**
* @title MarginStorage
* @author dYdX
*
* This contract serves as the storage for the entire state of MarginStorage
*/
contract MarginStorage {
MarginState.State state;
}
// File: contracts/margin/impl/LoanGetters.sol
/**
* @title LoanGetters
* @author dYdX
*
* A collection of public constant getter functions that allows reading of the state of any loan
* offering stored in the dYdX protocol.
*/
contract LoanGetters is MarginStorage {
// ============ Public Constant Functions ============
/**
* Gets the principal amount of a loan offering that is no longer available.
*
* @param loanHash Unique hash of the loan offering
* @return The total unavailable amount of the loan offering, which is equal to the
* filled amount plus the canceled amount.
*/
function getLoanUnavailableAmount(
bytes32 loanHash
)
external
view
returns (uint256)
{
return MarginCommon.getUnavailableLoanOfferingAmountImpl(state, loanHash);
}
/**
* Gets the total amount of owed token lent for a loan.
*
* @param loanHash Unique hash of the loan offering
* @return The total filled amount of the loan offering.
*/
function getLoanFilledAmount(
bytes32 loanHash
)
external
view
returns (uint256)
{
return state.loanFills[loanHash];
}
/**
* Gets the amount of a loan offering that has been canceled.
*
* @param loanHash Unique hash of the loan offering
* @return The total canceled amount of the loan offering.
*/
function getLoanCanceledAmount(
bytes32 loanHash
)
external
view
returns (uint256)
{
return state.loanCancels[loanHash];
}
}
// File: contracts/margin/interfaces/lender/CancelMarginCallDelegator.sol
/**
* @title CancelMarginCallDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to let other addresses cancel a
* margin-call for a loan owned by the smart contract.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface CancelMarginCallDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to let other addresses call cancelMarginCall().
*
* NOTE: If not returning zero (or not reverting), this contract must assume that Margin will
* either revert the entire transaction or that the margin-call was successfully canceled.
*
* @param canceler Address of the caller of the cancelMarginCall function
* @param positionId Unique ID of the position
* @return This address to accept, a different address to ask that contract
*/
function cancelMarginCallOnBehalfOf(
address canceler,
bytes32 positionId
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/interfaces/lender/MarginCallDelegator.sol
/**
* @title MarginCallDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to let other addresses margin-call a loan
* owned by the smart contract.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface MarginCallDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to let other addresses call marginCall().
*
* NOTE: If not returning zero (or not reverting), this contract must assume that Margin will
* either revert the entire transaction or that the loan was successfully margin-called.
*
* @param caller Address of the caller of the marginCall function
* @param positionId Unique ID of the position
* @param depositAmount Amount of heldToken deposit that will be required to cancel the call
* @return This address to accept, a different address to ask that contract
*/
function marginCallOnBehalfOf(
address caller,
bytes32 positionId,
uint256 depositAmount
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/impl/LoanImpl.sol
/**
* @title LoanImpl
* @author dYdX
*
* This library contains the implementation for the following functions of Margin:
*
* - marginCall
* - cancelMarginCallImpl
* - cancelLoanOffering
*/
library LoanImpl {
using SafeMath for uint256;
// ============ Events ============
/**
* A position was margin-called
*/
event MarginCallInitiated(
bytes32 indexed positionId,
address indexed lender,
address indexed owner,
uint256 requiredDeposit
);
/**
* A margin call was canceled
*/
event MarginCallCanceled(
bytes32 indexed positionId,
address indexed lender,
address indexed owner,
uint256 depositAmount
);
/**
* A loan offering was canceled before it was used. Any amount less than the
* total for the loan offering can be canceled.
*/
event LoanOfferingCanceled(
bytes32 indexed loanHash,
address indexed payer,
address indexed feeRecipient,
uint256 cancelAmount
);
// ============ Public Implementation Functions ============
function marginCallImpl(
MarginState.State storage state,
bytes32 positionId,
uint256 requiredDeposit
)
public
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
require(
position.callTimestamp == 0,
"LoanImpl#marginCallImpl: The position has already been margin-called"
);
// Ensure lender consent
marginCallOnBehalfOfRecurse(
position.lender,
msg.sender,
positionId,
requiredDeposit
);
position.callTimestamp = TimestampHelper.getBlockTimestamp32();
position.requiredDeposit = requiredDeposit;
emit MarginCallInitiated(
positionId,
position.lender,
position.owner,
requiredDeposit
);
}
function cancelMarginCallImpl(
MarginState.State storage state,
bytes32 positionId
)
public
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
require(
position.callTimestamp > 0,
"LoanImpl#cancelMarginCallImpl: Position has not been margin-called"
);
// Ensure lender consent
cancelMarginCallOnBehalfOfRecurse(
position.lender,
msg.sender,
positionId
);
state.positions[positionId].callTimestamp = 0;
state.positions[positionId].requiredDeposit = 0;
emit MarginCallCanceled(
positionId,
position.lender,
position.owner,
0
);
}
function cancelLoanOfferingImpl(
MarginState.State storage state,
address[9] addresses,
uint256[7] values256,
uint32[4] values32,
uint256 cancelAmount
)
public
returns (uint256)
{
MarginCommon.LoanOffering memory loanOffering = parseLoanOffering(
addresses,
values256,
values32
);
require(
msg.sender == loanOffering.payer,
"LoanImpl#cancelLoanOfferingImpl: Only loan offering payer can cancel"
);
require(
loanOffering.expirationTimestamp > block.timestamp,
"LoanImpl#cancelLoanOfferingImpl: Loan offering has already expired"
);
uint256 remainingAmount = loanOffering.rates.maxAmount.sub(
MarginCommon.getUnavailableLoanOfferingAmountImpl(state, loanOffering.loanHash)
);
uint256 amountToCancel = Math.min256(remainingAmount, cancelAmount);
// If the loan was already fully canceled, then just return 0 amount was canceled
if (amountToCancel == 0) {
return 0;
}
state.loanCancels[loanOffering.loanHash] =
state.loanCancels[loanOffering.loanHash].add(amountToCancel);
emit LoanOfferingCanceled(
loanOffering.loanHash,
loanOffering.payer,
loanOffering.feeRecipient,
amountToCancel
);
return amountToCancel;
}
// ============ Private Helper-Functions ============
function marginCallOnBehalfOfRecurse(
address contractAddr,
address who,
bytes32 positionId,
uint256 requiredDeposit
)
private
{
// no need to ask for permission
if (who == contractAddr) {
return;
}
address newContractAddr =
MarginCallDelegator(contractAddr).marginCallOnBehalfOf(
msg.sender,
positionId,
requiredDeposit
);
if (newContractAddr != contractAddr) {
marginCallOnBehalfOfRecurse(
newContractAddr,
who,
positionId,
requiredDeposit
);
}
}
function cancelMarginCallOnBehalfOfRecurse(
address contractAddr,
address who,
bytes32 positionId
)
private
{
// no need to ask for permission
if (who == contractAddr) {
return;
}
address newContractAddr =
CancelMarginCallDelegator(contractAddr).cancelMarginCallOnBehalfOf(
msg.sender,
positionId
);
if (newContractAddr != contractAddr) {
cancelMarginCallOnBehalfOfRecurse(
newContractAddr,
who,
positionId
);
}
}
// ============ Parsing Functions ============
function parseLoanOffering(
address[9] addresses,
uint256[7] values256,
uint32[4] values32
)
private
view
returns (MarginCommon.LoanOffering memory)
{
MarginCommon.LoanOffering memory loanOffering = MarginCommon.LoanOffering({
owedToken: addresses[0],
heldToken: addresses[1],
payer: addresses[2],
owner: addresses[3],
taker: addresses[4],
positionOwner: addresses[5],
feeRecipient: addresses[6],
lenderFeeToken: addresses[7],
takerFeeToken: addresses[8],
rates: parseLoanOfferRates(values256, values32),
expirationTimestamp: values256[5],
callTimeLimit: values32[0],
maxDuration: values32[1],
salt: values256[6],
loanHash: 0,
signature: new bytes(0)
});
loanOffering.loanHash = MarginCommon.getLoanOfferingHash(loanOffering);
return loanOffering;
}
function parseLoanOfferRates(
uint256[7] values256,
uint32[4] values32
)
private
pure
returns (MarginCommon.LoanRates memory)
{
MarginCommon.LoanRates memory rates = MarginCommon.LoanRates({
maxAmount: values256[0],
minAmount: values256[1],
minHeldToken: values256[2],
interestRate: values32[2],
lenderFee: values256[3],
takerFee: values256[4],
interestPeriod: values32[3]
});
return rates;
}
}
// File: contracts/margin/impl/MarginAdmin.sol
/**
* @title MarginAdmin
* @author dYdX
*
* Contains admin functions for the Margin contract
* The owner can put Margin into various close-only modes, which will disallow new position creation
*/
contract MarginAdmin is Ownable {
// ============ Enums ============
// All functionality enabled
uint8 private constant OPERATION_STATE_OPERATIONAL = 0;
// Only closing functions + cancelLoanOffering allowed (marginCall, closePosition,
// cancelLoanOffering, closePositionDirectly, forceRecoverCollateral)
uint8 private constant OPERATION_STATE_CLOSE_AND_CANCEL_LOAN_ONLY = 1;
// Only closing functions allowed (marginCall, closePosition, closePositionDirectly,
// forceRecoverCollateral)
uint8 private constant OPERATION_STATE_CLOSE_ONLY = 2;
// Only closing functions allowed (marginCall, closePositionDirectly, forceRecoverCollateral)
uint8 private constant OPERATION_STATE_CLOSE_DIRECTLY_ONLY = 3;
// This operation state (and any higher) is invalid
uint8 private constant OPERATION_STATE_INVALID = 4;
// ============ Events ============
/**
* Event indicating the operation state has changed
*/
event OperationStateChanged(
uint8 from,
uint8 to
);
// ============ State Variables ============
uint8 public operationState;
// ============ Constructor ============
constructor()
public
Ownable()
{
operationState = OPERATION_STATE_OPERATIONAL;
}
// ============ Modifiers ============
modifier onlyWhileOperational() {
require(
operationState == OPERATION_STATE_OPERATIONAL,
"MarginAdmin#onlyWhileOperational: Can only call while operational"
);
_;
}
modifier cancelLoanOfferingStateControl() {
require(
operationState == OPERATION_STATE_OPERATIONAL
|| operationState == OPERATION_STATE_CLOSE_AND_CANCEL_LOAN_ONLY,
"MarginAdmin#cancelLoanOfferingStateControl: Invalid operation state"
);
_;
}
modifier closePositionStateControl() {
require(
operationState == OPERATION_STATE_OPERATIONAL
|| operationState == OPERATION_STATE_CLOSE_AND_CANCEL_LOAN_ONLY
|| operationState == OPERATION_STATE_CLOSE_ONLY,
"MarginAdmin#closePositionStateControl: Invalid operation state"
);
_;
}
modifier closePositionDirectlyStateControl() {
_;
}
// ============ Owner-Only State-Changing Functions ============
function setOperationState(
uint8 newState
)
external
onlyOwner
{
require(
newState < OPERATION_STATE_INVALID,
"MarginAdmin#setOperationState: newState is not a valid operation state"
);
if (newState != operationState) {
emit OperationStateChanged(
operationState,
newState
);
operationState = newState;
}
}
}
// File: contracts/margin/impl/MarginEvents.sol
/**
* @title MarginEvents
* @author dYdX
*
* Contains events for the Margin contract.
*
* NOTE: Any Margin function libraries that use events will need to both define the event here
* and copy the event into the library itself as libraries don't support sharing events
*/
contract MarginEvents {
// ============ Events ============
/**
* A position was opened
*/
event PositionOpened(
bytes32 indexed positionId,
address indexed trader,
address indexed lender,
bytes32 loanHash,
address owedToken,
address heldToken,
address loanFeeRecipient,
uint256 principal,
uint256 heldTokenFromSell,
uint256 depositAmount,
uint256 interestRate,
uint32 callTimeLimit,
uint32 maxDuration,
bool depositInHeldToken
);
/*
* A position was increased
*/
event PositionIncreased(
bytes32 indexed positionId,
address indexed trader,
address indexed lender,
address positionOwner,
address loanOwner,
bytes32 loanHash,
address loanFeeRecipient,
uint256 amountBorrowed,
uint256 principalAdded,
uint256 heldTokenFromSell,
uint256 depositAmount,
bool depositInHeldToken
);
/**
* A position was closed or partially closed
*/
event PositionClosed(
bytes32 indexed positionId,
address indexed closer,
address indexed payoutRecipient,
uint256 closeAmount,
uint256 remainingAmount,
uint256 owedTokenPaidToLender,
uint256 payoutAmount,
uint256 buybackCostInHeldToken,
bool payoutInHeldToken
);
/**
* Collateral for a position was forcibly recovered
*/
event CollateralForceRecovered(
bytes32 indexed positionId,
address indexed recipient,
uint256 amount
);
/**
* A position was margin-called
*/
event MarginCallInitiated(
bytes32 indexed positionId,
address indexed lender,
address indexed owner,
uint256 requiredDeposit
);
/**
* A margin call was canceled
*/
event MarginCallCanceled(
bytes32 indexed positionId,
address indexed lender,
address indexed owner,
uint256 depositAmount
);
/**
* A loan offering was canceled before it was used. Any amount less than the
* total for the loan offering can be canceled.
*/
event LoanOfferingCanceled(
bytes32 indexed loanHash,
address indexed payer,
address indexed feeRecipient,
uint256 cancelAmount
);
/**
* Additional collateral for a position was posted by the owner
*/
event AdditionalCollateralDeposited(
bytes32 indexed positionId,
uint256 amount,
address depositor
);
/**
* Ownership of a loan was transferred to a new address
*/
event LoanTransferred(
bytes32 indexed positionId,
address indexed from,
address indexed to
);
/**
* Ownership of a position was transferred to a new address
*/
event PositionTransferred(
bytes32 indexed positionId,
address indexed from,
address indexed to
);
}
// File: contracts/margin/impl/OpenPositionImpl.sol
/**
* @title OpenPositionImpl
* @author dYdX
*
* This library contains the implementation for the openPosition function of Margin
*/
library OpenPositionImpl {
using SafeMath for uint256;
// ============ Events ============
/**
* A position was opened
*/
event PositionOpened(
bytes32 indexed positionId,
address indexed trader,
address indexed lender,
bytes32 loanHash,
address owedToken,
address heldToken,
address loanFeeRecipient,
uint256 principal,
uint256 heldTokenFromSell,
uint256 depositAmount,
uint256 interestRate,
uint32 callTimeLimit,
uint32 maxDuration,
bool depositInHeldToken
);
// ============ Public Implementation Functions ============
function openPositionImpl(
MarginState.State storage state,
address[11] addresses,
uint256[10] values256,
uint32[4] values32,
bool depositInHeldToken,
bytes signature,
bytes orderData
)
public
returns (bytes32)
{
BorrowShared.Tx memory transaction = parseOpenTx(
addresses,
values256,
values32,
depositInHeldToken,
signature
);
require(
!MarginCommon.positionHasExisted(state, transaction.positionId),
"OpenPositionImpl#openPositionImpl: positionId already exists"
);
doBorrowAndSell(state, transaction, orderData);
// Before doStoreNewPosition() so that PositionOpened event is before Transferred events
recordPositionOpened(
transaction
);
doStoreNewPosition(
state,
transaction
);
return transaction.positionId;
}
// ============ Private Helper-Functions ============
function doBorrowAndSell(
MarginState.State storage state,
BorrowShared.Tx memory transaction,
bytes orderData
)
private
{
BorrowShared.validateTxPreSell(state, transaction);
if (transaction.depositInHeldToken) {
BorrowShared.doDepositHeldToken(state, transaction);
} else {
BorrowShared.doDepositOwedToken(state, transaction);
}
transaction.heldTokenFromSell = BorrowShared.doSell(
state,
transaction,
orderData,
MathHelpers.maxUint256()
);
BorrowShared.doPostSell(state, transaction);
}
function doStoreNewPosition(
MarginState.State storage state,
BorrowShared.Tx memory transaction
)
private
{
MarginCommon.storeNewPosition(
state,
transaction.positionId,
MarginCommon.Position({
owedToken: transaction.loanOffering.owedToken,
heldToken: transaction.loanOffering.heldToken,
lender: transaction.loanOffering.owner,
owner: transaction.owner,
principal: transaction.principal,
requiredDeposit: 0,
callTimeLimit: transaction.loanOffering.callTimeLimit,
startTimestamp: 0,
callTimestamp: 0,
maxDuration: transaction.loanOffering.maxDuration,
interestRate: transaction.loanOffering.rates.interestRate,
interestPeriod: transaction.loanOffering.rates.interestPeriod
}),
transaction.loanOffering.payer
);
}
function recordPositionOpened(
BorrowShared.Tx transaction
)
private
{
emit PositionOpened(
transaction.positionId,
msg.sender,
transaction.loanOffering.payer,
transaction.loanOffering.loanHash,
transaction.loanOffering.owedToken,
transaction.loanOffering.heldToken,
transaction.loanOffering.feeRecipient,
transaction.principal,
transaction.heldTokenFromSell,
transaction.depositAmount,
transaction.loanOffering.rates.interestRate,
transaction.loanOffering.callTimeLimit,
transaction.loanOffering.maxDuration,
transaction.depositInHeldToken
);
}
// ============ Parsing Functions ============
function parseOpenTx(
address[11] addresses,
uint256[10] values256,
uint32[4] values32,
bool depositInHeldToken,
bytes signature
)
private
view
returns (BorrowShared.Tx memory)
{
BorrowShared.Tx memory transaction = BorrowShared.Tx({
positionId: MarginCommon.getPositionIdFromNonce(values256[9]),
owner: addresses[0],
principal: values256[7],
lenderAmount: values256[7],
loanOffering: parseLoanOffering(
addresses,
values256,
values32,
signature
),
exchangeWrapper: addresses[10],
depositInHeldToken: depositInHeldToken,
depositAmount: values256[8],
collateralAmount: 0, // set later
heldTokenFromSell: 0 // set later
});
return transaction;
}
function parseLoanOffering(
address[11] addresses,
uint256[10] values256,
uint32[4] values32,
bytes signature
)
private
view
returns (MarginCommon.LoanOffering memory)
{
MarginCommon.LoanOffering memory loanOffering = MarginCommon.LoanOffering({
owedToken: addresses[1],
heldToken: addresses[2],
payer: addresses[3],
owner: addresses[4],
taker: addresses[5],
positionOwner: addresses[6],
feeRecipient: addresses[7],
lenderFeeToken: addresses[8],
takerFeeToken: addresses[9],
rates: parseLoanOfferRates(values256, values32),
expirationTimestamp: values256[5],
callTimeLimit: values32[0],
maxDuration: values32[1],
salt: values256[6],
loanHash: 0,
signature: signature
});
loanOffering.loanHash = MarginCommon.getLoanOfferingHash(loanOffering);
return loanOffering;
}
function parseLoanOfferRates(
uint256[10] values256,
uint32[4] values32
)
private
pure
returns (MarginCommon.LoanRates memory)
{
MarginCommon.LoanRates memory rates = MarginCommon.LoanRates({
maxAmount: values256[0],
minAmount: values256[1],
minHeldToken: values256[2],
lenderFee: values256[3],
takerFee: values256[4],
interestRate: values32[2],
interestPeriod: values32[3]
});
return rates;
}
}
// File: contracts/margin/impl/OpenWithoutCounterpartyImpl.sol
/**
* @title OpenWithoutCounterpartyImpl
* @author dYdX
*
* This library contains the implementation for the openWithoutCounterparty
* function of Margin
*/
library OpenWithoutCounterpartyImpl {
// ============ Structs ============
struct Tx {
bytes32 positionId;
address positionOwner;
address owedToken;
address heldToken;
address loanOwner;
uint256 principal;
uint256 deposit;
uint32 callTimeLimit;
uint32 maxDuration;
uint32 interestRate;
uint32 interestPeriod;
}
// ============ Events ============
/**
* A position was opened
*/
event PositionOpened(
bytes32 indexed positionId,
address indexed trader,
address indexed lender,
bytes32 loanHash,
address owedToken,
address heldToken,
address loanFeeRecipient,
uint256 principal,
uint256 heldTokenFromSell,
uint256 depositAmount,
uint256 interestRate,
uint32 callTimeLimit,
uint32 maxDuration,
bool depositInHeldToken
);
// ============ Public Implementation Functions ============
function openWithoutCounterpartyImpl(
MarginState.State storage state,
address[4] addresses,
uint256[3] values256,
uint32[4] values32
)
public
returns (bytes32)
{
Tx memory openTx = parseTx(
addresses,
values256,
values32
);
validate(
state,
openTx
);
Vault(state.VAULT).transferToVault(
openTx.positionId,
openTx.heldToken,
msg.sender,
openTx.deposit
);
recordPositionOpened(
openTx
);
doStoreNewPosition(
state,
openTx
);
return openTx.positionId;
}
// ============ Private Helper-Functions ============
function doStoreNewPosition(
MarginState.State storage state,
Tx memory openTx
)
private
{
MarginCommon.storeNewPosition(
state,
openTx.positionId,
MarginCommon.Position({
owedToken: openTx.owedToken,
heldToken: openTx.heldToken,
lender: openTx.loanOwner,
owner: openTx.positionOwner,
principal: openTx.principal,
requiredDeposit: 0,
callTimeLimit: openTx.callTimeLimit,
startTimestamp: 0,
callTimestamp: 0,
maxDuration: openTx.maxDuration,
interestRate: openTx.interestRate,
interestPeriod: openTx.interestPeriod
}),
msg.sender
);
}
function validate(
MarginState.State storage state,
Tx memory openTx
)
private
view
{
require(
!MarginCommon.positionHasExisted(state, openTx.positionId),
"openWithoutCounterpartyImpl#validate: positionId already exists"
);
require(
openTx.principal > 0,
"openWithoutCounterpartyImpl#validate: principal cannot be 0"
);
require(
openTx.owedToken != address(0),
"openWithoutCounterpartyImpl#validate: owedToken cannot be 0"
);
require(
openTx.owedToken != openTx.heldToken,
"openWithoutCounterpartyImpl#validate: owedToken cannot be equal to heldToken"
);
require(
openTx.positionOwner != address(0),
"openWithoutCounterpartyImpl#validate: positionOwner cannot be 0"
);
require(
openTx.loanOwner != address(0),
"openWithoutCounterpartyImpl#validate: loanOwner cannot be 0"
);
require(
openTx.maxDuration > 0,
"openWithoutCounterpartyImpl#validate: maxDuration cannot be 0"
);
require(
openTx.interestPeriod <= openTx.maxDuration,
"openWithoutCounterpartyImpl#validate: interestPeriod must be <= maxDuration"
);
}
function recordPositionOpened(
Tx memory openTx
)
private
{
emit PositionOpened(
openTx.positionId,
msg.sender,
msg.sender,
bytes32(0),
openTx.owedToken,
openTx.heldToken,
address(0),
openTx.principal,
0,
openTx.deposit,
openTx.interestRate,
openTx.callTimeLimit,
openTx.maxDuration,
true
);
}
// ============ Parsing Functions ============
function parseTx(
address[4] addresses,
uint256[3] values256,
uint32[4] values32
)
private
view
returns (Tx memory)
{
Tx memory openTx = Tx({
positionId: MarginCommon.getPositionIdFromNonce(values256[2]),
positionOwner: addresses[0],
owedToken: addresses[1],
heldToken: addresses[2],
loanOwner: addresses[3],
principal: values256[0],
deposit: values256[1],
callTimeLimit: values32[0],
maxDuration: values32[1],
interestRate: values32[2],
interestPeriod: values32[3]
});
return openTx;
}
}
// File: contracts/margin/impl/PositionGetters.sol
/**
* @title PositionGetters
* @author dYdX
*
* A collection of public constant getter functions that allows reading of the state of any position
* stored in the dYdX protocol.
*/
contract PositionGetters is MarginStorage {
using SafeMath for uint256;
// ============ Public Constant Functions ============
/**
* Gets if a position is currently open.
*
* @param positionId Unique ID of the position
* @return True if the position is exists and is open
*/
function containsPosition(
bytes32 positionId
)
external
view
returns (bool)
{
return MarginCommon.containsPositionImpl(state, positionId);
}
/**
* Gets if a position is currently margin-called.
*
* @param positionId Unique ID of the position
* @return True if the position is margin-called
*/
function isPositionCalled(
bytes32 positionId
)
external
view
returns (bool)
{
return (state.positions[positionId].callTimestamp > 0);
}
/**
* Gets if a position was previously open and is now closed.
*
* @param positionId Unique ID of the position
* @return True if the position is now closed
*/
function isPositionClosed(
bytes32 positionId
)
external
view
returns (bool)
{
return state.closedPositions[positionId];
}
/**
* Gets the total amount of owedToken ever repaid to the lender for a position.
*
* @param positionId Unique ID of the position
* @return Total amount of owedToken ever repaid
*/
function getTotalOwedTokenRepaidToLender(
bytes32 positionId
)
external
view
returns (uint256)
{
return state.totalOwedTokenRepaidToLender[positionId];
}
/**
* Gets the amount of heldToken currently locked up in Vault for a particular position.
*
* @param positionId Unique ID of the position
* @return The amount of heldToken
*/
function getPositionBalance(
bytes32 positionId
)
external
view
returns (uint256)
{
return MarginCommon.getPositionBalanceImpl(state, positionId);
}
/**
* Gets the time until the interest fee charged for the position will increase.
* Returns 1 if the interest fee increases every second.
* Returns 0 if the interest fee will never increase again.
*
* @param positionId Unique ID of the position
* @return The number of seconds until the interest fee will increase
*/
function getTimeUntilInterestIncrease(
bytes32 positionId
)
external
view
returns (uint256)
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
uint256 effectiveTimeElapsed = MarginCommon.calculateEffectiveTimeElapsed(
position,
block.timestamp
);
uint256 absoluteTimeElapsed = block.timestamp.sub(position.startTimestamp);
if (absoluteTimeElapsed > effectiveTimeElapsed) { // past maxDuration
return 0;
} else {
// nextStep is the final second at which the calculated interest fee is the same as it
// is currently, so add 1 to get the correct value
return effectiveTimeElapsed.add(1).sub(absoluteTimeElapsed);
}
}
/**
* Gets the amount of owedTokens currently needed to close the position completely, including
* interest fees.
*
* @param positionId Unique ID of the position
* @return The number of owedTokens
*/
function getPositionOwedAmount(
bytes32 positionId
)
external
view
returns (uint256)
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
return MarginCommon.calculateOwedAmount(
position,
position.principal,
block.timestamp
);
}
/**
* Gets the amount of owedTokens needed to close a given principal amount of the position at a
* given time, including interest fees.
*
* @param positionId Unique ID of the position
* @param principalToClose Amount of principal being closed
* @param timestamp Block timestamp in seconds of close
* @return The number of owedTokens owed
*/
function getPositionOwedAmountAtTime(
bytes32 positionId,
uint256 principalToClose,
uint32 timestamp
)
external
view
returns (uint256)
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
require(
timestamp >= position.startTimestamp,
"PositionGetters#getPositionOwedAmountAtTime: Requested time before position started"
);
return MarginCommon.calculateOwedAmount(
position,
principalToClose,
timestamp
);
}
/**
* Gets the amount of owedTokens that can be borrowed from a lender to add a given principal
* amount to the position at a given time.
*
* @param positionId Unique ID of the position
* @param principalToAdd Amount being added to principal
* @param timestamp Block timestamp in seconds of addition
* @return The number of owedTokens that will be borrowed
*/
function getLenderAmountForIncreasePositionAtTime(
bytes32 positionId,
uint256 principalToAdd,
uint32 timestamp
)
external
view
returns (uint256)
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
require(
timestamp >= position.startTimestamp,
"PositionGetters#getLenderAmountForIncreasePositionAtTime: timestamp < position start"
);
return MarginCommon.calculateLenderAmountForIncreasePosition(
position,
principalToAdd,
timestamp
);
}
// ============ All Properties ============
/**
* Get a Position by id. This does not validate the position exists. If the position does not
* exist, all 0's will be returned.
*
* @param positionId Unique ID of the position
* @return Addresses corresponding to:
*
* [0] = owedToken
* [1] = heldToken
* [2] = lender
* [3] = owner
*
* Values corresponding to:
*
* [0] = principal
* [1] = requiredDeposit
*
* Values corresponding to:
*
* [0] = callTimeLimit
* [1] = startTimestamp
* [2] = callTimestamp
* [3] = maxDuration
* [4] = interestRate
* [5] = interestPeriod
*/
function getPosition(
bytes32 positionId
)
external
view
returns (
address[4],
uint256[2],
uint32[6]
)
{
MarginCommon.Position storage position = state.positions[positionId];
return (
[
position.owedToken,
position.heldToken,
position.lender,
position.owner
],
[
position.principal,
position.requiredDeposit
],
[
position.callTimeLimit,
position.startTimestamp,
position.callTimestamp,
position.maxDuration,
position.interestRate,
position.interestPeriod
]
);
}
// ============ Individual Properties ============
function getPositionLender(
bytes32 positionId
)
external
view
returns (address)
{
return state.positions[positionId].lender;
}
function getPositionOwner(
bytes32 positionId
)
external
view
returns (address)
{
return state.positions[positionId].owner;
}
function getPositionHeldToken(
bytes32 positionId
)
external
view
returns (address)
{
return state.positions[positionId].heldToken;
}
function getPositionOwedToken(
bytes32 positionId
)
external
view
returns (address)
{
return state.positions[positionId].owedToken;
}
function getPositionPrincipal(
bytes32 positionId
)
external
view
returns (uint256)
{
return state.positions[positionId].principal;
}
function getPositionInterestRate(
bytes32 positionId
)
external
view
returns (uint256)
{
return state.positions[positionId].interestRate;
}
function getPositionRequiredDeposit(
bytes32 positionId
)
external
view
returns (uint256)
{
return state.positions[positionId].requiredDeposit;
}
function getPositionStartTimestamp(
bytes32 positionId
)
external
view
returns (uint32)
{
return state.positions[positionId].startTimestamp;
}
function getPositionCallTimestamp(
bytes32 positionId
)
external
view
returns (uint32)
{
return state.positions[positionId].callTimestamp;
}
function getPositionCallTimeLimit(
bytes32 positionId
)
external
view
returns (uint32)
{
return state.positions[positionId].callTimeLimit;
}
function getPositionMaxDuration(
bytes32 positionId
)
external
view
returns (uint32)
{
return state.positions[positionId].maxDuration;
}
function getPositioninterestPeriod(
bytes32 positionId
)
external
view
returns (uint32)
{
return state.positions[positionId].interestPeriod;
}
}
// File: contracts/margin/impl/TransferImpl.sol
/**
* @title TransferImpl
* @author dYdX
*
* This library contains the implementation for the transferPosition and transferLoan functions of
* Margin
*/
library TransferImpl {
// ============ Public Implementation Functions ============
function transferLoanImpl(
MarginState.State storage state,
bytes32 positionId,
address newLender
)
public
{
require(
MarginCommon.containsPositionImpl(state, positionId),
"TransferImpl#transferLoanImpl: Position does not exist"
);
address originalLender = state.positions[positionId].lender;
require(
msg.sender == originalLender,
"TransferImpl#transferLoanImpl: Only lender can transfer ownership"
);
require(
newLender != originalLender,
"TransferImpl#transferLoanImpl: Cannot transfer ownership to self"
);
// Doesn't change the state of positionId; figures out the final owner of loan.
// That is, newLender may pass ownership to a different address.
address finalLender = TransferInternal.grantLoanOwnership(
positionId,
originalLender,
newLender);
require(
finalLender != originalLender,
"TransferImpl#transferLoanImpl: Cannot ultimately transfer ownership to self"
);
// Set state only after resolving the new owner (to reduce the number of storage calls)
state.positions[positionId].lender = finalLender;
}
function transferPositionImpl(
MarginState.State storage state,
bytes32 positionId,
address newOwner
)
public
{
require(
MarginCommon.containsPositionImpl(state, positionId),
"TransferImpl#transferPositionImpl: Position does not exist"
);
address originalOwner = state.positions[positionId].owner;
require(
msg.sender == originalOwner,
"TransferImpl#transferPositionImpl: Only position owner can transfer ownership"
);
require(
newOwner != originalOwner,
"TransferImpl#transferPositionImpl: Cannot transfer ownership to self"
);
// Doesn't change the state of positionId; figures out the final owner of position.
// That is, newOwner may pass ownership to a different address.
address finalOwner = TransferInternal.grantPositionOwnership(
positionId,
originalOwner,
newOwner);
require(
finalOwner != originalOwner,
"TransferImpl#transferPositionImpl: Cannot ultimately transfer ownership to self"
);
// Set state only after resolving the new owner (to reduce the number of storage calls)
state.positions[positionId].owner = finalOwner;
}
}
// File: contracts/margin/Margin.sol
/**
* @title Margin
* @author dYdX
*
* This contract is used to facilitate margin trading as per the dYdX protocol
*/
contract Margin is
ReentrancyGuard,
MarginStorage,
MarginEvents,
MarginAdmin,
LoanGetters,
PositionGetters
{
using SafeMath for uint256;
// ============ Constructor ============
constructor(
address vault,
address proxy
)
public
MarginAdmin()
{
state = MarginState.State({
VAULT: vault,
TOKEN_PROXY: proxy
});
}
// ============ Public State Changing Functions ============
/**
* Open a margin position. Called by the margin trader who must provide both a
* signed loan offering as well as a DEX Order with which to sell the owedToken.
*
* @param addresses Addresses corresponding to:
*
* [0] = position owner
* [1] = owedToken
* [2] = heldToken
* [3] = loan payer
* [4] = loan owner
* [5] = loan taker
* [6] = loan position owner
* [7] = loan fee recipient
* [8] = loan lender fee token
* [9] = loan taker fee token
* [10] = exchange wrapper address
*
* @param values256 Values corresponding to:
*
* [0] = loan maximum amount
* [1] = loan minimum amount
* [2] = loan minimum heldToken
* [3] = loan lender fee
* [4] = loan taker fee
* [5] = loan expiration timestamp (in seconds)
* [6] = loan salt
* [7] = position amount of principal
* [8] = deposit amount
* [9] = nonce (used to calculate positionId)
*
* @param values32 Values corresponding to:
*
* [0] = loan call time limit (in seconds)
* [1] = loan maxDuration (in seconds)
* [2] = loan interest rate (annual nominal percentage times 10**6)
* [3] = loan interest update period (in seconds)
*
* @param depositInHeldToken True if the trader wishes to pay the margin deposit in heldToken.
* False if the margin deposit will be in owedToken
* and then sold along with the owedToken borrowed from the lender
* @param signature If loan payer is an account, then this must be the tightly-packed
* ECDSA V/R/S parameters from signing the loan hash. If loan payer
* is a smart contract, these are arbitrary bytes that the contract
* will recieve when choosing whether to approve the loan.
* @param order Order object to be passed to the exchange wrapper
* @return Unique ID for the new position
*/
function openPosition(
address[11] addresses,
uint256[10] values256,
uint32[4] values32,
bool depositInHeldToken,
bytes signature,
bytes order
)
external
onlyWhileOperational
nonReentrant
returns (bytes32)
{
return OpenPositionImpl.openPositionImpl(
state,
addresses,
values256,
values32,
depositInHeldToken,
signature,
order
);
}
/**
* Open a margin position without a counterparty. The caller will serve as both the
* lender and the position owner
*
* @param addresses Addresses corresponding to:
*
* [0] = position owner
* [1] = owedToken
* [2] = heldToken
* [3] = loan owner
*
* @param values256 Values corresponding to:
*
* [0] = principal
* [1] = deposit amount
* [2] = nonce (used to calculate positionId)
*
* @param values32 Values corresponding to:
*
* [0] = call time limit (in seconds)
* [1] = maxDuration (in seconds)
* [2] = interest rate (annual nominal percentage times 10**6)
* [3] = interest update period (in seconds)
*
* @return Unique ID for the new position
*/
function openWithoutCounterparty(
address[4] addresses,
uint256[3] values256,
uint32[4] values32
)
external
onlyWhileOperational
nonReentrant
returns (bytes32)
{
return OpenWithoutCounterpartyImpl.openWithoutCounterpartyImpl(
state,
addresses,
values256,
values32
);
}
/**
* Increase the size of a position. Funds will be borrowed from the loan payer and sold as per
* the position. The amount of owedToken borrowed from the lender will be >= the amount of
* principal added, as it will incorporate interest already earned by the position so far.
*
* @param positionId Unique ID of the position
* @param addresses Addresses corresponding to:
*
* [0] = loan payer
* [1] = loan taker
* [2] = loan position owner
* [3] = loan fee recipient
* [4] = loan lender fee token
* [5] = loan taker fee token
* [6] = exchange wrapper address
*
* @param values256 Values corresponding to:
*
* [0] = loan maximum amount
* [1] = loan minimum amount
* [2] = loan minimum heldToken
* [3] = loan lender fee
* [4] = loan taker fee
* [5] = loan expiration timestamp (in seconds)
* [6] = loan salt
* [7] = amount of principal to add to the position (NOTE: the amount pulled from the lender
* will be >= this amount)
*
* @param values32 Values corresponding to:
*
* [0] = loan call time limit (in seconds)
* [1] = loan maxDuration (in seconds)
*
* @param depositInHeldToken True if the trader wishes to pay the margin deposit in heldToken.
* False if the margin deposit will be pulled in owedToken
* and then sold along with the owedToken borrowed from the lender
* @param signature If loan payer is an account, then this must be the tightly-packed
* ECDSA V/R/S parameters from signing the loan hash. If loan payer
* is a smart contract, these are arbitrary bytes that the contract
* will recieve when choosing whether to approve the loan.
* @param order Order object to be passed to the exchange wrapper
* @return Amount of owedTokens pulled from the lender
*/
function increasePosition(
bytes32 positionId,
address[7] addresses,
uint256[8] values256,
uint32[2] values32,
bool depositInHeldToken,
bytes signature,
bytes order
)
external
onlyWhileOperational
nonReentrant
returns (uint256)
{
return IncreasePositionImpl.increasePositionImpl(
state,
positionId,
addresses,
values256,
values32,
depositInHeldToken,
signature,
order
);
}
/**
* Increase a position directly by putting up heldToken. The caller will serve as both the
* lender and the position owner
*
* @param positionId Unique ID of the position
* @param principalToAdd Principal amount to add to the position
* @return Amount of heldToken pulled from the msg.sender
*/
function increaseWithoutCounterparty(
bytes32 positionId,
uint256 principalToAdd
)
external
onlyWhileOperational
nonReentrant
returns (uint256)
{
return IncreasePositionImpl.increaseWithoutCounterpartyImpl(
state,
positionId,
principalToAdd
);
}
/**
* Close a position. May be called by the owner or with the approval of the owner. May provide
* an order and exchangeWrapper to facilitate the closing of the position. The payoutRecipient
* is sent the resulting payout.
*
* @param positionId Unique ID of the position
* @param requestedCloseAmount Principal amount of the position to close. The actual amount
* closed is also bounded by:
* 1) The principal of the position
* 2) The amount allowed by the owner if closer != owner
* @param payoutRecipient Address of the recipient of tokens paid out from closing
* @param exchangeWrapper Address of the exchange wrapper
* @param payoutInHeldToken True to pay out the payoutRecipient in heldToken,
* False to pay out the payoutRecipient in owedToken
* @param order Order object to be passed to the exchange wrapper
* @return Values corresponding to:
* 1) Principal of position closed
* 2) Amount of tokens (heldToken if payoutInHeldtoken is true,
* owedToken otherwise) received by the payoutRecipient
* 3) Amount of owedToken paid (incl. interest fee) to the lender
*/
function closePosition(
bytes32 positionId,
uint256 requestedCloseAmount,
address payoutRecipient,
address exchangeWrapper,
bool payoutInHeldToken,
bytes order
)
external
closePositionStateControl
nonReentrant
returns (uint256, uint256, uint256)
{
return ClosePositionImpl.closePositionImpl(
state,
positionId,
requestedCloseAmount,
payoutRecipient,
exchangeWrapper,
payoutInHeldToken,
order
);
}
/**
* Helper to close a position by paying owedToken directly rather than using an exchangeWrapper.
*
* @param positionId Unique ID of the position
* @param requestedCloseAmount Principal amount of the position to close. The actual amount
* closed is also bounded by:
* 1) The principal of the position
* 2) The amount allowed by the owner if closer != owner
* @param payoutRecipient Address of the recipient of tokens paid out from closing
* @return Values corresponding to:
* 1) Principal amount of position closed
* 2) Amount of heldToken received by the payoutRecipient
* 3) Amount of owedToken paid (incl. interest fee) to the lender
*/
function closePositionDirectly(
bytes32 positionId,
uint256 requestedCloseAmount,
address payoutRecipient
)
external
closePositionDirectlyStateControl
nonReentrant
returns (uint256, uint256, uint256)
{
return ClosePositionImpl.closePositionImpl(
state,
positionId,
requestedCloseAmount,
payoutRecipient,
address(0),
true,
new bytes(0)
);
}
/**
* Reduce the size of a position and withdraw a proportional amount of heldToken from the vault.
* Must be approved by both the position owner and lender.
*
* @param positionId Unique ID of the position
* @param requestedCloseAmount Principal amount of the position to close. The actual amount
* closed is also bounded by:
* 1) The principal of the position
* 2) The amount allowed by the owner if closer != owner
* 3) The amount allowed by the lender if closer != lender
* @return Values corresponding to:
* 1) Principal amount of position closed
* 2) Amount of heldToken received by the msg.sender
*/
function closeWithoutCounterparty(
bytes32 positionId,
uint256 requestedCloseAmount,
address payoutRecipient
)
external
closePositionStateControl
nonReentrant
returns (uint256, uint256)
{
return CloseWithoutCounterpartyImpl.closeWithoutCounterpartyImpl(
state,
positionId,
requestedCloseAmount,
payoutRecipient
);
}
/**
* Margin-call a position. Only callable with the approval of the position lender. After the
* call, the position owner will have time equal to the callTimeLimit of the position to close
* the position. If the owner does not close the position, the lender can recover the collateral
* in the position.
*
* @param positionId Unique ID of the position
* @param requiredDeposit Amount of deposit the position owner will have to put up to cancel
* the margin-call. Passing in 0 means the margin call cannot be
* canceled by depositing
*/
function marginCall(
bytes32 positionId,
uint256 requiredDeposit
)
external
nonReentrant
{
LoanImpl.marginCallImpl(
state,
positionId,
requiredDeposit
);
}
/**
* Cancel a margin-call. Only callable with the approval of the position lender.
*
* @param positionId Unique ID of the position
*/
function cancelMarginCall(
bytes32 positionId
)
external
onlyWhileOperational
nonReentrant
{
LoanImpl.cancelMarginCallImpl(state, positionId);
}
/**
* Used to recover the heldTokens held as collateral. Is callable after the maximum duration of
* the loan has expired or the loan has been margin-called for the duration of the callTimeLimit
* but remains unclosed. Only callable with the approval of the position lender.
*
* @param positionId Unique ID of the position
* @param recipient Address to send the recovered tokens to
* @return Amount of heldToken recovered
*/
function forceRecoverCollateral(
bytes32 positionId,
address recipient
)
external
nonReentrant
returns (uint256)
{
return ForceRecoverCollateralImpl.forceRecoverCollateralImpl(
state,
positionId,
recipient
);
}
/**
* Deposit additional heldToken as collateral for a position. Cancels margin-call if:
* 0 < position.requiredDeposit < depositAmount. Only callable by the position owner.
*
* @param positionId Unique ID of the position
* @param depositAmount Additional amount in heldToken to deposit
*/
function depositCollateral(
bytes32 positionId,
uint256 depositAmount
)
external
onlyWhileOperational
nonReentrant
{
DepositCollateralImpl.depositCollateralImpl(
state,
positionId,
depositAmount
);
}
/**
* Cancel an amount of a loan offering. Only callable by the loan offering's payer.
*
* @param addresses Array of addresses:
*
* [0] = owedToken
* [1] = heldToken
* [2] = loan payer
* [3] = loan owner
* [4] = loan taker
* [5] = loan position owner
* [6] = loan fee recipient
* [7] = loan lender fee token
* [8] = loan taker fee token
*
* @param values256 Values corresponding to:
*
* [0] = loan maximum amount
* [1] = loan minimum amount
* [2] = loan minimum heldToken
* [3] = loan lender fee
* [4] = loan taker fee
* [5] = loan expiration timestamp (in seconds)
* [6] = loan salt
*
* @param values32 Values corresponding to:
*
* [0] = loan call time limit (in seconds)
* [1] = loan maxDuration (in seconds)
* [2] = loan interest rate (annual nominal percentage times 10**6)
* [3] = loan interest update period (in seconds)
*
* @param cancelAmount Amount to cancel
* @return Amount that was canceled
*/
function cancelLoanOffering(
address[9] addresses,
uint256[7] values256,
uint32[4] values32,
uint256 cancelAmount
)
external
cancelLoanOfferingStateControl
nonReentrant
returns (uint256)
{
return LoanImpl.cancelLoanOfferingImpl(
state,
addresses,
values256,
values32,
cancelAmount
);
}
/**
* Transfer ownership of a loan to a new address. This new address will be entitled to all
* payouts for this loan. Only callable by the lender for a position. If "who" is a contract, it
* must implement the LoanOwner interface.
*
* @param positionId Unique ID of the position
* @param who New owner of the loan
*/
function transferLoan(
bytes32 positionId,
address who
)
external
nonReentrant
{
TransferImpl.transferLoanImpl(
state,
positionId,
who);
}
/**
* Transfer ownership of a position to a new address. This new address will be entitled to all
* payouts. Only callable by the owner of a position. If "who" is a contract, it must implement
* the PositionOwner interface.
*
* @param positionId Unique ID of the position
* @param who New owner of the position
*/
function transferPosition(
bytes32 positionId,
address who
)
external
nonReentrant
{
TransferImpl.transferPositionImpl(
state,
positionId,
who);
}
// ============ Public Constant Functions ============
/**
* Gets the address of the Vault contract that holds and accounts for tokens.
*
* @return The address of the Vault contract
*/
function getVaultAddress()
external
view
returns (address)
{
return state.VAULT;
}
/**
* Gets the address of the TokenProxy contract that accounts must set allowance on in order to
* make loans or open/close positions.
*
* @return The address of the TokenProxy contract
*/
function getTokenProxyAddress()
external
view
returns (address)
{
return state.TOKEN_PROXY;
}
}
// File: contracts/margin/interfaces/OnlyMargin.sol
/**
* @title OnlyMargin
* @author dYdX
*
* Contract to store the address of the main Margin contract and trust only that address to call
* certain functions.
*/
contract OnlyMargin {
// ============ Constants ============
// Address of the known and trusted Margin contract on the blockchain
address public DYDX_MARGIN;
// ============ Constructor ============
constructor(
address margin
)
public
{
DYDX_MARGIN = margin;
}
// ============ Modifiers ============
modifier onlyMargin()
{
require(
msg.sender == DYDX_MARGIN,
"OnlyMargin#onlyMargin: Only Margin can call"
);
_;
}
}
// File: contracts/margin/external/lib/LoanOfferingParser.sol
/**
* @title LoanOfferingParser
* @author dYdX
*
* Contract for LoanOfferingVerifiers to parse arguments
*/
contract LoanOfferingParser {
// ============ Parsing Functions ============
function parseLoanOffering(
address[9] addresses,
uint256[7] values256,
uint32[4] values32,
bytes signature
)
internal
pure
returns (MarginCommon.LoanOffering memory)
{
MarginCommon.LoanOffering memory loanOffering;
fillLoanOfferingAddresses(loanOffering, addresses);
fillLoanOfferingValues256(loanOffering, values256);
fillLoanOfferingValues32(loanOffering, values32);
loanOffering.signature = signature;
return loanOffering;
}
function fillLoanOfferingAddresses(
MarginCommon.LoanOffering memory loanOffering,
address[9] addresses
)
private
pure
{
loanOffering.owedToken = addresses[0];
loanOffering.heldToken = addresses[1];
loanOffering.payer = addresses[2];
loanOffering.owner = addresses[3];
loanOffering.taker = addresses[4];
loanOffering.positionOwner = addresses[5];
loanOffering.feeRecipient = addresses[6];
loanOffering.lenderFeeToken = addresses[7];
loanOffering.takerFeeToken = addresses[8];
}
function fillLoanOfferingValues256(
MarginCommon.LoanOffering memory loanOffering,
uint256[7] values256
)
private
pure
{
loanOffering.rates.maxAmount = values256[0];
loanOffering.rates.minAmount = values256[1];
loanOffering.rates.minHeldToken = values256[2];
loanOffering.rates.lenderFee = values256[3];
loanOffering.rates.takerFee = values256[4];
loanOffering.expirationTimestamp = values256[5];
loanOffering.salt = values256[6];
}
function fillLoanOfferingValues32(
MarginCommon.LoanOffering memory loanOffering,
uint32[4] values32
)
private
pure
{
loanOffering.callTimeLimit = values32[0];
loanOffering.maxDuration = values32[1];
loanOffering.rates.interestRate = values32[2];
loanOffering.rates.interestPeriod = values32[3];
}
}
// File: contracts/margin/external/lib/MarginHelper.sol
/**
* @title MarginHelper
* @author dYdX
*
* This library contains helper functions for interacting with Margin
*/
library MarginHelper {
function getPosition(
address DYDX_MARGIN,
bytes32 positionId
)
internal
view
returns (MarginCommon.Position memory)
{
(
address[4] memory addresses,
uint256[2] memory values256,
uint32[6] memory values32
) = Margin(DYDX_MARGIN).getPosition(positionId);
return MarginCommon.Position({
owedToken: addresses[0],
heldToken: addresses[1],
lender: addresses[2],
owner: addresses[3],
principal: values256[0],
requiredDeposit: values256[1],
callTimeLimit: values32[0],
startTimestamp: values32[1],
callTimestamp: values32[2],
maxDuration: values32[3],
interestRate: values32[4],
interestPeriod: values32[5]
});
}
}
// File: contracts/margin/external/BucketLender/BucketLender.sol
/**
* @title BucketLender
* @author dYdX
*
* On-chain shared lender that allows anyone to deposit tokens into this contract to be used to
* lend tokens for a particular margin position.
*
* - Each bucket has three variables:
* - Available Amount
* - The available amount of tokens that the bucket has to lend out
* - Outstanding Principal
* - The amount of principal that the bucket is responsible for in the margin position
* - Weight
* - Used to keep track of each account's weighted ownership within a bucket
* - Relative weight between buckets is meaningless
* - Only accounts' relative weight within a bucket matters
*
* - Token Deposits:
* - Go into a particular bucket, determined by time since the start of the position
* - If the position has not started: bucket = 0
* - If the position has started: bucket = ceiling(time_since_start / BUCKET_TIME)
* - This is always the highest bucket; no higher bucket yet exists
* - Increase the bucket's Available Amount
* - Increase the bucket's weight and the account's weight in that bucket
*
* - Token Withdrawals:
* - Can be from any bucket with available amount
* - Decrease the bucket's Available Amount
* - Decrease the bucket's weight and the account's weight in that bucket
*
* - Increasing the Position (Lending):
* - The lowest buckets with Available Amount are used first
* - Decreases Available Amount
* - Increases Outstanding Principal
*
* - Decreasing the Position (Being Paid-Back)
* - The highest buckets with Outstanding Principal are paid back first
* - Decreases Outstanding Principal
* - Increases Available Amount
*
*
* - Over time, this gives highest interest rates to earlier buckets, but disallows withdrawals from
* those buckets for a longer period of time.
* - Deposits in the same bucket earn the same interest rate.
* - Lenders can withdraw their funds at any time if they are not being lent (and are therefore not
* making the maximum interest).
* - The highest bucket with Outstanding Principal is always less-than-or-equal-to the lowest bucket
with Available Amount
*/
contract BucketLender is
Ownable,
OnlyMargin,
LoanOwner,
IncreaseLoanDelegator,
MarginCallDelegator,
CancelMarginCallDelegator,
ForceRecoverCollateralDelegator,
LoanOfferingParser,
LoanOfferingVerifier,
ReentrancyGuard
{
using SafeMath for uint256;
using TokenInteract for address;
// ============ Events ============
event Deposit(
address indexed beneficiary,
uint256 bucket,
uint256 amount,
uint256 weight
);
event Withdraw(
address indexed withdrawer,
uint256 bucket,
uint256 weight,
uint256 owedTokenWithdrawn,
uint256 heldTokenWithdrawn
);
event PrincipalIncreased(
uint256 principalTotal,
uint256 bucketNumber,
uint256 principalForBucket,
uint256 amount
);
event PrincipalDecreased(
uint256 principalTotal,
uint256 bucketNumber,
uint256 principalForBucket,
uint256 amount
);
event AvailableIncreased(
uint256 availableTotal,
uint256 bucketNumber,
uint256 availableForBucket,
uint256 amount
);
event AvailableDecreased(
uint256 availableTotal,
uint256 bucketNumber,
uint256 availableForBucket,
uint256 amount
);
// ============ State Variables ============
/**
* Available Amount is the amount of tokens that is available to be lent by each bucket.
* These tokens are also available to be withdrawn by the accounts that have weight in the
* bucket.
*/
// Available Amount for each bucket
mapping(uint256 => uint256) public availableForBucket;
// Total Available Amount
uint256 public availableTotal;
/**
* Outstanding Principal is the share of the margin position's principal that each bucket
* is responsible for. That is, each bucket with Outstanding Principal is owed
* (Outstanding Principal)*E^(RT) owedTokens in repayment.
*/
// Outstanding Principal for each bucket
mapping(uint256 => uint256) public principalForBucket;
// Total Outstanding Principal
uint256 public principalTotal;
/**
* Weight determines an account's proportional share of a bucket. Relative weights have no
* meaning if they are not for the same bucket. Likewise, the relative weight of two buckets has
* no meaning. However, the relative weight of two accounts within the same bucket is equal to
* the accounts' shares in the bucket and are therefore proportional to the payout that they
* should expect from withdrawing from that bucket.
*/
// Weight for each account in each bucket
mapping(uint256 => mapping(address => uint256)) public weightForBucketForAccount;
// Total Weight for each bucket
mapping(uint256 => uint256) public weightForBucket;
/**
* The critical bucket is:
* - Greater-than-or-equal-to The highest bucket with Outstanding Principal
* - Less-than-or-equal-to the lowest bucket with Available Amount
*
* It is equal to both of these values in most cases except in an edge cases where the two
* buckets are different. This value is cached to find such a bucket faster than looping through
* all possible buckets.
*/
uint256 public criticalBucket = 0;
/**
* Latest cached value for totalOwedTokenRepaidToLender.
* This number updates on the dYdX Margin base protocol whenever the position is
* partially-closed, but this contract is not notified at that time. Therefore, it is updated
* upon increasing the position or when depositing/withdrawing
*/
uint256 public cachedRepaidAmount = 0;
// True if the position was closed from force-recovering the collateral
bool public wasForceClosed = false;
// ============ Constants ============
// Unique ID of the position
bytes32 public POSITION_ID;
// Address of the token held in the position as collateral
address public HELD_TOKEN;
// Address of the token being lent
address public OWED_TOKEN;
// Time between new buckets
uint32 public BUCKET_TIME;
// Interest rate of the position
uint32 public INTEREST_RATE;
// Interest period of the position
uint32 public INTEREST_PERIOD;
// Maximum duration of the position
uint32 public MAX_DURATION;
// Margin-call time-limit of the position
uint32 public CALL_TIMELIMIT;
// (NUMERATOR/DENOMINATOR) denotes the minimum collateralization ratio of the position
uint32 public MIN_HELD_TOKEN_NUMERATOR;
uint32 public MIN_HELD_TOKEN_DENOMINATOR;
// Accounts that are permitted to margin-call positions (or cancel the margin call)
mapping(address => bool) public TRUSTED_MARGIN_CALLERS;
// Accounts that are permitted to withdraw on behalf of any address
mapping(address => bool) public TRUSTED_WITHDRAWERS;
// ============ Constructor ============
constructor(
address margin,
bytes32 positionId,
address heldToken,
address owedToken,
uint32[7] parameters,
address[] trustedMarginCallers,
address[] trustedWithdrawers
)
public
OnlyMargin(margin)
{
POSITION_ID = positionId;
HELD_TOKEN = heldToken;
OWED_TOKEN = owedToken;
require(
parameters[0] != 0,
"BucketLender#constructor: BUCKET_TIME cannot be zero"
);
BUCKET_TIME = parameters[0];
INTEREST_RATE = parameters[1];
INTEREST_PERIOD = parameters[2];
MAX_DURATION = parameters[3];
CALL_TIMELIMIT = parameters[4];
MIN_HELD_TOKEN_NUMERATOR = parameters[5];
MIN_HELD_TOKEN_DENOMINATOR = parameters[6];
// Initialize TRUSTED_MARGIN_CALLERS and TRUSTED_WITHDRAWERS
uint256 i = 0;
for (i = 0; i < trustedMarginCallers.length; i++) {
TRUSTED_MARGIN_CALLERS[trustedMarginCallers[i]] = true;
}
for (i = 0; i < trustedWithdrawers.length; i++) {
TRUSTED_WITHDRAWERS[trustedWithdrawers[i]] = true;
}
// Set maximum allowance on proxy
OWED_TOKEN.approve(
Margin(margin).getTokenProxyAddress(),
MathHelpers.maxUint256()
);
}
// ============ Modifiers ============
modifier onlyPosition(bytes32 positionId) {
require(
POSITION_ID == positionId,
"BucketLender#onlyPosition: Incorrect position"
);
_;
}
// ============ Margin-Only State-Changing Functions ============
/**
* Function a smart contract must implement to be able to consent to a loan. The loan offering
* will be generated off-chain. The "loan owner" address will own the loan-side of the resulting
* position.
*
* @param addresses Loan offering addresses
* @param values256 Loan offering uint256s
* @param values32 Loan offering uint32s
* @param positionId Unique ID of the position
* @param signature Arbitrary bytes
* @return This address to accept, a different address to ask that contract
*/
function verifyLoanOffering(
address[9] addresses,
uint256[7] values256,
uint32[4] values32,
bytes32 positionId,
bytes signature
)
external
onlyMargin
nonReentrant
onlyPosition(positionId)
returns (address)
{
require(
Margin(DYDX_MARGIN).containsPosition(POSITION_ID),
"BucketLender#verifyLoanOffering: This contract should not open a new position"
);
MarginCommon.LoanOffering memory loanOffering = parseLoanOffering(
addresses,
values256,
values32,
signature
);
// CHECK ADDRESSES
assert(loanOffering.owedToken == OWED_TOKEN);
assert(loanOffering.heldToken == HELD_TOKEN);
assert(loanOffering.payer == address(this));
assert(loanOffering.owner == address(this));
require(
loanOffering.taker == address(0),
"BucketLender#verifyLoanOffering: loanOffering.taker is non-zero"
);
require(
loanOffering.feeRecipient == address(0),
"BucketLender#verifyLoanOffering: loanOffering.feeRecipient is non-zero"
);
require(
loanOffering.positionOwner == address(0),
"BucketLender#verifyLoanOffering: loanOffering.positionOwner is non-zero"
);
require(
loanOffering.lenderFeeToken == address(0),
"BucketLender#verifyLoanOffering: loanOffering.lenderFeeToken is non-zero"
);
require(
loanOffering.takerFeeToken == address(0),
"BucketLender#verifyLoanOffering: loanOffering.takerFeeToken is non-zero"
);
// CHECK VALUES256
require(
loanOffering.rates.maxAmount == MathHelpers.maxUint256(),
"BucketLender#verifyLoanOffering: loanOffering.maxAmount is incorrect"
);
require(
loanOffering.rates.minAmount == 0,
"BucketLender#verifyLoanOffering: loanOffering.minAmount is non-zero"
);
require(
loanOffering.rates.minHeldToken == 0,
"BucketLender#verifyLoanOffering: loanOffering.minHeldToken is non-zero"
);
require(
loanOffering.rates.lenderFee == 0,
"BucketLender#verifyLoanOffering: loanOffering.lenderFee is non-zero"
);
require(
loanOffering.rates.takerFee == 0,
"BucketLender#verifyLoanOffering: loanOffering.takerFee is non-zero"
);
require(
loanOffering.expirationTimestamp == MathHelpers.maxUint256(),
"BucketLender#verifyLoanOffering: expirationTimestamp is incorrect"
);
require(
loanOffering.salt == 0,
"BucketLender#verifyLoanOffering: loanOffering.salt is non-zero"
);
// CHECK VALUES32
require(
loanOffering.callTimeLimit == MathHelpers.maxUint32(),
"BucketLender#verifyLoanOffering: loanOffering.callTimelimit is incorrect"
);
require(
loanOffering.maxDuration == MathHelpers.maxUint32(),
"BucketLender#verifyLoanOffering: loanOffering.maxDuration is incorrect"
);
assert(loanOffering.rates.interestRate == INTEREST_RATE);
assert(loanOffering.rates.interestPeriod == INTEREST_PERIOD);
// no need to require anything about loanOffering.signature
return address(this);
}
/**
* Called by the Margin contract when anyone transfers ownership of a loan to this contract.
* This function initializes this contract and returns this address to indicate to Margin
* that it is willing to take ownership of the loan.
*
* @param from Address of the previous owner
* @param positionId Unique ID of the position
* @return This address on success, throw otherwise
*/
function receiveLoanOwnership(
address from,
bytes32 positionId
)
external
onlyMargin
nonReentrant
onlyPosition(positionId)
returns (address)
{
MarginCommon.Position memory position = MarginHelper.getPosition(DYDX_MARGIN, POSITION_ID);
uint256 initialPrincipal = position.principal;
uint256 minHeldToken = MathHelpers.getPartialAmount(
uint256(MIN_HELD_TOKEN_NUMERATOR),
uint256(MIN_HELD_TOKEN_DENOMINATOR),
initialPrincipal
);
assert(initialPrincipal > 0);
assert(principalTotal == 0);
assert(from != address(this)); // position must be opened without lending from this position
require(
position.owedToken == OWED_TOKEN,
"BucketLender#receiveLoanOwnership: Position owedToken mismatch"
);
require(
position.heldToken == HELD_TOKEN,
"BucketLender#receiveLoanOwnership: Position heldToken mismatch"
);
require(
position.maxDuration == MAX_DURATION,
"BucketLender#receiveLoanOwnership: Position maxDuration mismatch"
);
require(
position.callTimeLimit == CALL_TIMELIMIT,
"BucketLender#receiveLoanOwnership: Position callTimeLimit mismatch"
);
require(
position.interestRate == INTEREST_RATE,
"BucketLender#receiveLoanOwnership: Position interestRate mismatch"
);
require(
position.interestPeriod == INTEREST_PERIOD,
"BucketLender#receiveLoanOwnership: Position interestPeriod mismatch"
);
require(
Margin(DYDX_MARGIN).getPositionBalance(POSITION_ID) >= minHeldToken,
"BucketLender#receiveLoanOwnership: Not enough heldToken as collateral"
);
// set relevant constants
principalForBucket[0] = initialPrincipal;
principalTotal = initialPrincipal;
weightForBucket[0] = weightForBucket[0].add(initialPrincipal);
weightForBucketForAccount[0][from] =
weightForBucketForAccount[0][from].add(initialPrincipal);
return address(this);
}
/**
* Called by Margin when additional value is added onto the position this contract
* is lending for. Balance is added to the address that loaned the additional tokens.
*
* @param payer Address that loaned the additional tokens
* @param positionId Unique ID of the position
* @param principalAdded Amount that was added to the position
* @param lentAmount Amount of owedToken lent
* @return This address to accept, a different address to ask that contract
*/
function increaseLoanOnBehalfOf(
address payer,
bytes32 positionId,
uint256 principalAdded,
uint256 lentAmount
)
external
onlyMargin
nonReentrant
onlyPosition(positionId)
returns (address)
{
Margin margin = Margin(DYDX_MARGIN);
require(
payer == address(this),
"BucketLender#increaseLoanOnBehalfOf: Other lenders cannot lend for this position"
);
require(
!margin.isPositionCalled(POSITION_ID),
"BucketLender#increaseLoanOnBehalfOf: No lending while the position is margin-called"
);
// This function is only called after the state has been updated in the base protocol;
// thus, the principal in the base protocol will equal the principal after the increase
uint256 principalAfterIncrease = margin.getPositionPrincipal(POSITION_ID);
uint256 principalBeforeIncrease = principalAfterIncrease.sub(principalAdded);
// principalTotal was the principal after the previous increase
accountForClose(principalTotal.sub(principalBeforeIncrease));
accountForIncrease(principalAdded, lentAmount);
assert(principalTotal == principalAfterIncrease);
return address(this);
}
/**
* Function a contract must implement in order to let other addresses call marginCall().
*
* @param caller Address of the caller of the marginCall function
* @param positionId Unique ID of the position
* @param depositAmount Amount of heldToken deposit that will be required to cancel the call
* @return This address to accept, a different address to ask that contract
*/
function marginCallOnBehalfOf(
address caller,
bytes32 positionId,
uint256 depositAmount
)
external
onlyMargin
nonReentrant
onlyPosition(positionId)
returns (address)
{
require(
TRUSTED_MARGIN_CALLERS[caller],
"BucketLender#marginCallOnBehalfOf: Margin-caller must be trusted"
);
require(
depositAmount == 0, // prevents depositing from canceling the margin-call
"BucketLender#marginCallOnBehalfOf: Deposit amount must be zero"
);
return address(this);
}
/**
* Function a contract must implement in order to let other addresses call cancelMarginCall().
*
* @param canceler Address of the caller of the cancelMarginCall function
* @param positionId Unique ID of the position
* @return This address to accept, a different address to ask that contract
*/
function cancelMarginCallOnBehalfOf(
address canceler,
bytes32 positionId
)
external
onlyMargin
nonReentrant
onlyPosition(positionId)
returns (address)
{
require(
TRUSTED_MARGIN_CALLERS[canceler],
"BucketLender#cancelMarginCallOnBehalfOf: Margin-call-canceler must be trusted"
);
return address(this);
}
/**
* Function a contract must implement in order to let other addresses call
* forceRecoverCollateral().
*
* param recoverer Address of the caller of the forceRecoverCollateral() function
* @param positionId Unique ID of the position
* @param recipient Address to send the recovered tokens to
* @return This address to accept, a different address to ask that contract
*/
function forceRecoverCollateralOnBehalfOf(
address /* recoverer */,
bytes32 positionId,
address recipient
)
external
onlyMargin
nonReentrant
onlyPosition(positionId)
returns (address)
{
return forceRecoverCollateralInternal(recipient);
}
// ============ Public State-Changing Functions ============
/**
* Allow anyone to recalculate the Outstanding Principal and Available Amount for the buckets if
* part of the position has been closed since the last position increase.
*/
function rebalanceBuckets()
external
nonReentrant
{
rebalanceBucketsInternal();
}
/**
* Allows users to deposit owedToken into this contract. Allowance must be set on this contract
* for "token" in at least the amount "amount".
*
* @param beneficiary The account that will be entitled to this depoit
* @param amount The amount of owedToken to deposit
* @return The bucket number that was deposited into
*/
function deposit(
address beneficiary,
uint256 amount
)
external
nonReentrant
returns (uint256)
{
Margin margin = Margin(DYDX_MARGIN);
bytes32 positionId = POSITION_ID;
require(
beneficiary != address(0),
"BucketLender#deposit: Beneficiary cannot be the zero address"
);
require(
amount != 0,
"BucketLender#deposit: Cannot deposit zero tokens"
);
require(
!margin.isPositionClosed(positionId),
"BucketLender#deposit: Cannot deposit after the position is closed"
);
require(
!margin.isPositionCalled(positionId),
"BucketLender#deposit: Cannot deposit while the position is margin-called"
);
rebalanceBucketsInternal();
OWED_TOKEN.transferFrom(
msg.sender,
address(this),
amount
);
uint256 bucket = getCurrentBucket();
uint256 effectiveAmount = availableForBucket[bucket].add(getBucketOwedAmount(bucket));
uint256 weightToAdd = 0;
if (effectiveAmount == 0) {
weightToAdd = amount; // first deposit in bucket
} else {
weightToAdd = MathHelpers.getPartialAmount(
amount,
effectiveAmount,
weightForBucket[bucket]
);
}
require(
weightToAdd != 0,
"BucketLender#deposit: Cannot deposit for zero weight"
);
// update state
updateAvailable(bucket, amount, true);
weightForBucketForAccount[bucket][beneficiary] =
weightForBucketForAccount[bucket][beneficiary].add(weightToAdd);
weightForBucket[bucket] = weightForBucket[bucket].add(weightToAdd);
emit Deposit(
beneficiary,
bucket,
amount,
weightToAdd
);
return bucket;
}
/**
* Allows users to withdraw their lent funds. An account can withdraw its weighted share of the
* bucket.
*
* While the position is open, a bucket's share is equal to:
* Owed Token: (Available Amount) + (Outstanding Principal) * (1 + interest)
* Held Token: 0
*
* After the position is closed, a bucket's share is equal to:
* Owed Token: (Available Amount)
* Held Token: (Held Token Balance) * (Outstanding Principal) / (Total Outstanding Principal)
*
* @param buckets The bucket numbers to withdraw from
* @param maxWeights The maximum weight to withdraw from each bucket. The amount of tokens
* withdrawn will be at least this amount, but not necessarily more.
* Withdrawing the same weight from different buckets does not necessarily
* return the same amounts from those buckets. In order to withdraw as many
* tokens as possible, use the maximum uint256.
* @param onBehalfOf The address to withdraw on behalf of
* @return 1) The number of owedTokens withdrawn
* 2) The number of heldTokens withdrawn
*/
function withdraw(
uint256[] buckets,
uint256[] maxWeights,
address onBehalfOf
)
external
nonReentrant
returns (uint256, uint256)
{
require(
buckets.length == maxWeights.length,
"BucketLender#withdraw: The lengths of the input arrays must match"
);
if (onBehalfOf != msg.sender) {
require(
TRUSTED_WITHDRAWERS[msg.sender],
"BucketLender#withdraw: Only trusted withdrawers can withdraw on behalf of others"
);
}
rebalanceBucketsInternal();
// decide if some bucket is unable to be withdrawn from (is locked)
// the zero value represents no-lock
uint256 lockedBucket = 0;
if (
Margin(DYDX_MARGIN).containsPosition(POSITION_ID) &&
criticalBucket == getCurrentBucket()
) {
lockedBucket = criticalBucket;
}
uint256[2] memory results; // [0] = totalOwedToken, [1] = totalHeldToken
uint256 maxHeldToken = 0;
if (wasForceClosed) {
maxHeldToken = HELD_TOKEN.balanceOf(address(this));
}
for (uint256 i = 0; i < buckets.length; i++) {
uint256 bucket = buckets[i];
// prevent withdrawing from the current bucket if it is also the critical bucket
if ((bucket != 0) && (bucket == lockedBucket)) {
continue;
}
(uint256 owedTokenForBucket, uint256 heldTokenForBucket) = withdrawSingleBucket(
onBehalfOf,
bucket,
maxWeights[i],
maxHeldToken
);
results[0] = results[0].add(owedTokenForBucket);
results[1] = results[1].add(heldTokenForBucket);
}
// Transfer share of owedToken
OWED_TOKEN.transfer(msg.sender, results[0]);
HELD_TOKEN.transfer(msg.sender, results[1]);
return (results[0], results[1]);
}
/**
* Allows the owner to withdraw any excess tokens sent to the vault by unconventional means,
* including (but not limited-to) token airdrops. Any tokens moved to this contract by calling
* deposit() will be accounted for and will not be withdrawable by this function.
*
* @param token ERC20 token address
* @param to Address to transfer tokens to
* @return Amount of tokens withdrawn
*/
function withdrawExcessToken(
address token,
address to
)
external
onlyOwner
returns (uint256)
{
rebalanceBucketsInternal();
uint256 amount = token.balanceOf(address(this));
if (token == OWED_TOKEN) {
amount = amount.sub(availableTotal);
} else if (token == HELD_TOKEN) {
require(
!wasForceClosed,
"BucketLender#withdrawExcessToken: heldToken cannot be withdrawn if force-closed"
);
}
token.transfer(to, amount);
return amount;
}
// ============ Public Getter Functions ============
/**
* Get the current bucket number that funds will be deposited into. This is also the highest
* bucket so far.
*
* @return The highest bucket and the one that funds will be deposited into
*/
function getCurrentBucket()
public
view
returns (uint256)
{
// load variables from storage;
Margin margin = Margin(DYDX_MARGIN);
bytes32 positionId = POSITION_ID;
uint32 bucketTime = BUCKET_TIME;
assert(!margin.isPositionClosed(positionId));
// if position not created, allow deposits in the first bucket
if (!margin.containsPosition(positionId)) {
return 0;
}
// return the number of BUCKET_TIME periods elapsed since the position start, rounded-up
uint256 startTimestamp = margin.getPositionStartTimestamp(positionId);
return block.timestamp.sub(startTimestamp).div(bucketTime).add(1);
}
/**
* Gets the outstanding amount of owedToken owed to a bucket. This is the principal amount of
* the bucket multiplied by the interest accrued in the position. If the position is closed,
* then any outstanding principal will never be repaid in the form of owedToken.
*
* @param bucket The bucket number
* @return The amount of owedToken that this bucket expects to be paid-back if the posi
*/
function getBucketOwedAmount(
uint256 bucket
)
public
view
returns (uint256)
{
// if the position is completely closed, then the outstanding principal will never be repaid
if (Margin(DYDX_MARGIN).isPositionClosed(POSITION_ID)) {
return 0;
}
uint256 lentPrincipal = principalForBucket[bucket];
// the bucket has no outstanding principal
if (lentPrincipal == 0) {
return 0;
}
// get the total amount of owedToken that would be paid back at this time
uint256 owedAmount = Margin(DYDX_MARGIN).getPositionOwedAmountAtTime(
POSITION_ID,
principalTotal,
uint32(block.timestamp)
);
// return the bucket's share
return MathHelpers.getPartialAmount(
lentPrincipal,
principalTotal,
owedAmount
);
}
// ============ Internal Functions ============
function forceRecoverCollateralInternal(
address recipient
)
internal
returns (address)
{
require(
recipient == address(this),
"BucketLender#forceRecoverCollateralOnBehalfOf: Recipient must be this contract"
);
rebalanceBucketsInternal();
wasForceClosed = true;
return address(this);
}
// ============ Private Helper Functions ============
/**
* Recalculates the Outstanding Principal and Available Amount for the buckets. Only changes the
* state if part of the position has been closed since the last position increase.
*/
function rebalanceBucketsInternal()
private
{
// if force-closed, don't update the outstanding principal values; they are needed to repay
// lenders with heldToken
if (wasForceClosed) {
return;
}
uint256 marginPrincipal = Margin(DYDX_MARGIN).getPositionPrincipal(POSITION_ID);
accountForClose(principalTotal.sub(marginPrincipal));
assert(principalTotal == marginPrincipal);
}
/**
* Updates the state variables at any time. Only does anything after the position has been
* closed or partially-closed since the last time this function was called.
*
* - Increases the available amount in the highest buckets with outstanding principal
* - Decreases the principal amount in those buckets
*
* @param principalRemoved Amount of principal closed since the last update
*/
function accountForClose(
uint256 principalRemoved
)
private
{
if (principalRemoved == 0) {
return;
}
uint256 newRepaidAmount = Margin(DYDX_MARGIN).getTotalOwedTokenRepaidToLender(POSITION_ID);
assert(newRepaidAmount.sub(cachedRepaidAmount) >= principalRemoved);
uint256 principalToSub = principalRemoved;
uint256 availableToAdd = newRepaidAmount.sub(cachedRepaidAmount);
uint256 criticalBucketTemp = criticalBucket;
// loop over buckets in reverse order starting with the critical bucket
for (
uint256 bucket = criticalBucketTemp;
principalToSub > 0;
bucket--
) {
assert(bucket <= criticalBucketTemp); // no underflow on bucket
uint256 principalTemp = Math.min256(principalToSub, principalForBucket[bucket]);
if (principalTemp == 0) {
continue;
}
uint256 availableTemp = MathHelpers.getPartialAmount(
principalTemp,
principalToSub,
availableToAdd
);
updateAvailable(bucket, availableTemp, true);
updatePrincipal(bucket, principalTemp, false);
principalToSub = principalToSub.sub(principalTemp);
availableToAdd = availableToAdd.sub(availableTemp);
criticalBucketTemp = bucket;
}
assert(principalToSub == 0);
assert(availableToAdd == 0);
setCriticalBucket(criticalBucketTemp);
cachedRepaidAmount = newRepaidAmount;
}
/**
* Updates the state variables when a position is increased.
*
* - Decreases the available amount in the lowest buckets with available token
* - Increases the principal amount in those buckets
*
* @param principalAdded Amount of principal added to the position
* @param lentAmount Amount of owedToken lent
*/
function accountForIncrease(
uint256 principalAdded,
uint256 lentAmount
)
private
{
require(
lentAmount <= availableTotal,
"BucketLender#accountForIncrease: No lending not-accounted-for funds"
);
uint256 principalToAdd = principalAdded;
uint256 availableToSub = lentAmount;
uint256 criticalBucketTemp;
// loop over buckets in order starting from the critical bucket
uint256 lastBucket = getCurrentBucket();
for (
uint256 bucket = criticalBucket;
principalToAdd > 0;
bucket++
) {
assert(bucket <= lastBucket); // should never go past the last bucket
uint256 availableTemp = Math.min256(availableToSub, availableForBucket[bucket]);
if (availableTemp == 0) {
continue;
}
uint256 principalTemp = MathHelpers.getPartialAmount(
availableTemp,
availableToSub,
principalToAdd
);
updateAvailable(bucket, availableTemp, false);
updatePrincipal(bucket, principalTemp, true);
principalToAdd = principalToAdd.sub(principalTemp);
availableToSub = availableToSub.sub(availableTemp);
criticalBucketTemp = bucket;
}
assert(principalToAdd == 0);
assert(availableToSub == 0);
setCriticalBucket(criticalBucketTemp);
}
/**
* Withdraw
*
* @param onBehalfOf The account for which to withdraw for
* @param bucket The bucket number to withdraw from
* @param maxWeight The maximum weight to withdraw
* @param maxHeldToken The total amount of heldToken that has been force-recovered
* @return 1) The number of owedTokens withdrawn
* 2) The number of heldTokens withdrawn
*/
function withdrawSingleBucket(
address onBehalfOf,
uint256 bucket,
uint256 maxWeight,
uint256 maxHeldToken
)
private
returns (uint256, uint256)
{
// calculate the user's share
uint256 bucketWeight = weightForBucket[bucket];
if (bucketWeight == 0) {
return (0, 0);
}
uint256 userWeight = weightForBucketForAccount[bucket][onBehalfOf];
uint256 weightToWithdraw = Math.min256(maxWeight, userWeight);
if (weightToWithdraw == 0) {
return (0, 0);
}
// update state
weightForBucket[bucket] = weightForBucket[bucket].sub(weightToWithdraw);
weightForBucketForAccount[bucket][onBehalfOf] = userWeight.sub(weightToWithdraw);
// calculate for owedToken
uint256 owedTokenToWithdraw = withdrawOwedToken(
bucket,
weightToWithdraw,
bucketWeight
);
// calculate for heldToken
uint256 heldTokenToWithdraw = withdrawHeldToken(
bucket,
weightToWithdraw,
bucketWeight,
maxHeldToken
);
emit Withdraw(
onBehalfOf,
bucket,
weightToWithdraw,
owedTokenToWithdraw,
heldTokenToWithdraw
);
return (owedTokenToWithdraw, heldTokenToWithdraw);
}
/**
* Helper function to withdraw earned owedToken from this contract.
*
* @param bucket The bucket number to withdraw from
* @param userWeight The amount of weight the user is using to withdraw
* @param bucketWeight The total weight of the bucket
* @return The amount of owedToken being withdrawn
*/
function withdrawOwedToken(
uint256 bucket,
uint256 userWeight,
uint256 bucketWeight
)
private
returns (uint256)
{
// amount to return for the bucket
uint256 owedTokenToWithdraw = MathHelpers.getPartialAmount(
userWeight,
bucketWeight,
availableForBucket[bucket].add(getBucketOwedAmount(bucket))
);
// check that there is enough token to give back
require(
owedTokenToWithdraw <= availableForBucket[bucket],
"BucketLender#withdrawOwedToken: There must be enough available owedToken"
);
// update amounts
updateAvailable(bucket, owedTokenToWithdraw, false);
return owedTokenToWithdraw;
}
/**
* Helper function to withdraw heldToken from this contract.
*
* @param bucket The bucket number to withdraw from
* @param userWeight The amount of weight the user is using to withdraw
* @param bucketWeight The total weight of the bucket
* @param maxHeldToken The total amount of heldToken available to withdraw
* @return The amount of heldToken being withdrawn
*/
function withdrawHeldToken(
uint256 bucket,
uint256 userWeight,
uint256 bucketWeight,
uint256 maxHeldToken
)
private
returns (uint256)
{
if (maxHeldToken == 0) {
return 0;
}
// user's principal for the bucket
uint256 principalForBucketForAccount = MathHelpers.getPartialAmount(
userWeight,
bucketWeight,
principalForBucket[bucket]
);
uint256 heldTokenToWithdraw = MathHelpers.getPartialAmount(
principalForBucketForAccount,
principalTotal,
maxHeldToken
);
updatePrincipal(bucket, principalForBucketForAccount, false);
return heldTokenToWithdraw;
}
// ============ Setter Functions ============
/**
* Changes the critical bucket variable
*
* @param bucket The value to set criticalBucket to
*/
function setCriticalBucket(
uint256 bucket
)
private
{
// don't spend the gas to sstore unless we need to change the value
if (criticalBucket == bucket) {
return;
}
criticalBucket = bucket;
}
/**
* Changes the available owedToken amount. This changes both the variable to track the total
* amount as well as the variable to track a particular bucket.
*
* @param bucket The bucket number
* @param amount The amount to change the available amount by
* @param increase True if positive change, false if negative change
*/
function updateAvailable(
uint256 bucket,
uint256 amount,
bool increase
)
private
{
if (amount == 0) {
return;
}
uint256 newTotal;
uint256 newForBucket;
if (increase) {
newTotal = availableTotal.add(amount);
newForBucket = availableForBucket[bucket].add(amount);
emit AvailableIncreased(newTotal, bucket, newForBucket, amount); // solium-disable-line
} else {
newTotal = availableTotal.sub(amount);
newForBucket = availableForBucket[bucket].sub(amount);
emit AvailableDecreased(newTotal, bucket, newForBucket, amount); // solium-disable-line
}
availableTotal = newTotal;
availableForBucket[bucket] = newForBucket;
}
/**
* Changes the principal amount. This changes both the variable to track the total
* amount as well as the variable to track a particular bucket.
*
* @param bucket The bucket number
* @param amount The amount to change the principal amount by
* @param increase True if positive change, false if negative change
*/
function updatePrincipal(
uint256 bucket,
uint256 amount,
bool increase
)
private
{
if (amount == 0) {
return;
}
uint256 newTotal;
uint256 newForBucket;
if (increase) {
newTotal = principalTotal.add(amount);
newForBucket = principalForBucket[bucket].add(amount);
emit PrincipalIncreased(newTotal, bucket, newForBucket, amount); // solium-disable-line
} else {
newTotal = principalTotal.sub(amount);
newForBucket = principalForBucket[bucket].sub(amount);
emit PrincipalDecreased(newTotal, bucket, newForBucket, amount); // solium-disable-line
}
principalTotal = newTotal;
principalForBucket[bucket] = newForBucket;
}
}
// File: contracts/margin/external/BucketLender/BucketLenderFactory.sol
/**
* @title BucketLenderFactory
* @author dYdX
*
* Contract that allows anyone to deploy a BucketLender contract by sending a transaction.
*/
contract BucketLenderFactory {
// ============ Events ============
event BucketLenderCreated(
address indexed creator,
address indexed owner,
bytes32 indexed positionId,
address at
);
// ============ State Variables ============
// Address of the Margin contract for the dYdX Margin Trading Protocol
address public DYDX_MARGIN;
// ============ Constructor ============
constructor(
address margin
)
public
{
DYDX_MARGIN = margin;
}
// ============ Public Functions ============
/**
* Deploy a new BucketLender contract to the blockchain
*
* @param positionId Unique ID of the position
* @param owner Address to which ownership of the BucketLender will be transferred
* @param heldToken Address of the token held in the position as collateral
* @param owedToken Address of the token being lent by the BucketLender
* @param parameters Values corresponding to:
*
* [0] = number of seconds per bucket
* [1] = interest rate
* [2] = interest period
* [3] = maximum loan duration
* [4] = margin-call timelimit
* [5] = numerator of minimum heldToken-per-owedToken
* [6] = denominator of minimum heldToken-per-owedToken
*
* @param marginCallers Accounts that are permitted to margin-call positions (or cancel the margin call)
* @return The address of the new BucketLender contract
*/
function createBucketLender(
bytes32 positionId,
address owner,
address heldToken,
address owedToken,
uint32[7] parameters,
address[] marginCallers,
address[] withdrawers
)
external
returns (address)
{
address newBucketLender = new BucketLender(
DYDX_MARGIN,
positionId,
heldToken,
owedToken,
parameters,
marginCallers,
withdrawers
);
BucketLender(newBucketLender).transferOwnership(owner);
emit BucketLenderCreated(
msg.sender,
owner,
positionId,
newBucketLender
);
return newBucketLender;
}
}
|
Calculates partial value given a numerator and denominator, rounded up. numerator Numerator denominator Denominator target Value to calculate partial of return Rounded-up result of target numerator / denominator/
|
function getPartialAmountRoundedUp(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256)
{
return divisionRoundedUp(numerator.mul(target), denominator);
}
| 1,593,881
|
./full_match/4/0xeF26b9eE7A6e380Fc8940197F94d1cffC52DBd29/sources/contracts/WrappedPunk.sol
|
Check for the case where there is a bid from the new owner and refund it. Any other bid can stay in place. Kill bid and refund value
|
function safeTransferFrom(address from, address to, uint punkIndex) public override {
super.safeTransferFrom(from, to, uint256(punkIndex), "");
Bid memory bid = punkBids[punkIndex];
if (bid.bidder == to) {
pendingWithdrawals[to] += bid.value;
punkBids[punkIndex] = Bid(false, punkIndex, address(0x0), 0);
}
}
| 12,470,333
|
./full_match/84531/0xd7149865d07cCfdfB10f858AFAb297A8251882Cc/sources/contracts/stores/OrderStore.sol
|
Disable processing new orders Only callable by governance
|
function setIsProcessingPaused(bool b) external onlyGov {
isProcessingPaused = b;
}
| 11,525,610
|
/**
*Submitted for verification at BscScan.com on 2021-08-24
*/
// 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;
}
}
/**
* @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);
}
}
/**
* @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());
}
}
/**
* @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;
}
}
/**
* @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);
}
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;
}
}
/**
* @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);
}
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
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
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");
}
}
}
interface IZaiReferral {
/**
* @dev Record referral.
*/
function recordReferral(address user, address referrer) external;
/**
* @dev Record referral commission.
*/
function recordReferralCommission(address referrer, uint256 commission) external;
/**
* @dev Get the referrer address that referred the user.
*/
function getReferrer(address user) external view returns (address);
}
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
);
}
pragma abicoder v2;
/**
* @title Zai Option - forked from PancakePredictionV2
*/
contract zaiOption is Ownable, Pausable, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
AggregatorV3Interface public oracle;
bool public genesisLockOnce = false;
bool public genesisStartOnce = false;
address public adminAddress; // address of the admin
address public operatorAddress; // address of the operator
uint256 public bufferSeconds; // number of seconds for valid execution of a prediction round
uint256 public intervalSeconds; // interval in seconds between two prediction rounds
uint256 public minBetAmount; // minimum betting amount (denominated in wei)
uint256 public treasuryFee; // treasury rate (e.g. 200 = 2%, 150 = 1.50%)
uint256 public treasuryAmount; // treasury amount that was not claimed
// Operational Addresses
// address public treasuryAddress = 0xBe511eF95e14E0524aA86187B233cffDBA87aB98;
address public devAddress = 0x8bC8B45626b43d5F63D79D6002B1bA730B70F88a;
address public staffAddress = 0x0926345c8Eb1206461F49cCF213ca52B46e34429;
// address public buybackAddress = 0x5bA4b2E88ea7303aa25c0798B28e107d129A2A2a;
address public Maintenance = 0xa7F749B90BDbDe8d2C0EC61a952914C88D863027;
uint256 public currentEpoch; // current epoch for prediction round
uint256 public oracleLatestRoundId; // converted from uint80 (Chainlink)
uint256 public oracleUpdateAllowance; // seconds
uint256 public constant MAX_TREASURY_FEE = 1000; // 10%
uint256 public passedBlocks = 200480; // 1 week of blocks
uint256 public jackpotLock = 0; // blockNumber for counting
// ZAIF FEE Calculation
uint16 public constant TaxFee = 500;
// 2% for referral payments
uint16 public constant refFee = 200;
// Zai referral contract address.
IZaiReferral public zaiReferral;
// Referral commission rate in basis points.
uint16 public referralCommissionRate = 200;
//jackpot Acumulation Amount
uint256 public jackpotAcmAmt;
uint256 public jackpotAcmSafeCheck;
mapping(uint256 => mapping(address => BetInfo)) public ledger;
mapping(uint256 => Round) public rounds;
mapping(uint256 => RoundJackpotInfo) public roundsInfo;
mapping(address => uint256[]) public userRounds;
enum Position {
Bull,
Bear
}
struct Round {
uint256 epoch;
uint256 startTimestamp;
uint256 lockTimestamp;
uint256 closeTimestamp;
int256 lockPrice;
int256 closePrice;
uint256 lockOracleId;
uint256 closeOracleId;
uint256 totalAmount;
uint256 bullAmount;
uint256 bearAmount;
uint256 rewardBaseCalAmount;
uint256 rewardAmount;
bool oracleCalled;
}
struct RoundJackpotInfo {
uint256 epoch;
bool jackpotRound;
bool jackpotClaimed;
}
struct BetInfo {
Position position;
uint256 amount;
bool claimed; // default false
}
event BetBear(address indexed sender, uint256 indexed epoch, uint256 amount);
event BetBull(address indexed sender, uint256 indexed epoch, uint256 amount);
event Claim(address indexed sender, uint256 indexed epoch, uint256 amount);
event EndRound(uint256 indexed epoch, uint256 indexed roundId, int256 price);
event LockRound(uint256 indexed epoch, uint256 indexed roundId, int256 price);
event ReferralCommissionPaid(address indexed user, address indexed referrer, uint256 commissionAmount);
event NewAdminAddress(address admin);
event NewBufferAndIntervalSeconds(uint256 bufferSeconds, uint256 intervalSeconds);
event NewMinBetAmount(uint256 indexed epoch, uint256 minBetAmount);
event NewTreasuryFee(uint256 indexed epoch, uint256 treasuryFee);
event NewOperatorAddress(address operator);
event NewOracle(address oracle);
event NewOracleUpdateAllowance(uint256 oracleUpdateAllowance);
event Pause(uint256 indexed epoch);
event RewardsCalculated(
uint256 indexed epoch,
uint256 rewardBaseCalAmount,
uint256 rewardAmount,
uint256 treasuryAmount
);
event StartRound(uint256 indexed epoch);
event TokenRecovery(address indexed token, uint256 amount);
event TreasuryClaim(uint256 amount);
event Unpause(uint256 indexed epoch);
IERC20 public zaif;
modifier onlyAdmin() {
require(msg.sender == adminAddress, "Not admin");
_;
}
modifier onlyAdminOrOperator() {
require(msg.sender == adminAddress || msg.sender == operatorAddress, "Not operator/admin");
_;
}
modifier onlyOperator() {
require(msg.sender == operatorAddress, "Not operator");
_;
}
modifier notContract() {
require(!_isContract(msg.sender), "Contract not allowed");
require(msg.sender == tx.origin, "Proxy contract not allowed");
_;
}
/**
* @notice Constructor
* @param _oracleAddress: oracle address
* @param _adminAddress: admin address
* @param _operatorAddress: operator address
* @param _intervalSeconds: number of time within an interval
* @param _bufferSeconds: buffer of time for resolution of price
* @param _minBetAmount: minimum bet amounts (in wei)
* @param _oracleUpdateAllowance: oracle update allowance
* @param _treasuryFee: treasury fee (1000 = 10%)
*/
constructor(
address _oracleAddress,
address _adminAddress,
address _operatorAddress,
uint256 _intervalSeconds,
uint256 _bufferSeconds,
uint256 _minBetAmount,
uint256 _oracleUpdateAllowance,
uint256 _treasuryFee
) {
require(_treasuryFee <= MAX_TREASURY_FEE, "Treasury fee too high");
oracle = AggregatorV3Interface(_oracleAddress);
adminAddress = _adminAddress;
operatorAddress = _operatorAddress;
intervalSeconds = _intervalSeconds;
bufferSeconds = _bufferSeconds;
minBetAmount = _minBetAmount;
oracleUpdateAllowance = _oracleUpdateAllowance;
treasuryFee = _treasuryFee;
}
// Set the token contract address
function setzaiAddress(IERC20 zaifAddress) public onlyOwner {
zaif = zaifAddress;
}
// Set the maintenance address
function setMaintenance(address _maintenance) public onlyOwner {
Maintenance = _maintenance;
}
/**
* @notice Bet bear position
* @param epoch: epoch
*/
function betBear(uint256 epoch,address _referrer ,uint256 amount) external whenNotPaused nonReentrant notContract {
require(epoch == currentEpoch, "Bet is too early/late");
require(_bettable(epoch), "Round not bettable");
require(amount >= minBetAmount, "Bet amount must be greater than minBetAmount");
require(ledger[epoch][msg.sender].amount == 0, "Can only bet once per round");
//Calculate token tax fees
uint256 taxAmount = amount.mul(TaxFee).div(10000);
uint256 taxedAmount = amount - taxAmount;
//Record Referral
if (amount > 0 && address(zaiReferral) != address(0) && _referrer != address(0) && _referrer != msg.sender) {
zaiReferral.recordReferral(msg.sender, _referrer);
}
// Update round data
Round storage round = rounds[epoch];
RoundJackpotInfo storage roundInfo = roundsInfo[epoch];
// JackPot check
if(jackpotLock != 0){
if(block.number >= jackpotLock + passedBlocks){
round.totalAmount = round.totalAmount + taxedAmount + jackpotAcmAmt;
jackpotLock = 0;
jackpotAcmAmt = 0;
roundInfo.jackpotRound = true;
}else{
round.totalAmount = round.totalAmount + taxedAmount;
}
}else{
round.totalAmount = round.totalAmount + taxedAmount;
}
round.bearAmount = round.bearAmount + taxedAmount;
// Update user data
BetInfo storage betInfo = ledger[epoch][msg.sender];
betInfo.position = Position.Bear;
betInfo.amount += taxedAmount;
userRounds[msg.sender].push(epoch);
zaif.transferFrom(msg.sender,address(this),amount);
emit BetBear(msg.sender, epoch, amount);
}
/**
* @notice Bet bull position
* @param epoch: epoch
*/
function betBull(uint256 epoch,address _referrer, uint256 amount) external whenNotPaused nonReentrant notContract {
require(epoch == currentEpoch, "Bet is too early/late");
require(_bettable(epoch), "Round not bettable");
require(amount >= minBetAmount, "Bet amount must be greater than minBetAmount");
require(ledger[epoch][msg.sender].amount == 0, "Can only bet once per round");
//Calculate token tax fees
uint256 taxAmount = amount.mul(TaxFee).div(10000);
uint256 taxedAmount = amount - taxAmount;
//Record Referral
if (amount > 0 && address(zaiReferral) != address(0) && _referrer != address(0) && _referrer != msg.sender) {
zaiReferral.recordReferral(msg.sender, _referrer);
}
// Update round data
Round storage round = rounds[epoch];
RoundJackpotInfo storage roundInfo = roundsInfo[epoch];
// JackPot check
if(jackpotLock != 0){
if(block.number >= jackpotLock + passedBlocks){
round.totalAmount = round.totalAmount + taxedAmount + jackpotAcmAmt;
jackpotLock = 0;
jackpotAcmAmt = 0;
roundInfo.jackpotRound = true;
}else{
round.totalAmount = round.totalAmount + taxedAmount;
}
}else{
round.totalAmount = round.totalAmount + taxedAmount;
}
round.bullAmount = round.bullAmount + taxedAmount;
// Update user data
BetInfo storage betInfo = ledger[epoch][msg.sender];
betInfo.position = Position.Bull;
betInfo.amount = taxedAmount;
userRounds[msg.sender].push(epoch);
zaif.transferFrom(msg.sender,address(this),amount);
emit BetBull(msg.sender, epoch, amount);
}
/**
* @notice Claim reward for an array of epochs
* @param epochs: array of epochs
*/
function claim(uint256[] calldata epochs) external nonReentrant notContract {
uint256 reward; // Initializes reward
for (uint256 i = 0; i < epochs.length; i++) {
require(rounds[epochs[i]].startTimestamp != 0, "Round has not started");
require(block.timestamp > rounds[epochs[i]].closeTimestamp, "Round has not ended");
uint256 addedReward = 0;
// Round valid, claim rewards
if (rounds[epochs[i]].oracleCalled) {
require(claimable(epochs[i], msg.sender), "Not eligible for claim");
Round memory round = rounds[epochs[i]];
RoundJackpotInfo memory roundInfo = roundsInfo[epochs[i]];
if (roundInfo.jackpotRound == true) {
if(roundInfo.jackpotClaimed == false){
jackpotAcmSafeCheck = 0;
roundInfo.jackpotClaimed = true;
}
}
addedReward = (ledger[epochs[i]][msg.sender].amount * round.rewardAmount) / round.rewardBaseCalAmount;
uint256 ReferralAmt = (addedReward * refFee) / 10000;
payReferralCommission(msg.sender,addedReward);
addedReward = addedReward - ReferralAmt;
}
// Round invalid, refund bet amount
else {
require(refundable(epochs[i], msg.sender), "Not eligible for refund");
if (roundsInfo[epochs[i]].jackpotRound == true) {
if(roundsInfo[epochs[i]].jackpotClaimed == false){
jackpotAcmAmt = jackpotAcmSafeCheck;
roundsInfo[epochs[i]].jackpotClaimed = true;
}
}
addedReward = ledger[epochs[i]][msg.sender].amount;
}
ledger[epochs[i]][msg.sender].claimed = true;
reward += addedReward;
emit Claim(msg.sender, epochs[i], addedReward);
}
if (reward > 0) {
IERC20(zaif).safeTransfer(msg.sender,reward);
}
}
/**
* @notice Start the next round n, lock price for round n-1, end round n-2
* @dev Callable by operator
*/
function executeRound() external whenNotPaused onlyOperator {
require(
genesisStartOnce && genesisLockOnce,
"Can only run after genesisStartRound and genesisLockRound is triggered"
);
(uint80 currentRoundId, int256 currentPrice) = _getPriceFromOracle();
oracleLatestRoundId = uint256(currentRoundId);
// CurrentEpoch refers to previous round (n-1)
_safeLockRound(currentEpoch, currentRoundId, currentPrice);
_safeEndRound(currentEpoch - 1, currentRoundId, currentPrice);
_calculateRewards(currentEpoch - 1);
// Increment currentEpoch to current round (n)
currentEpoch = currentEpoch + 1;
_safeStartRound(currentEpoch);
}
/**
* @notice Lock genesis round
* @dev Callable by operator
*/
function genesisLockRound() external whenNotPaused onlyOperator {
require(genesisStartOnce, "Can only run after genesisStartRound is triggered");
require(!genesisLockOnce, "Can only run genesisLockRound once");
(uint80 currentRoundId, int256 currentPrice) = _getPriceFromOracle();
oracleLatestRoundId = uint256(currentRoundId);
_safeLockRound(currentEpoch, currentRoundId, currentPrice);
currentEpoch = currentEpoch + 1;
_startRound(currentEpoch);
genesisLockOnce = true;
}
/**
* @notice Start genesis round
* @dev Callable by admin or operator
*/
function genesisStartRound() external whenNotPaused onlyOperator {
require(!genesisStartOnce, "Can only run genesisStartRound once");
currentEpoch = currentEpoch + 1;
_startRound(currentEpoch);
genesisStartOnce = true;
}
/**
* @notice called by the admin to pause, triggers stopped state
* @dev Callable by admin or operator
*/
function pause() external whenNotPaused onlyAdminOrOperator {
_pause();
emit Pause(currentEpoch);
}
/**
* @notice Claim all rewards in treasury
* @dev Callable by admin
*/
function claimTreasury() external nonReentrant onlyAdmin {
uint256 currentTreasuryAmount = treasuryAmount;
treasuryAmount = 0;
uint256 maintenanceAmt = (currentTreasuryAmount * 3333) / 10000; // 1% total > 33.3% of 3%
uint256 devAmt = (currentTreasuryAmount * 3333) / 10000; // 1% total > 33.3% of 3%
uint256 staffAmt = (currentTreasuryAmount * 3333) / 10000; // 1% total > 33.3% of 3%
// IERC20(zaif).safeTransfer(treasuryAddress,treasuryAmt);
IERC20(zaif).safeTransfer(devAddress, devAmt);
IERC20(zaif).safeTransfer(staffAddress, staffAmt);
IERC20(zaif).safeTransfer(Maintenance, maintenanceAmt);
emit TreasuryClaim(currentTreasuryAmount);
}
/**
* @notice called by the admin to unpause, returns to normal state
* Reset genesis state. Once paused, the rounds would need to be kickstarted by genesis
*/
function unpause() external whenPaused onlyAdmin {
genesisStartOnce = false;
genesisLockOnce = false;
_unpause();
emit Unpause(currentEpoch);
}
/**
* @notice Set buffer and interval (in seconds)
* @dev Callable by admin
*/
function setBufferAndIntervalSeconds(uint256 _bufferSeconds, uint256 _intervalSeconds)
external
whenPaused
onlyAdmin
{
require(_bufferSeconds < _intervalSeconds, "bufferSeconds must be inferior to intervalSeconds");
bufferSeconds = _bufferSeconds;
intervalSeconds = _intervalSeconds;
emit NewBufferAndIntervalSeconds(_bufferSeconds, _intervalSeconds);
}
/**
* @notice Set minBetAmount
* @dev Callable by admin
*/
function setMinBetAmount(uint256 _minBetAmount) external whenPaused onlyAdmin {
require(_minBetAmount != 0, "Must be superior to 0");
minBetAmount = _minBetAmount;
emit NewMinBetAmount(currentEpoch, minBetAmount);
}
/**
* @notice Set operator address
* @dev Callable by admin
*/
function setOperator(address _operatorAddress) external onlyAdmin {
require(_operatorAddress != address(0), "Cannot be zero address");
operatorAddress = _operatorAddress;
emit NewOperatorAddress(_operatorAddress);
}
/**
* @notice Set Oracle address
* @dev Callable by admin
*/
function setOracle(address _oracle) external whenPaused onlyAdmin {
require(_oracle != address(0), "Cannot be zero address");
oracleLatestRoundId = 0;
oracle = AggregatorV3Interface(_oracle);
// Dummy check to make sure the interface implements this function properly
oracle.latestRoundData();
emit NewOracle(_oracle);
}
/**
* @notice Set oracle update allowance
* @dev Callable by admin
*/
function setOracleUpdateAllowance(uint256 _oracleUpdateAllowance) external whenPaused onlyAdmin {
oracleUpdateAllowance = _oracleUpdateAllowance;
emit NewOracleUpdateAllowance(_oracleUpdateAllowance);
}
/**
* @notice Set treasury fee
* @dev Callable by admin
* fees are distributed 1% for Feature Maintenance 1% for development on distribution 1% for staff on distribution
*/
function setTreasuryFee(uint256 _treasuryFee) external whenPaused onlyAdmin {
require(_treasuryFee <= MAX_TREASURY_FEE, "Treasury fee too high");
treasuryFee = _treasuryFee;
emit NewTreasuryFee(currentEpoch, treasuryFee);
}
/**
* @notice It allows the owner to recover tokens sent to the contract by mistake
* @param _token: token address
* @param _amount: token amount
* @dev Callable by owner
*/
function recoverToken(address _token, uint256 _amount) external onlyOwner {
IERC20(_token).safeTransfer(address(msg.sender), _amount);
emit TokenRecovery(_token, _amount);
}
/**
* @notice Set admin address
* @dev Callable by owner
*/
function setAdmin(address _adminAddress) external onlyOwner {
require(_adminAddress != address(0), "Cannot be zero address");
adminAddress = _adminAddress;
emit NewAdminAddress(_adminAddress);
}
/**
* @notice Returns round epochs and bet information for a user that has participated
* @param user: user address
* @param cursor: cursor
* @param size: size
*/
function getUserRounds(
address user,
uint256 cursor,
uint256 size
)
external
view
returns (
uint256[] memory,
BetInfo[] memory,
uint256
)
{
uint256 length = size;
if (length > userRounds[user].length - cursor) {
length = userRounds[user].length - cursor;
}
uint256[] memory values = new uint256[](length);
BetInfo[] memory betInfo = new BetInfo[](length);
for (uint256 i = 0; i < length; i++) {
values[i] = userRounds[user][cursor + i];
betInfo[i] = ledger[values[i]][user];
}
return (values, betInfo, cursor + length);
}
/**
* @notice Returns round epochs length
* @param user: user address
*/
function getUserRoundsLength(address user) external view returns (uint256) {
return userRounds[user].length;
}
function getJackpotAmount() external view returns (uint256) {
return jackpotAcmAmt;
}
function getJackpotLockBlock() external view returns (uint256) {
return jackpotLock;
}
/**
* @notice Get the claimable stats of specific epoch and user account
* @param epoch: epoch
* @param user: user address
*/
function claimable(uint256 epoch, address user) public view returns (bool) {
BetInfo memory betInfo = ledger[epoch][user];
Round memory round = rounds[epoch];
if (round.lockPrice == round.closePrice) {
return false;
}
return
round.oracleCalled &&
betInfo.amount != 0 &&
!betInfo.claimed &&
((round.closePrice > round.lockPrice && betInfo.position == Position.Bull) ||
(round.closePrice < round.lockPrice && betInfo.position == Position.Bear));
}
/**
* @notice Get the refundable stats of specific epoch and user account
* @param epoch: epoch
* @param user: user address
*/
function refundable(uint256 epoch, address user) public view returns (bool) {
BetInfo memory betInfo = ledger[epoch][user];
Round memory round = rounds[epoch];
return
!round.oracleCalled &&
!betInfo.claimed &&
block.timestamp > round.closeTimestamp + bufferSeconds &&
betInfo.amount != 0;
}
/**
* @notice Calculate rewards for round
* @param epoch: epoch
*/
function _calculateRewards(uint256 epoch) internal {
require(rounds[epoch].rewardBaseCalAmount == 0 && rounds[epoch].rewardAmount == 0, "Rewards calculated");
Round storage round = rounds[epoch];
uint256 rewardBaseCalAmount;
uint256 treasuryAmt;
uint256 rewardAmount;
// Bull wins
if (round.closePrice > round.lockPrice) {
rewardBaseCalAmount = round.bullAmount;
treasuryAmt = (round.totalAmount * treasuryFee) / 10000;
rewardAmount = round.totalAmount - treasuryAmt;
}
// Bear wins
else if (round.closePrice < round.lockPrice) {
rewardBaseCalAmount = round.bearAmount;
treasuryAmt = (round.totalAmount * treasuryFee) / 10000;
rewardAmount = round.totalAmount - treasuryAmt;
}
// House wins
else {
rewardBaseCalAmount = 0;
rewardAmount = 0;
treasuryAmt = round.totalAmount;
}
round.rewardBaseCalAmount = rewardBaseCalAmount;
round.rewardAmount = rewardAmount;
// Add to treasury
treasuryAmount += treasuryAmt;
emit RewardsCalculated(epoch, rewardBaseCalAmount, rewardAmount, treasuryAmt);
}
/**
* @notice End round
* @param epoch: epoch
* @param roundId: roundId
* @param price: price of the round
*/
function _safeEndRound(
uint256 epoch,
uint256 roundId,
int256 price
) internal {
require(rounds[epoch].lockTimestamp != 0, "Can only end round after round has locked");
require(block.timestamp >= rounds[epoch].closeTimestamp, "Can only end round after closeTimestamp");
require(
block.timestamp <= rounds[epoch].closeTimestamp + bufferSeconds,
"Can only end round within bufferSeconds"
);
Round storage round = rounds[epoch];
round.closePrice = price;
round.closeOracleId = roundId;
round.oracleCalled = true;
emit EndRound(epoch, roundId, round.closePrice);
}
/**
* @notice Lock round
* @param epoch: epoch
* @param roundId: roundId
* @param price: price of the round
*/
function _safeLockRound(
uint256 epoch,
uint256 roundId,
int256 price
) internal {
require(rounds[epoch].startTimestamp != 0, "Can only lock round after round has started");
require(block.timestamp >= rounds[epoch].lockTimestamp, "Can only lock round after lockTimestamp");
require(
block.timestamp <= rounds[epoch].lockTimestamp + bufferSeconds,
"Can only lock round within bufferSeconds"
);
Round storage round = rounds[epoch];
round.closeTimestamp = block.timestamp + intervalSeconds;
round.lockPrice = price;
round.lockOracleId = roundId;
emit LockRound(epoch, roundId, round.lockPrice);
}
/**
* @notice Start round
* Previous round n-2 must end
* @param epoch: epoch
*/
function _safeStartRound(uint256 epoch) internal {
require(genesisStartOnce, "Can only run after genesisStartRound is triggered");
require(rounds[epoch - 2].closeTimestamp != 0, "Can only start round after round n-2 has ended");
require(
block.timestamp >= rounds[epoch - 2].closeTimestamp,
"Can only start new round after round n-2 closeTimestamp"
);
_startRound(epoch);
}
/**
* @notice Transfer BNB in a safe way
* @param to: address to transfer BNB to
* @param value: BNB amount to transfer (in wei)
*/
function _safeTransferBNB(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}("");
require(success, "TransferHelper: BNB_TRANSFER_FAILED");
}
/**
* @notice Start round
* Previous round n-2 must end
* @param epoch: epoch
*/
function _startRound(uint256 epoch) internal {
Round storage round = rounds[epoch];
round.startTimestamp = block.timestamp;
round.lockTimestamp = block.timestamp + intervalSeconds;
round.closeTimestamp = block.timestamp + (2 * intervalSeconds);
round.epoch = epoch;
round.totalAmount = 0;
emit StartRound(epoch);
}
/**
* @notice Determine if a round is valid for receiving bets
* Round must have started and locked
* Current timestamp must be within startTimestamp and closeTimestamp
*/
function _bettable(uint256 epoch) internal view returns (bool) {
return
rounds[epoch].startTimestamp != 0 &&
rounds[epoch].lockTimestamp != 0 &&
block.timestamp > rounds[epoch].startTimestamp &&
block.timestamp < rounds[epoch].lockTimestamp;
}
/**
* @notice Get latest recorded price from oracle
* If it falls below allowed buffer or has not updated, it would be invalid.
*/
function _getPriceFromOracle() internal view returns (uint80, int256) {
uint256 leastAllowedTimestamp = block.timestamp + oracleUpdateAllowance;
(uint80 roundId, int256 price, , uint256 timestamp, ) = oracle.latestRoundData();
require(timestamp <= leastAllowedTimestamp, "Oracle update exceeded max timestamp allowance");
require(
uint256(roundId) > oracleLatestRoundId,
"Oracle update roundId must be larger than oracleLatestRoundId"
);
return (roundId, price);
}
/**
* @notice Returns true if `account` is a contract.
* @param account: account address
*/
function _isContract(address account) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
// Update the zai referral contract address by the owner
function setzaiReferral(IZaiReferral _zaiReferral) public onlyOwner {
zaiReferral = _zaiReferral;
}
// Update how many blocks to pay the jackpot
function setPassedBlocks(uint256 _passedBlocks) public onlyOwner {
passedBlocks = _passedBlocks;
}
// Update referral commission rate by the owner
function setReferralCommissionRate(uint16 _referralCommissionRate) public onlyOperator {
referralCommissionRate = _referralCommissionRate;
}
// Pay referral commission to the referrer who referred this user.
function payReferralCommission(address _user, uint256 _pending) internal {
if (address(zaiReferral) != address(0) && referralCommissionRate > 0) {
address referrer = zaiReferral.getReferrer(_user);
uint256 commissionAmount = _pending.mul(referralCommissionRate).div(10000);
if (referrer != address(0) && commissionAmount > 0) {
IERC20(zaif).safeTransfer(referrer, commissionAmount);
uint256 TaxAmount = commissionAmount.mul(TaxFee).div(10000);
commissionAmount = commissionAmount - TaxAmount;
zaiReferral.recordReferralCommission(referrer, commissionAmount);
emit ReferralCommissionPaid(_user, referrer, commissionAmount);
} else{
// add to JackPot Amount > acumulation to pay in 200480 blocks roughly 1 week
if(jackpotLock == 0){
jackpotLock = block.number;
}
jackpotAcmAmt += commissionAmount;
// Amount in case jackpot round fails ,it backs to the jackpot
jackpotAcmSafeCheck += commissionAmount;
}
}
}
}
|
Start round Previous round n-2 must end epoch: epoch/
|
function _startRound(uint256 epoch) internal {
Round storage round = rounds[epoch];
round.startTimestamp = block.timestamp;
round.lockTimestamp = block.timestamp + intervalSeconds;
round.closeTimestamp = block.timestamp + (2 * intervalSeconds);
round.epoch = epoch;
round.totalAmount = 0;
emit StartRound(epoch);
}
| 6,385,370
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./SafeMath.sol";
import "./IUniswapV2Factory.sol";
import "./OwnableUpgradeSafe.sol";
import "./IERC20.sol";
contract XAUTransferHandler is OwnableUpgradeSafe {
using SafeMath for uint256;
address tokenUniswapPairXAU;
address[] public trackedPairs;
uint16 public feePercentX100;
bool public transfersPaused;
mapping (address => bool) public noFeeList;
mapping (address => bool) public isPair;
event NewTransfersPaused(bool oldTransfersPaused, bool newTransfersPaused);
event NewFeePercentX100(uint256 oldFeePercentX100, uint256 newFeePercentX100);
function initialize(
address _tokenUniswapPairXAU,
address _xauVault,
uint16 _feePercentX100
) public initializer {
tokenUniswapPairXAU = _tokenUniswapPairXAU;
OwnableUpgradeSafe.__Ownable_init();
feePercentX100 = _feePercentX100;
transfersPaused = true;
_editNoFeeList(_xauVault, true);
_addPairToTrack(tokenUniswapPairXAU);
}
function addPairToTrack(address pair) onlyOwner public {
_addPairToTrack(pair);
}
function setNewTokenUniswap(address _tokenUniswapPairXAU) public onlyOwner {
tokenUniswapPairXAU = _tokenUniswapPairXAU;
_addPairToTrack(tokenUniswapPairXAU);
}
function _addPairToTrack(address pair) internal {
uint256 length = trackedPairs.length;
for (uint256 i = 0; i < length; i++) {
require(trackedPairs[i] != pair, "Pair already tracked");
}
// we sync
sync(pair);
// we add to array so we can loop over it
trackedPairs.push(pair);
// we add pair to no fee sender list
_editNoFeeList(pair, true);
// we add it to pair mapping to lookups
isPair[pair] = true;
}
// CORE token is pausable
function setTransfersPaused(bool _transfersPaused) public onlyOwner {
bool oldTransfersPaused = transfersPaused;
transfersPaused = _transfersPaused;
// Sync all tracked pairs
uint256 length = trackedPairs.length;
for (uint256 i = 0; i < length; i++) {
sync(trackedPairs[i]);
}
emit NewTransfersPaused(oldTransfersPaused, _transfersPaused);
}
function setFeePercentX100(uint16 _feePercentX100) public onlyOwner {
require(_feePercentX100 <= 1000, 'Fee clamped at 10%');
uint256 oldFeePercentX100 = feePercentX100;
feePercentX100 = _feePercentX100;
emit NewFeePercentX100(oldFeePercentX100, _feePercentX100);
}
function editNoFeeList(address _address, bool noFee) public onlyOwner {
_editNoFeeList(_address, noFee);
}
function _editNoFeeList(address _address, bool noFee) internal{
noFeeList[_address] = noFee;
}
// Old sync for backwards compatibility - syncs xautokenEthPair
function sync() public returns (bool lastIsMint, bool lpTokenBurn) {
(lastIsMint, lpTokenBurn) = sync(tokenUniswapPairXAU);
}
mapping(address => uint256) private lpSupplyOfPair;
function sync(address pair) public returns (bool lastIsMint, bool lpTokenBurn) {
uint256 _LPSupplyOfPairNow = IERC20(pair).totalSupply();
lpTokenBurn = lpSupplyOfPair[pair] > _LPSupplyOfPairNow;
lpSupplyOfPair[pair] = _LPSupplyOfPairNow;
lastIsMint = false;
}
function handleTransfer
(address sender,
address recipient,
uint256 amount
) public {
}
function calculateAmountsAfterFee(
address sender,
address recipient,
uint256 amount
) public returns (uint256 transferToAmount, uint256 transferToFeeDistributorAmount) {
require(transfersPaused == false, "XAU TransferHandler: Transfers Paused");
if (isPair[recipient]) {
sync(recipient);
}
if (!isPair[recipient] && !isPair[sender])
sync();
if (noFeeList[sender]) {
transferToFeeDistributorAmount = 0;
transferToAmount = amount;
}
else {
// console.log("Normal fee transfer");
transferToFeeDistributorAmount = amount.mul(feePercentX100).div(10000);
transferToAmount = amount.sub(transferToFeeDistributorAmount);
}
}
}
|
console.log("Normal fee transfer");
|
function calculateAmountsAfterFee(
address sender,
address recipient,
uint256 amount
) public returns (uint256 transferToAmount, uint256 transferToFeeDistributorAmount) {
require(transfersPaused == false, "XAU TransferHandler: Transfers Paused");
if (isPair[recipient]) {
sync(recipient);
}
if (!isPair[recipient] && !isPair[sender])
sync();
if (noFeeList[sender]) {
transferToFeeDistributorAmount = 0;
transferToAmount = amount;
}
else {
transferToFeeDistributorAmount = amount.mul(feePercentX100).div(10000);
transferToAmount = amount.sub(transferToFeeDistributorAmount);
}
}
| 28,552
|
// SPDX-License-Identifier: CC0-1.0
pragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./utils/PausableEIP1967Admin.sol";
import "./SBCToken.sol";
import "./SBCDepositContract.sol";
/**
* @title SBCWrapper
* @dev Wrapper engine contract for minting wrapped tokens that can be deposited into SBC.
* Used for wrapping of STAKE and other possible ERC20 tokens.
*/
contract SBCWrapper is IERC677Receiver, PausableEIP1967Admin, Claimable, ReentrancyGuard {
using SafeERC20 for IERC20;
enum TokenStatus {
DISABLED,
ENABLED,
PAUSED
}
mapping(address => TokenStatus) public tokenStatus;
// if tokenRate[A] = X, then user will receive Y * X / 10**18 wrapped tokens for locking Y of A tokens.
mapping(address => uint256) public tokenRate;
SBCToken public immutable sbcToken;
SBCDepositContract public immutable sbcDepositContract;
event Swap(address indexed token, address indexed user, uint256 amount, uint256 received);
event SwapRateUpdated(address indexed token, uint256 rate);
event TokenSwapEnabled(address indexed token);
event TokenSwapPaused(address indexed token);
constructor(SBCToken _sbcToken, SBCDepositContract _depositContract) {
sbcToken = _sbcToken;
sbcDepositContract = _depositContract;
}
/**
* @dev Enables swapping of new token into wrapped SBC token at a given rate.
* Only admin can call this method.
* @param _token address of the enabled or reenabled token contract.
* @param _rate exchange rate for the new pair, multiplied by 10**18.
*/
function enableToken(address _token, uint256 _rate) external onlyAdmin {
require(_rate > 0, "SBCWrapper: invalid rate");
TokenStatus oldStatus = tokenStatus[_token];
tokenStatus[_token] = TokenStatus.ENABLED;
tokenRate[_token] = _rate;
if (oldStatus != TokenStatus.ENABLED) {
emit TokenSwapEnabled(_token);
}
emit SwapRateUpdated(_token, _rate);
}
/**
* @dev Temporary pauses swapping of some particular token, which can be reenaled later.
* Only admin can call this method.
* @param _token address of the paused token contract.
*/
function pauseToken(address _token) external onlyAdmin {
require(tokenStatus[_token] == TokenStatus.ENABLED, "SBCWrapper: token is not enabled");
tokenStatus[_token] = TokenStatus.PAUSED;
emit TokenSwapPaused(_token);
}
/**
* @dev Swaps some of the whitelisted tokens for the newly created wrapped tokens.
* Tokens must be pre-approved before calling this function.
* @param _token address of the swapped token contract.
* @param _amount amount of tokens to swap.
* @param _permitData optional permit calldata to use for preliminary token approval.
* supports STAKE permit and EIP2612 standards.
*/
function swap(
address _token,
uint256 _amount,
bytes calldata _permitData
) external nonReentrant whenNotPaused {
require(tokenStatus[_token] == TokenStatus.ENABLED, "SBCWrapper: token is not enabled");
if (_permitData.length > 4) {
// supported signatures:
// permit(address,address,uint256,uint256,bool,uint8,bytes32,bytes32)
// permit(address,address,uint256,uint256,uint8,bytes32,bytes32)
require(
bytes4(_permitData[0:4]) == bytes4(0x8fcbaf0c) || bytes4(_permitData[0:4]) == bytes4(0xd505accf),
"SBCWrapper: invalid permit signature"
);
(bool status, ) = _token.call(_permitData);
require(status, "SBCWrapper: permit failed");
}
address sender = _msgSender();
// We do not plan to support any deflationary or rebasing tokens in this contract
// so it is not required to check that ERC20 balance has indeed change.
// It is an admin responsibility to carefully check that enabled token correctly implements ERC20 standard.
IERC20(_token).safeTransferFrom(sender, address(this), _amount);
_swapTokens(sender, _token, _amount);
}
/**
* @dev ERC677 callback for swapping tokens in the simpler way during transferAndCall.
* @param from address of the received token contract.
* @param value amount of the received tokens.
* @param data should be empty for a simple token swap, otherwise will pass it further to the deposit contract.
*/
function onTokenTransfer(
address from,
uint256 value,
bytes calldata data
) external override nonReentrant whenNotPaused returns (bool) {
address token = _msgSender();
require(tokenStatus[token] == TokenStatus.ENABLED, "SBCWrapper: token is not enabled");
if (data.length == 0) {
_swapTokens(from, token, value);
} else {
uint256 swappedAmount = _swapTokens(address(this), token, value);
sbcToken.transferAndCall(address(sbcDepositContract), swappedAmount, data);
}
return true;
}
/**
* @dev Allows to transfer any locked token from this contract.
* Only admin can call this method.
* While it is not allowed to claim previously enabled or paused tokens,
* the admin should still verify that the claimed token is a valid ERC20 token contract.
* @param _token address of the token, if it is not provided (0x00..00), native coins will be transferred.
* @param _to address that will receive the locked tokens on this contract.
*/
function claimTokens(address _token, address _to) external onlyAdmin {
require(tokenStatus[_token] == TokenStatus.DISABLED, "SBCWrapper: token already swappable");
_claimValues(_token, _to);
}
function _swapTokens(
address _receiver,
address _token,
uint256 _amount
) internal returns (uint256) {
uint256 acquired = (_amount * tokenRate[_token]) / 1 ether;
require(acquired > 0, "SBCWrapper: invalid amount");
sbcToken.mint(_receiver, acquired);
emit Swap(_token, _receiver, _amount, acquired);
return acquired;
}
}
|
ERC677 callback for swapping tokens in the simpler way during transferAndCall. from address of the received token contract. value amount of the received tokens. data should be empty for a simple token swap, otherwise will pass it further to the deposit contract./
|
function onTokenTransfer(
address from,
uint256 value,
bytes calldata data
) external override nonReentrant whenNotPaused returns (bool) {
address token = _msgSender();
require(tokenStatus[token] == TokenStatus.ENABLED, "SBCWrapper: token is not enabled");
if (data.length == 0) {
_swapTokens(from, token, value);
uint256 swappedAmount = _swapTokens(address(this), token, value);
sbcToken.transferAndCall(address(sbcDepositContract), swappedAmount, data);
}
return true;
}
| 1,051,840
|
// SunSwapBridge.sol
// SPDX-License-Identifier: MIT
// solhint-disable-next-line
pragma solidity ^0.8.0;
/// @title Up Stable Token eXperiment SunSwap bridge
/// @author USTX Team
/// @dev This contract implements the DEX functionality for the USTX token (v2).
// solhint-disable-next-line
interface IUstxDEX {
// Events
event TokenBuy(address indexed buyer, uint256 indexed usdtSold, uint256 indexed tokensBought, uint256 price, uint256 tIndex);
event TokenSell(address indexed buyer, uint256 indexed tokensSold, uint256 indexed usdtBought, uint256 price, uint256 tIndex);
event Snapshot(address indexed operator, uint256 indexed reserveBalance, uint256 indexed tokenBalance);
event AdminAdded(address indexed account);
event AdminRemoved(address indexed account);
/***********************************|
| Exchange Functions |
|__________________________________*/
/**
* @dev Public function to preview token purchase with exact input in USDT
* @param usdtSold amount of USDT to sell
* @return number of tokens that can be purchased with input usdtSold
*/
function buyTokenInputPreview(uint256 usdtSold) external view returns (uint256);
/**
* @dev Public function to preview token sale with exact input in tokens
* @param tokensSold amount of token to sell
* @return Amount of USDT that can be bought with input Tokens.
*/
function sellTokenInputPreview(uint256 tokensSold) external view returns (uint256);
/**
* @dev Public function to buy tokens during launchpad
* @param rSell amount of UDST to sell
* @param minTokens minimum amount of tokens to buy
* @return number of tokens bought
*/
function buyTokenLaunchInput(uint256 rSell, uint256 tIndex, uint256 minTokens) external returns (uint256);
/**
* @dev Public function to buy tokens during launchpad and transfer them to recipient
* @param rSell amount of UDST to sell
* @param minTokens minimum amount of tokens to buy
* @param recipient recipient of the transaction
* @return number of tokens bought
*/
function buyTokenLaunchTransferInput(uint256 rSell, uint256 tIndex, uint256 minTokens, address recipient) external returns(uint256);
/**
* @dev Public function to buy tokens
* @param rSell amount of UDST to sell
* @param minTokens minimum amount of tokens to buy
* @param tIndex index of the reserve token to swap
* @return number of tokens bought
*/
function buyTokenInput(uint256 rSell, uint256 tIndex, uint256 minTokens) external returns (uint256);
/**
* @dev Public function to buy tokens and transfer them to recipient
* @param rSell amount of UDST to sell
* @param minTokens minimum amount of tokens to buy
* @param tIndex index of the reserve token to swap
* @param recipient recipient of the transaction
* @return number of tokens bought
*/
function buyTokenTransferInput(uint256 rSell, uint256 tIndex, uint256 minTokens, address recipient) external returns(uint256);
/**
* @dev Public function to sell tokens
* @param tokensSold number of tokens to sell
* @param minUsdts minimum number of UDST to buy
* @return number of USDTs bought
*/
function sellTokenInput(uint256 tokensSold, uint256 tIndex, uint256 minUsdts) external returns (uint256);
/**
* @dev Public function to sell tokens and trasnfer USDT to recipient
* @param tokensSold number of tokens to sell
* @param minUsdts minimum number of UDST to buy
* @param recipient recipient of the transaction
* @return number of USDTs bought
*/
function sellTokenTransferInput(uint256 tokensSold, uint256 tIndex, uint256 minUsdts, address recipient) external returns (uint256);
/**************************************|
| Getter and Setter Functions |
|_____________________________________*/
/**
* @dev Function to get current price
* @return current price
*
*/
function getPrice() external view returns (uint256);
}
|
Up Stable Token eXperiment SunSwap bridge USTX Team This contract implements the DEX functionality for the USTX token (v2). solhint-disable-next-line Events
|
interface IUstxDEX {
event TokenBuy(address indexed buyer, uint256 indexed usdtSold, uint256 indexed tokensBought, uint256 price, uint256 tIndex);
event TokenSell(address indexed buyer, uint256 indexed tokensSold, uint256 indexed usdtBought, uint256 price, uint256 tIndex);
event Snapshot(address indexed operator, uint256 indexed reserveBalance, uint256 indexed tokenBalance);
event AdminAdded(address indexed account);
event AdminRemoved(address indexed account);
| Exchange Functions |
|__________________________________*/
function buyTokenInputPreview(uint256 usdtSold) external view returns (uint256);
function sellTokenInputPreview(uint256 tokensSold) external view returns (uint256);
function buyTokenLaunchInput(uint256 rSell, uint256 tIndex, uint256 minTokens) external returns (uint256);
function buyTokenLaunchTransferInput(uint256 rSell, uint256 tIndex, uint256 minTokens, address recipient) external returns(uint256);
function buyTokenInput(uint256 rSell, uint256 tIndex, uint256 minTokens) external returns (uint256);
function buyTokenTransferInput(uint256 rSell, uint256 tIndex, uint256 minTokens, address recipient) external returns(uint256);
function sellTokenInput(uint256 tokensSold, uint256 tIndex, uint256 minUsdts) external returns (uint256);
function sellTokenTransferInput(uint256 tokensSold, uint256 tIndex, uint256 minUsdts, address recipient) external returns (uint256);
| Getter and Setter Functions |
|_____________________________________*/
function getPrice() external view returns (uint256);
pragma solidity ^0.8.0;
}
| 6,405,139
|
contract TurnBasedGame {
bool debug; // If contract is deployed in debug mode, some debug features are enabled
modifier debugOnly {
if (!debug)
throw;
_
}
event GameEnded(bytes32 indexed gameId);
event GameClosed(bytes32 indexed gameId, address indexed player);
event GameTimeoutStarted(bytes32 indexed gameId, uint timeoutStarted, int8 timeoutState);
// GameDrawOfferRejected: notification that a draw of the currently turning player
// is rejected by the waiting player
event GameDrawOfferRejected(bytes32 indexed gameId);
event DebugInts(string message, uint value1, uint value2, uint value3);
struct Game {
address player1;
address player2;
string player1Alias;
string player2Alias;
address nextPlayer;
address winner;
bool ended;
uint pot; // What this game is worth: ether paid into the game
uint player1Winnings;
uint player2Winnings;
uint turnTime; // in minutes
uint timeoutStarted; // timer for timeout
/*
* -2 draw offered by nextPlayer
* -1 draw offered by waiting player
* 0 nothing
* 1 checkmate
* 2 timeout
*/
int8 timeoutState;
}
mapping (bytes32 => Game) public games;
// stack of open game ids
mapping (bytes32 => bytes32) public openGameIds;
bytes32 public head;
// stack of games of players
mapping (address => mapping (bytes32 => bytes32)) public gamesOfPlayers;
mapping (address => bytes32) public gamesOfPlayersHeads;
function getGamesOfPlayer(address player) constant returns (bytes32[]) {
var playerHead = gamesOfPlayersHeads[player];
var counter = 0;
for (var ga = playerHead; ga != 0; ga = gamesOfPlayers[player][ga]) {
counter++;
}
bytes32[] memory data = new bytes32[](counter);
var currentGame = playerHead;
for (var i = 0; i < counter; i++) {
data[i] = currentGame;
currentGame = gamesOfPlayers[player][currentGame];
}
return data;
}
function getOpenGameIds() constant returns (bytes32[]) {
var counter = 0;
for (var ga = head; ga != 'end'; ga = openGameIds[ga]) {
counter++;
}
bytes32[] memory data = new bytes32[](counter);
var currentGame = head;
for (var i = 0; i < counter; i++) {
data[i] = currentGame;
currentGame = openGameIds[currentGame];
}
return data;
}
// closes a game that is not currently running
function closePlayerGame(bytes32 gameId) public {
var game = games[gameId];
// game already started and not finished yet
if (!(game.player2 == 0 || game.ended))
throw;
if (msg.sender != game.player1 && msg.sender != game.player2)
throw;
if (!game.ended)
games[gameId].ended = true;
if (game.player2 == 0) {
// Remove from openGameIds
if (head == gameId) {
head = openGameIds[head];
openGameIds[gameId] = 0;
} else {
for (var g = head; g != 'end' && openGameIds[g] != 'end'; g = openGameIds[g]) {
if (openGameIds[g] == gameId) {
openGameIds[g] = openGameIds[gameId];
openGameIds[gameId] = 0;
break;
}
}
}
games[gameId].player1Winnings = games[gameId].pot;
games[gameId].pot = 0;
}
// Remove from gamesOfPlayers
var playerHead = gamesOfPlayersHeads[msg.sender];
if (playerHead == gameId) {
gamesOfPlayersHeads[msg.sender] = gamesOfPlayers[msg.sender][playerHead];
gamesOfPlayers[msg.sender][head] = 0;
} else {
for (var ga = playerHead; ga != 0 && gamesOfPlayers[msg.sender][ga] != 'end';
ga = gamesOfPlayers[msg.sender][ga]) {
if (gamesOfPlayers[msg.sender][ga] == gameId) {
gamesOfPlayers[msg.sender][ga] = gamesOfPlayers[msg.sender][gameId];
gamesOfPlayers[msg.sender][gameId] = 0;
break;
}
}
}
GameClosed(gameId, msg.sender);
}
/**
* Surrender = unilateral declaration of loss
*/
function surrender(bytes32 gameId) notEnded(gameId) public {
if (games[gameId].winner != 0) {
// Game already ended
throw;
}
if (games[gameId].player1 == msg.sender) {
// Player 1 surrendered, player 2 won
games[gameId].winner = games[gameId].player2;
games[gameId].player2Winnings = games[gameId].pot;
games[gameId].pot = 0;
} else if(games[gameId].player2 == msg.sender) {
// Player 2 surrendered, player 1 won
games[gameId].winner = games[gameId].player1;
games[gameId].player1Winnings = games[gameId].pot;
games[gameId].pot = 0;
} else {
// Sender is not a participant of this game
throw;
}
games[gameId].ended = true;
GameEnded(gameId);
}
/**
* Allows the winner of a game to withdraw their ether
* bytes32 gameId: ID of the game they have won
*/
function withdraw(bytes32 gameId) public {
uint payout = 0;
if(games[gameId].player1 == msg.sender && games[gameId].player1Winnings > 0) {
payout = games[gameId].player1Winnings;
games[gameId].player1Winnings = 0;
if (!msg.sender.send(payout)) {
throw;
}
}
else if(games[gameId].player2 == msg.sender && games[gameId].player2Winnings > 0) {
payout = games[gameId].player2Winnings;
games[gameId].player2Winnings = 0;
if (!msg.sender.send(payout)) {
throw;
}
}
else {
throw;
}
}
function isGameEnded(bytes32 gameId) public constant returns (bool) {
return games[gameId].ended;
}
modifier notEnded(bytes32 gameId) {
if (games[gameId].ended) throw;
_
}
function initGame(string player1Alias, bool playAsWhite, uint turnTime) public returns (bytes32) {
if (turnTime < 5)
throw;
// Generate game id based on player's addresses and current block number
bytes32 gameId = sha3(msg.sender, block.number);
games[gameId].ended = false;
games[gameId].turnTime = turnTime;
games[gameId].timeoutState = 0;
// Initialize participants
games[gameId].player1 = msg.sender;
games[gameId].player1Alias = player1Alias;
games[gameId].player1Winnings = 0;
games[gameId].player2Winnings = 0;
// Initialize game value
games[gameId].pot = msg.value * 2;
// Add game to gamesOfPlayers
gamesOfPlayers[msg.sender][gameId] = gamesOfPlayersHeads[msg.sender];
gamesOfPlayersHeads[msg.sender] = gameId;
// Add to openGameIds
openGameIds[gameId] = head;
head = gameId;
return gameId;
}
/**
* Join an initialized game
* bytes32 gameId: ID of the game to join
* string player2Alias: Alias of the player that is joining
*/
function joinGame(bytes32 gameId, string player2Alias) public {
// Check that this game does not have a second player yet
if (games[gameId].player2 != 0) {
throw;
}
// throw if the second player did not match the bet.
if (msg.value != games[gameId].pot) {
throw;
}
games[gameId].pot += msg.value;
games[gameId].player2 = msg.sender;
games[gameId].player2Alias = player2Alias;
// Add game to gamesOfPlayers
gamesOfPlayers[msg.sender][gameId] = gamesOfPlayersHeads[msg.sender];
gamesOfPlayersHeads[msg.sender] = gameId;
// Remove from openGameIds
if (head == gameId) {
head = openGameIds[head];
openGameIds[gameId] = 0;
} else {
for (var g = head; g != 'end' && openGameIds[g] != 'end'; g = openGameIds[g]) {
if (openGameIds[g] == gameId) {
openGameIds[g] = openGameIds[gameId];
openGameIds[gameId] = 0;
break;
}
}
}
}
/* The sender claims he has won the game. Starts a timeout. */
function claimWin(bytes32 gameId) notEnded(gameId) public {
var game = games[gameId];
// just the two players currently playing
if (msg.sender != game.player1 && msg.sender != game.player2)
throw;
// only if timeout has not started
if (game.timeoutState != 0)
throw;
// you can only claim draw / victory in the enemies turn
if (msg.sender == game.nextPlayer)
throw;
game.timeoutStarted = now;
game.timeoutState = 1;
GameTimeoutStarted(gameId, game.timeoutStarted, game.timeoutState);
}
/* The sender offers the other player a draw. Starts a timeout. */
function offerDraw(bytes32 gameId) notEnded(gameId) public {
var game = games[gameId];
// just the two players currently playing
if (msg.sender != game.player1 && msg.sender != game.player2)
throw;
// only if timeout has not started or is a draw by nextPlayer
if (game.timeoutState != 0 && game.timeoutState != 2)
throw;
// if state = timeout, timeout has to be 2*timeoutTime
if (game.timeoutState == 2 && now < game.timeoutStarted + 2 * game.turnTime * 1 minutes)
throw;
if (msg.sender == game.nextPlayer) {
game.timeoutState = -2;
} else {
game.timeoutState = -1;
}
game.timeoutStarted = now;
GameTimeoutStarted(gameId, game.timeoutStarted, game.timeoutState);
}
/*
* The sender claims that the other player is not in the game anymore.
* Starts a Timeout that can be claimed
*/
function claimTimeout(bytes32 gameId) notEnded(gameId) public {
var game = games[gameId];
// just the two players currently playing
if (msg.sender != game.player1 && msg.sender != game.player2)
throw;
// only if timeout has not started
if (game.timeoutState != 0)
throw;
// you can only claim draw / victory in the enemies turn
if (msg.sender == game.nextPlayer)
throw;
game.timeoutStarted = now;
game.timeoutState = 2;
GameTimeoutStarted(gameId, game.timeoutStarted, game.timeoutState);
}
/*
* The sender (waiting player) rejects the draw offered by the
* other (turning / current) player.
*/
function rejectCurrentPlayerDraw(bytes32 gameId) notEnded(gameId) public {
var game = games[gameId];
// just the two players currently playing
if (msg.sender != game.player1 && msg.sender != game.player2)
throw;
// only if timeout is present
if (game.timeoutState != -2)
throw;
// only not playing player is able to reject a draw offer of the nextPlayer
if (msg.sender == game.nextPlayer)
throw;
game.timeoutState = 0;
GameDrawOfferRejected(gameId);
}
/* The sender claims a previously started timeout. */
function claimTimeoutEnded(bytes32 gameId) notEnded(gameId) public {
var game = games[gameId];
// just the two players currently playing
if (msg.sender != game.player1 && msg.sender != game.player2)
throw;
if (game.timeoutState == 0 || game.timeoutState == 2)
throw;
if (now < game.timeoutStarted + game.turnTime * 1 minutes)
throw;
if (msg.sender == game.nextPlayer) {
if (game.timeoutState == -2) { // draw
game.ended = true;
games[gameId].player1Winnings = games[gameId].pot / 2;
games[gameId].player2Winnings = games[gameId].pot / 2;
games[gameId].pot = 0;
GameEnded(gameId);
} else {
throw;
}
} else {
if (game.timeoutState == -1) { // draw
game.ended = true;
games[gameId].player1Winnings = games[gameId].pot / 2;
games[gameId].player2Winnings = games[gameId].pot / 2;
games[gameId].pot = 0;
GameEnded(gameId);
} else if (game.timeoutState == 1){ // win
game.ended = true;
game.winner = msg.sender;
if(msg.sender == game.player1) {
games[gameId].player1Winnings = games[gameId].pot;
games[gameId].pot = 0;
} else {
games[gameId].player2Winnings = games[gameId].pot;
games[gameId].pot = 0;
}
GameEnded(gameId);
} else {
throw;
}
}
}
/* A timeout can be confirmed by the non-initializing player. */
function confirmGameEnded(bytes32 gameId) notEnded(gameId) public {
var game = games[gameId];
// just the two players currently playing
if (msg.sender != game.player1 && msg.sender != game.player2)
throw;
if (game.timeoutState == 0)
throw;
if (msg.sender != game.nextPlayer) {
if (game.timeoutState == -2) { // draw
game.ended = true;
games[gameId].player1Winnings = games[gameId].pot / 2;
games[gameId].player2Winnings = games[gameId].pot / 2;
games[gameId].pot = 0;
GameEnded(gameId);
} else {
throw;
}
} else {
if (game.timeoutState == -1) { // draw
game.ended = true;
games[gameId].player1Winnings = games[gameId].pot / 2;
games[gameId].player2Winnings = games[gameId].pot / 2;
games[gameId].pot = 0;
GameEnded(gameId);
} else if (game.timeoutState == 1 || game.timeoutState == 2) { // win
game.ended = true;
if(msg.sender == game.player1) {
game.winner = game.player2;
games[gameId].player2Winnings = games[gameId].pot;
games[gameId].pot = 0;
} else {
game.winner = game.player1;
games[gameId].player1Winnings = games[gameId].pot;
games[gameId].pot = 0;
}
GameEnded(gameId);
} else {
throw;
}
}
}
function TurnBasedGame(bool enableDebugging) {
debug = enableDebugging;
head = 'end';
}
}
|
The sender claims that the other player is not in the game anymore. Starts a Timeout that can be claimed/ just the two players currently playing only if timeout has not started you can only claim draw / victory in the enemies turn
|
function claimTimeout(bytes32 gameId) notEnded(gameId) public {
var game = games[gameId];
if (msg.sender != game.player1 && msg.sender != game.player2)
throw;
if (game.timeoutState != 0)
throw;
if (msg.sender == game.nextPlayer)
throw;
game.timeoutStarted = now;
game.timeoutState = 2;
GameTimeoutStarted(gameId, game.timeoutStarted, game.timeoutState);
}
| 2,536,668
|
./full_match/7001/0x22A13bf48c252Af78Eb418D5F41A77352e116107/sources/@zetachain/protocol-contracts/contracts/evm/interfaces/ZetaInterfaces.sol
|
ZetaTokenConsumer makes it easier to handle the following situations: - Getting Zeta using native coin (to pay for destination gas while using `connector.send`) - Getting Zeta using a token (to pay for destination gas while using `connector.send`) - Getting native coin using Zeta (to return unused destination gas when `onZetaRevert` is executed) - Getting a token using Zeta (to return unused destination gas when `onZetaRevert` is executed) The interface can be implemented using different strategies, like UniswapV2, UniswapV3, etc/
|
interface ZetaTokenConsumer {
event EthExchangedForZeta(uint256 amountIn, uint256 amountOut);
event TokenExchangedForZeta(address token, uint256 amountIn, uint256 amountOut);
event ZetaExchangedForEth(uint256 amountIn, uint256 amountOut);
event ZetaExchangedForToken(address token, uint256 amountIn, uint256 amountOut);
function getZetaFromEth(address destinationAddress, uint256 minAmountOut) external payable returns (uint256);
function getZetaFromToken(
address destinationAddress,
uint256 minAmountOut,
address inputToken,
uint256 inputTokenAmount
) external returns (uint256);
function getEthFromZeta(
address destinationAddress,
uint256 minAmountOut,
uint256 zetaTokenAmount
) external returns (uint256);
function getTokenFromZeta(
address destinationAddress,
uint256 minAmountOut,
address outputToken,
uint256 zetaTokenAmount
) external returns (uint256);
function hasZetaLiquidity() external view returns (bool);
}
}
| 13,228,776
|
./partial_match/1/0x7497C39F11d2b39b4eF3dBB1e9A9857Df6FD5BdC/sources/SuperChoice.sol
|
get time since last sell measured in 2 week increments protection in case someone tries to use a contract to facilitate buys/sells cap the sell factor cooldown to 14 weeks and 50% of sell tax
|
function getHolderSellFactor(address holder) public view returns (uint256){
uint256 timeSinceLastSale = (block.timestamp.sub(_holderLastSellDate[holder])).div(2 weeks);
if(_holderLastSellDate[holder] == 0){
return sellFeeIncreaseFactor;
}
if(timeSinceLastSale >= 7){
}
}
| 4,333,653
|
/**
*Submitted for verification at Etherscan.io on 2021-04-23
*/
pragma solidity 0.6.6;
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) {
// 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.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
interface IToken {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function intervalLength() external returns (uint256);
function owner() external view returns (address);
function burn(uint256 _amount) external;
function renounceMinter() external;
function mint(address account, uint256 amount) external returns (bool);
function lock(
address recipient,
uint256 amount,
uint256 blocks,
bool deposit
) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function transfer(address to, uint256 amount) external returns (bool success);
}
interface IDutchAuction {
function auctionEnded() external view returns (bool);
function finaliseAuction() external;
}
interface IDutchSwapFactory {
function deployDutchAuction(
address _token,
uint256 _tokenSupply,
uint256 _startDate,
uint256 _endDate,
address _paymentCurrency,
uint256 _startPrice,
uint256 _minimumPrice,
address _wallet
) external returns (address dutchAuction);
}
interface IPriceOracle {
function consult(uint256 amountIn) external view returns (uint256 amountOut);
function update() external;
}
contract AuctionManager {
using SafeMath for uint256;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
// used as factor when dealing with %
uint256 constant ACCURACY = 1e4;
// when 95% at market price, start selling
uint256 public sellThreshold;
// cap auctions at certain amount of $TRDL minted
uint256 public dilutionBound;
// stop selling when volume small
// uint256 public dustThreshold; set at dilutionBound / 52
// % start_price above estimate, and % min_price below estimate
uint256 public priceSpan;
// auction duration
uint256 public auctionDuration;
IToken private strudel;
IToken private vBtc;
IToken private gStrudel;
IPriceOracle private btcPriceOracle;
IPriceOracle private vBtcPriceOracle;
IPriceOracle private strudelPriceOracle;
IDutchSwapFactory private auctionFactory;
IDutchAuction public currentAuction;
mapping(address => uint256) public lockTimeForAuction;
constructor(
address _strudelAddr,
address _gStrudel,
address _vBtcAddr,
address _btcPriceOracle,
address _vBtcPriceOracle,
address _strudelPriceOracle,
address _auctionFactory
) public {
strudel = IToken(_strudelAddr);
gStrudel = IToken(_gStrudel);
vBtc = IToken(_vBtcAddr);
btcPriceOracle = IPriceOracle(_btcPriceOracle);
vBtcPriceOracle = IPriceOracle(_vBtcPriceOracle);
strudelPriceOracle = IPriceOracle(_strudelPriceOracle);
auctionFactory = IDutchSwapFactory(_auctionFactory);
sellThreshold = 9500; // vBTC @ 95% of BTC price or above
dilutionBound = 70; // 0.7% of $TRDL total supply
priceSpan = 2500; // 25%
auctionDuration = 84600; // ~23,5h
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function _getDiff(uint256 a, uint256 b) internal pure returns (uint256) {
if (a > b) {
return a - b;
}
return b - a;
}
function decimals() public view returns (uint8) {
return gStrudel.decimals();
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return gStrudel.totalSupply();
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view returns (uint256) {
return gStrudel.balanceOf(account);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(strudel.owner() == msg.sender, "Ownable: caller is not the owner");
_;
}
function updateOracles() public {
try btcPriceOracle.update() {
// do nothing
} catch Error(string memory) {
// do nothing
} catch (bytes memory) {
// do nothing
}
try vBtcPriceOracle.update() {
// do nothing
} catch Error(string memory) {
// do nothing
} catch (bytes memory) {
// do nothing
}
try strudelPriceOracle.update() {
// do nothing
} catch Error(string memory) {
// do nothing
} catch (bytes memory) {
// do nothing
}
}
function rotateAuctions() external {
if (address(currentAuction) != address(0)) {
require(currentAuction.auctionEnded(), "previous auction hasn't ended");
try currentAuction.finaliseAuction() {
// do nothing
} catch Error(string memory) {
// do nothing
} catch (bytes memory) {
// do nothing
}
uint256 studelReserves = strudel.balanceOf(address(this));
if (studelReserves > 0) {
strudel.burn(studelReserves);
}
}
updateOracles();
// get prices
uint256 btcPriceInEth = btcPriceOracle.consult(1e18);
uint256 vBtcPriceInEth = vBtcPriceOracle.consult(1e18);
uint256 strudelPriceInEth = strudelPriceOracle.consult(1e18);
// measure outstanding supply
uint256 vBtcOutstandingSupply = vBtc.totalSupply();
uint256 strudelSupply = strudel.totalSupply();
uint256 vBtcAmount = vBtc.balanceOf(address(this));
vBtcOutstandingSupply -= vBtcAmount;
// calculate vBTC supply imbalance in ETH
uint256 imbalance = _getDiff(btcPriceInEth, vBtcPriceInEth).mul(vBtcOutstandingSupply);
uint256 cap = strudelSupply.mul(dilutionBound).mul(strudelPriceInEth).div(ACCURACY);
// cap by dillution bound
imbalance = min(
cap,
imbalance
);
// pause if imbalance below dust threshold
if (imbalance.div(strudelPriceInEth) < strudelSupply.mul(dilutionBound).div(52).div(ACCURACY)) {
// pause auctions
currentAuction = IDutchAuction(address(0));
return;
}
// determine what kind of auction we want
uint256 priceRelation = btcPriceInEth.mul(ACCURACY).div(vBtcPriceInEth);
if (priceRelation < ACCURACY.mul(ACCURACY).div(sellThreshold)) {
// cap vBtcAmount by imbalance in vBTC
vBtcAmount = min(vBtcAmount, imbalance.div(vBtcPriceInEth));
// calculate vBTC price
imbalance = vBtcPriceInEth.mul(1e18).div(strudelPriceInEth);
// auction off some vBTC
vBtc.approve(address(auctionFactory), vBtcAmount);
currentAuction = IDutchAuction(
auctionFactory.deployDutchAuction(
address(vBtc),
vBtcAmount,
now,
now + auctionDuration,
address(strudel),
imbalance.mul(ACCURACY.add(priceSpan)).div(ACCURACY), // startPrice
imbalance.mul(ACCURACY.sub(priceSpan)).div(ACCURACY), // minPrice
address(this)
)
);
} else {
// calculate price in vBTC
vBtcAmount = strudelPriceInEth.mul(1e18).div(vBtcPriceInEth);
// auction off some $TRDL
currentAuction = IDutchAuction(
auctionFactory.deployDutchAuction(
address(this),
imbalance.div(strudelPriceInEth), // calculate imbalance in $TRDL
now,
now + auctionDuration,
address(vBtc),
vBtcAmount.mul(ACCURACY.add(priceSpan)).div(ACCURACY), // startPrice
vBtcAmount.mul(ACCURACY.sub(priceSpan)).div(ACCURACY), // minPrice
address(this)
)
);
// if imbalance >= dillution bound, use max lock (52 weeks)
// if imbalance < dillution bound, lock shorter
lockTimeForAuction[address(currentAuction)] = gStrudel.intervalLength().mul(52).mul(imbalance).div(cap);
}
}
function setSellThreshold(uint256 _threshold) external onlyOwner {
require(_threshold >= 6000, "threshold below 60% minimum");
require(_threshold <= 12000, "threshold above 120% maximum");
sellThreshold = _threshold;
}
function setDulutionBound(uint256 _dilutionBound) external onlyOwner {
require(_dilutionBound <= 1000, "dilution bound above 10% max value");
dilutionBound = _dilutionBound;
}
function setPriceSpan(uint256 _priceSpan) external onlyOwner {
require(_priceSpan > 1000, "price span should have at least 10%");
require(_priceSpan < ACCURACY, "price span larger accuracy");
priceSpan = _priceSpan;
}
function setAuctionDuration(uint256 _auctionDuration) external onlyOwner {
require(_auctionDuration >= 3600, "auctions should run at laest for 1 hour");
require(_auctionDuration <= 604800, "auction duration should be less than week");
auctionDuration = _auctionDuration;
}
function renounceMinter() external onlyOwner {
strudel.renounceMinter();
}
function swipe(address tokenAddr) external onlyOwner {
IToken token = IToken(tokenAddr);
token.transfer(strudel.owner(), token.balanceOf(address(this)));
}
// In deployDutchAuction, approve and transferFrom are called
// In initDutchAuction, transferFrom is called again
// In DutchAuction, transfer is called to either payout, or return money to AuctionManager
function transferFrom(address, address, uint256) public pure returns (bool) {
return true;
}
function approve(address, uint256) public pure returns (bool) {
return true;
}
function transfer(address to, uint256 amount) public returns (bool success) {
// require sender is our Auction
address auction = msg.sender;
require(lockTimeForAuction[auction] > 0, "Caller is not our auction");
// if recipient is AuctionManager, it means we are doing a refund -> do nothing
if (to == address(this)) return true;
uint256 blocks = lockTimeForAuction[auction];
strudel.mint(address(this), amount);
strudel.approve(address(gStrudel), amount);
gStrudel.lock(to, amount, blocks, false);
return true;
}
}
|
See {IERC20-totalSupply}./
|
function totalSupply() public view returns (uint256) {
return gStrudel.totalSupply();
}
| 7,746,183
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title A base MisBlock token contract
/// @author Anderson L
/// @notice This contract is inherited by MisBlockETH and MisBlockBSC token contracts.
/// @dev All functions requiring onlyOwner are also pausable.
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import '@openzeppelin/contracts/access/Ownable.sol';
import "@openzeppelin/contracts/utils/Address.sol";
import '@openzeppelin/contracts/security/Pausable.sol';
import "./interfaces/UniswapInterfaces.sol";
contract MisBlockBase is ERC20, Pausable, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _tokenAllowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0) / 1000;
uint256 private _tTotal = 0;
uint256 private _rTotal = 0;
uint256 private _tFeeTotal;
uint256 public deployTime = block.timestamp;
uint256 public taxFee;
uint256 public liquidityFee;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = true;
mapping (address => bool) private _isMintAvailable;
address[] private _mintAvailableAddresses;
mapping (address => bool) private _isBurnAvailable;
address[] private _burnAvailableAddresses;
// Should re-set following 2 values as our token's requirement.
uint256 public maxTxAmount = 5000000 ether;
uint256 private constant TOKEN_SELL_TO_LIQUIDITY = 500000 ether;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
event TransferForVesting(address recipient, uint256 amount);
event Mint(address account, uint256 amount);
event AllocateVesting(address indexed vestingContract, uint256 amount, uint256 timestamp);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
struct LockFund {
uint256 amount;
uint256 releasetime;
}
mapping (address => bool) public isSwapAddress;
address[] public swapAddresses;
mapping (address => LockFund[]) private _lockFundsArray;
/// @notice Constructor. The token name is UNICOIN and the symbol name is UNICN.
/// @dev Should input swapaddress as PCS router address in BSC contract and UNISWAP router addres in ETH contract.
/// @param swapaddress An address of pcs or uniswap router contract.
/// @param initialMintAmount An address of pcs or uniswap router contract.
constructor(address swapaddress, uint256 initialMintAmount) ERC20("UNICOIN", "UNICN") {
_tTotal = initialMintAmount;
_rTotal = MAX.sub(MAX.mod(_tTotal));
_rOwned[_msgSender()] = _rTotal;
// Uniswap Address should be in SwapAddress list
isSwapAddress[swapaddress] = true;
swapAddresses.push(swapaddress);
// Owner should be in burn/mint available list
_isMintAvailable[_msgSender()] = true;
_mintAvailableAddresses.push(_msgSender());
_isBurnAvailable[_msgSender()] = true;
_burnAvailableAddresses.push(_msgSender());
//exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(swapaddress);
// set the rest of the contract variables
uniswapV2Router = _uniswapV2Router;
// Create a uniswap pair for this new token
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
emit Transfer(address(0), _msgSender(), _tTotal);
}
/**
* @notice Throws if called by any account other than mint available addresses.
*/
modifier onlyMintAvailable() {
require(_isMintAvailable[_msgSender()], "caller is not in the mint available list");
_;
}
/**
* @notice Throws if called by any account other than burn available addresses.
*/
modifier onlyBurnAvailable() {
require(_isBurnAvailable[_msgSender()], "caller is not in the burn available list");
_;
}
/**
* @notice add mint available address
*/
function addMintAvailableAddress(address account) external onlyOwner whenNotPaused {
require(!_isMintAvailable[account], "Account is already in list of mint available addresses");
_isMintAvailable[account] = true;
_mintAvailableAddresses.push(account);
}
/**
* @notice remove mint available address
*/
function removeMintAvailableAddress(address account) external onlyOwner whenNotPaused {
require(_isMintAvailable[account] == true, "Account is not in list of mint available addresses");
for (uint256 i = 0; i < _mintAvailableAddresses.length; i++) {
if (_mintAvailableAddresses[i] == account) {
_mintAvailableAddresses[i] = _mintAvailableAddresses[_mintAvailableAddresses.length - 1];
_isMintAvailable[account] = false;
_mintAvailableAddresses.pop();
break;
}
}
}
/**
* @notice add burn available address
*/
function addBurnAvailableAddress(address account) external onlyOwner whenNotPaused {
require(!_isBurnAvailable[account], "Account is already in list of burn available addresses");
_isBurnAvailable[account] = true;
_burnAvailableAddresses.push(account);
}
/**
* @notice remove burn available address
*/
function removeBurnAvailableAddress(address account) external onlyOwner whenNotPaused {
require(_isBurnAvailable[account] == true, "Account is not in list of burn available addresses");
for (uint256 i = 0; i < _burnAvailableAddresses.length; i++) {
if (_burnAvailableAddresses[i] == account) {
_burnAvailableAddresses[i] = _burnAvailableAddresses[_burnAvailableAddresses.length - 1];
_isBurnAvailable[account] = false;
_burnAvailableAddresses.pop();
break;
}
}
}
/// @notice We are despositing 1T tokens initially and allowing to mint 9T tokens more. This function can be called by only owner.
function mint(address account, uint256 amount) external onlyMintAvailable whenNotPaused {
_mint(account, amount);
emit Mint(account, amount);
}
/// @dev We should check reflection value should not be overr uint256's max value.
function _mint(address account, uint256 amount) internal override virtual {
require(account != address(0), "ERC20: mint to the zero address");
(uint256 rAmount,,,,,) = _getValues(amount);
require((~uint256(0) - rAmount) > _rTotal , "Mint value is exceeded limitation");
_rOwned[account] = _rOwned[account].add(rAmount);
if(_isExcluded[account]) {
_tOwned[account] = _tOwned[account].add(amount);
}
_rTotal += rAmount;
_tTotal += amount;
}
/// @notice Getting totalSupply.
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
/**
* @notice Getting balance of the account.
* @dev Checking the account is including in Reward List or not.
*/
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
/**
* @dev Checking whether the account is contract address or not.
*/
// function isContract(address account) internal view returns (bool) {
// uint32 size;
// assembly {
// size := extcodesize(account)
// }
// return (size > 0);
// }
/**
* @notice This function is standard transfer function.
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Taking fees and set timelock by proper logic.
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transferBase(_msgSender(), recipient, amount);
return true;
}
/**
* @notice This function is to getting allowance of spender.
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `sender` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address sender, address spender) public view override returns (uint256) {
return _tokenAllowances[sender][spender];
}
/**
* @notice This function is to approve transfer.
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) public override returns (bool) {
_approveBase(_msgSender(), spender, amount);
return true;
}
/**
* @notice This function is for delegating transfer.
* @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) public override returns (bool) {
require(sender != recipient, "sender and recipient is same address");
_transferBase(sender, recipient, amount);
_approveBase(sender, _msgSender(), _tokenAllowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @notice This function is to increase allowance.
* @dev Adds `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits an {Approval} event.
*/
function increaseAllowance(address spender, uint256 addedValue) public override virtual returns (bool) {
_approveBase(_msgSender(), spender, _tokenAllowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @notice This function is to decrease allowance.
* @dev Subs `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits an {Approval} event.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public override virtual returns (bool) {
_approveBase(_msgSender(), spender, _tokenAllowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @notice This function is to check whether the account is excluded from reward or not.
* @dev Check the account is excluded from reward or not.
*
* Returns a boolean value indicating whether the account is excluded from reward or not.
*
*/
function isExcludedFromReward(address account) external view returns (bool) {
return _isExcluded[account];
}
/**
* @notice Get total Fees taken by taxes.
*/
function totalFees() external view returns (uint256) {
return _tFeeTotal;
}
/**
* @notice This function is to deliver tokens to account holders.
*/
function deliver(uint256 tAmount) external {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
/**
* @notice Getting reflection value from token value.
*/
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) external view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
/**
* @notice Getting token value from reflection value.
*/
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
/**
* @notice exclude the account from the reward list.
*
* Must be called from only owner.
*
*/
function excludeFromReward(address account) external onlyOwner whenNotPaused {
// require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
/**
* @notice include the account into the reward list.
*
* Must be called from only owner.
*
*/
function includeInReward(address account) external onlyOwner whenNotPaused {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
/**
* @notice exclude the account from the taking fee. taxes are not applied for accounts from this list.
*
* Must be called from only owner.
*
*/
function excludeFromFee(address account) external onlyOwner whenNotPaused {
_isExcludedFromFee[account] = true;
}
/**
* @notice include the account into the taking fee. taxes would be applied for accounts from this list.
*
* Must be called from only owner.
*
*/
function includeInFee(address account) external onlyOwner {
_isExcludedFromFee[account] = false;
}
/**
* @notice setting maximum transfer amount as percentage.
*
* Must be called from only owner.
*
*/
function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner whenNotPaused {
maxTxAmount = _tTotal.mul(maxTxPercent).div(
10**2
);
}
/**
* @notice enable/disable Swap and Liquidity feature.
*
* Must be called from only owner.
*
*/
function setSwapAndLiquifyEnabled(bool enabled) external onlyOwner whenNotPaused {
swapAndLiquifyEnabled = enabled;
emit SwapAndLiquifyEnabledUpdated(enabled);
}
/**
* @notice burn tokens from the account.
*
* Must be called from only owner.
*
*/
function burn(address account, uint256 tAmount) external onlyBurnAvailable whenNotPaused {
uint256 burnerBalance = balanceOf(account);
require(burnerBalance >= tAmount, "Burnning amount is exceed balance");
(uint256 rAmount, , , , , ) = _getValues(tAmount);
_rOwned[account] = _rOwned[account].sub(rAmount);
if(_isExcluded[account]) {
_tOwned[account] = _tOwned[account].sub(tAmount);
}
_rTotal = _rTotal.sub(rAmount);
_tTotal = _tTotal.sub(tAmount);
}
/**
* @dev Inspired from Reflect Finance concept.
* to recieve ETH from uniswapV2Router when swaping
*/
receive() external payable {}
/**
* @dev applying fees. called by transfer functions.
*
* Internal function.
*
*/
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
/**
* @dev Internal function to get values related with reflection feature based on transfer amount.
* - rAmount : reflection amount for tAmount
* - rTransferAmount : reflection amount for tTransferAmount
* - rFee : reflection amount for tFee
* - tTransferAmount : transfer amount without all taxes(fee and liquidity)
* - tFee : tax fee for account holders
* - tLiquidity : tax fee for liquidity
*/
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity);
}
/**
* @dev Internal function to get token values based on transfer amount. called by {_getValues}
* - tTransferAmount : transfer amount without all taxes(fee and liquidity)
* - tFee : tax fee for account holders
* - tLiquidity : tax fee for liquidity
*/
function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) {
uint256 tFee = calculateTaxFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity);
return (tTransferAmount, tFee, tLiquidity);
}
/**
* @dev Internal function to get reflection values based on token values. called by {_getValues}
* - rAmount : reflection amount for tAmount
* - rTransferAmount : reflection amount for tTransferAmount
* - rFee : reflection amount for tFee
*/
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rLiquidity = tLiquidity.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity);
return (rAmount, rTransferAmount, rFee);
}
/**
* @dev Internal function to get rate between token and reflection value
*/
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
/**
* @dev Internal function to get total Supply of token and reflection. called by {_getRate}
*/
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
/**
* @dev Internal function to to apply liquidity fee.
*/
function _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}
/**
* @dev Internal function to calculate tax fee. Used 1000 instead of 100 for max percent to avoid decimals. For example, 7.5% will be calculated by 75/1000
*/
function calculateTaxFee(uint256 amount) private view returns (uint256) {
return amount.mul(taxFee).div(
10**3
);
}
/**
* @dev Internal function to calculate liquidity fee. Used 1000 instead of 100 for max percent to avoid decimals. For example, 7.5% will be calculated by 75/1000
*/
function calculateLiquidityFee(uint256 amount) private view returns (uint256) {
return amount.mul(liquidityFee).div(
10**3
);
}
/**
* @dev Internal function to set tax fees.
* First Month : 7.5%, Second Month : 5%, Third Month : 2.5%, From Fourth Month : 0
*/
function _setTaxFee(bool takeFee) private {
if (!takeFee) {
taxFee = 0;
liquidityFee = 0;
} else if ( block.timestamp < deployTime + 30 days) {
taxFee = 75;
liquidityFee = 75;
} else if ( block.timestamp < deployTime + 60 days) {
taxFee = 50;
liquidityFee = 50;
} else if ( block.timestamp < deployTime + 90 days) {
taxFee = 25;
liquidityFee = 25;
} else {
taxFee = 0;
liquidityFee = 0;
}
}
/**
* @notice Checking whether the address is excluded from fee or not
*/
function isExcludedFromFee(address account) external view returns(bool) {
return _isExcludedFromFee[account];
}
/**
* @dev Internal function to approve.
* Emits a {Approval} event.
*/
function _approveBase(address sender, address spender, uint256 amount) private {
require(sender != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_tokenAllowances[sender][spender] = amount;
emit Approval(sender, spender, amount);
}
/**
* @dev Internal function for standard transfer.
*/
function _transferBase(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(from != owner() && to != owner())
require(amount <= maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
uint256 senderBalance = balanceOf(from);
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
//indicates if fee should be deducted from transfer
bool takeFee = true;
//if from address is not in SwapAddress list, not taking fee
if(!isSwapAddress[from]){
takeFee = false;
}
//if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
//it will check timelock
_beforeTokenTransferBase(from, amount);
//transfer amount, it will take tax, burn, liquidity fee
_tokenTransfer(from,to,amount,takeFee);
//it will calculate timelock
_afterTokenTransferBase(from, to, amount);
// is the token balance of this contract address over the min number of
// tokens that we need to initiate a swap + liquidity lock?
// also, don't get caught in a circular liquidity event.
// also, don't swap & liquify if sender is uniswap pair.
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= maxTxAmount)
{
contractTokenBalance = maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= TOKEN_SELL_TO_LIQUIDITY;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
from != uniswapV2Pair &&
swapAndLiquifyEnabled
) {
contractTokenBalance = TOKEN_SELL_TO_LIQUIDITY;
//add liquidity
swapAndLiquify(contractTokenBalance);
}
}
/**
* @dev Internal function of swap feature.
* Emits {SwapAndLiquify}
*/
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
// split the contract balance into halves
uint256 half = contractTokenBalance.div(2);
uint256 otherHalf = contractTokenBalance.sub(half);
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered
// how much ETH did we just swap into?
uint256 newBalance = address(this).balance.sub(initialBalance);
// add liquidity to uniswap
addLiquidity(otherHalf, newBalance);
}
/**
* @dev Internal function for swapTokensForEth.
*/
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approveBase(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
/**
* @dev Internal function for addLiquidity.
*/
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approveBase(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
(uint token, uint eth, uint liquidity) = uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
owner(),
block.timestamp
);
emit SwapAndLiquify(token, eth, liquidity);
}
/**
* @dev Internal function of transfer.
* this method is responsible for taking all fee, if takeFee is true
*/
function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {
_setTaxFee(takeFee);
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
}
/**
* @dev called in case of both of sender and recipient are in reward list.
*/
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
/**
* @dev called in case of only sender is in reward list.
*/
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
/**
* @dev called in case of only recipient is in reward list.
*/
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
/**
* @dev called in case of both are not in reward list.
*/
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
/**
* @notice getting the list of addresses set as applying timelock from. All tokens transfered from addresses of this list is time locked by proper logic.
*/
function getSwapAddresses() external view returns (address[] memory){
return swapAddresses;
}
/**
* @notice add swap address
*/
function addSwapAddress(address account) external onlyOwner whenNotPaused {
require(!isSwapAddress[account], "Account is already in list of swap addresses");
isSwapAddress[account] = true;
swapAddresses.push(account);
}
/**
* @notice remove swap address
*/
function removeSwapAddress(address account) external onlyOwner whenNotPaused {
require(isSwapAddress[account] == true, "Account is not in list of swap addresses");
for (uint256 i = 0; i < swapAddresses.length; i++) {
if (swapAddresses[i] == account) {
swapAddresses[i] = swapAddresses[swapAddresses.length - 1];
isSwapAddress[account] = false;
swapAddresses.pop();
break;
}
}
}
/**
* @dev Internal function to be called before token transfer.
* Check time locked funds.
* If the address is having 1000 tokens. And 500 tokens were time locked.
* At this point if the account wants to transfer 600 tokens, then it will be reverted since the user is having only 500 tokens available.
*/
function _beforeTokenTransferBase(
address from,
uint256 amount
) private view {
LockFund[] storage lockFunds = _lockFundsArray[from];
if(lockFunds.length < 1) return;
uint256 lockedFundsSum = 0;
for (uint i = 0; i < lockFunds.length; i++) {
if(lockFunds[i].releasetime > block.timestamp)
{
lockedFundsSum += lockFunds[i].amount;
}
}
require(balanceOf(from) - lockedFundsSum >= amount, "Some of your balances were locked. And you don't have enough unlocked balance for this transaction.");
}
/**
* @dev Internal function to be called after token transfer.
* Applying time lock against tokens transferred from addresses in the timelock list
*/
function _afterTokenTransferBase(
address from,
address to,
uint256 amount
) private {
if(!isSwapAddress[from]) return;
LockFund[] storage lockFunds = _lockFundsArray[to];
lockFunds.push(LockFund(amount.div(10), block.timestamp + 1 days));
for (uint256 i = 1; i < 10; i++) {
lockFunds.push(LockFund(amount.div(10), block.timestamp + 1 days + i * 1 weeks));
}
}
}
|
We are despositing 1T tokens initially and allowing to mint 9T tokens more. This function can be called by only owner.
|
function mint(address account, uint256 amount) external onlyMintAvailable whenNotPaused {
_mint(account, amount);
emit Mint(account, amount);
}
| 5,426,022
|
./full_match/1/0xE0fC587E1F56b5968a7d5DC3667bA1f385fddb38/sources/contracts/TermRepoCollateralManager.sol
|
A helper function to validate various conditions required to liquidate return A boolean for whether borrower position eligible for full liquidation solhint-disable-next-line not-rely-on-time
|
function _validateBatchLiquidationForFullLiquidation(
address borrower,
address liquidator,
uint256[] calldata closureTokenAmounts
) internal returns (bool) {
if (block.timestamp > termRepoServicer.endOfRepurchaseWindow()) {
revert ShortfallLiquidationsClosed();
}
if (liquidator == borrower) {
revert SelfLiquidationNotPermitted();
}
if (collateralTokens.length != closureTokenAmounts.length) {
revert InvalidParameters(
"Closure amounts array not same length as collateral tokens list"
);
}
uint256 borrowerRepurchaseObligation = termRepoServicer
.getBorrowerRepurchaseObligation(borrower);
if (borrowerRepurchaseObligation == 0) {
revert ZeroBorrowerRepurchaseObligation();
}
bool allowFullLiquidation = getCollateralMarketValue(borrower) <
termPriceOracle
.usdValueOfTokens(purchaseToken, borrowerRepurchaseObligation)
.mantissa +
deMinimisMarginThreshold;
if (!allowFullLiquidation && !isBorrowerInShortfall(borrower)) {
revert BorrowerNotInShortfall();
}
return allowFullLiquidation;
}
| 9,687,147
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../IController.sol";
import "../../interfaces/MStable.sol";
/*
A strategy must implement the following calls;
- deposit()
- withdraw(address) must exclude any tokens used in the yield - Controller role - withdraw should return to Controller
- withdraw(uint) - Controller | Vault role - withdraw should always return to vault
- withdrawAll() - Controller | Vault role - withdraw should always return to vault
- balanceOf()
Where possible, strategies must remain as immutable as possible, instead of updating variables, we update the contract by linking it in the controller
*/
contract StrategyMStableSavingsUSDC {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address constant public want = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
address constant public mUSD = address(0xe2f2a5C287993345a840Db3B0845fbC70f5935a5);
address constant public mSave = address(0xcf3F73290803Fc04425BEE135a4Caeb2BaB2C2A1);
address public governance;
address public controller;
uint public fee = 50;
uint constant public max = 10000;
constructor(address _controller) public {
governance = msg.sender;
controller = _controller;
}
function getName() external pure returns (string memory) {
return "StrategyMStableSavingsUSDC";
}
function deposit() external {
uint _want = IERC20(want).balanceOf(address(this));
if (_want > 0) {
IERC20(want).safeApprove(address(mUSD), 0);
IERC20(want).safeApprove(address(mUSD), _want);
MStable(mUSD).mint(want, _want);
}
uint _musd = IERC20(mUSD).balanceOf(address(this));
if (_musd > 0) {
IERC20(mUSD).safeApprove(address(mSave), 0);
IERC20(mUSD).safeApprove(address(mSave), _musd);
mSavings(mSave).depositSavings(_musd);
}
}
function setFee(uint _fee) external {
require(msg.sender == governance, "!governance");
fee = _fee;
}
// Controller only function for creating additional rewards from dust
function withdraw(IERC20 _asset) external returns (uint balance) {
require(msg.sender == controller, "!controller");
require(address(_asset) != address(mUSD), "!musd");
require(address(_asset) != address(want), "!want");
balance = _asset.balanceOf(address(this));
_asset.safeTransfer(controller, balance);
}
// Withdraw partial funds, normally used with a vault withdrawal
function withdraw(uint _amount) external {
require(msg.sender == controller, "!controller");
uint _balance = IERC20(want).balanceOf(address(this));
if (_balance < _amount) {
_amount = _withdrawSome(_amount.sub(_balance));
_amount = _amount.add(_balance);
}
uint _fee = _amount.mul(fee).div(max);
IERC20(want).safeTransfer(IController(controller).rewards(), _fee);
address _vault = IController(controller).vaults(address(want));
require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds
IERC20(want).safeTransfer(_vault, _amount);
}
// Withdraw all funds, normally used when migrating strategies
function withdrawAll() external returns (uint balance) {
require(msg.sender == controller, "!controller");
_withdrawAll();
balance = IERC20(want).balanceOf(address(this));
address _vault = IController(controller).vaults(address(want));
require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds
IERC20(want).safeTransfer(_vault, balance);
}
function normalize(uint _amount) public view returns (uint) {
return _amount.mul(uint(10)**ERC20(want).decimals()).div(uint(10)**ERC20(mUSD).decimals());
}
function _withdrawAll() internal {
mSavings(mSave).redeem(mSavings(mSave).creditBalances(address(this)));
MStable(mUSD).redeem(want, normalize(IERC20(mUSD).balanceOf(address(this))));
}
function _withdrawSome(uint256 _amount) internal returns (uint) {
uint256 b = balanceSavings();
uint256 bT = balanceSavingsInToken();
require(bT >= _amount, "insufficient funds");
// can have unintentional rounding errors
uint256 amount = (b.mul(_amount.mul(1e12))).div(bT).add(1);
uint _before = IERC20(mUSD).balanceOf(address(this));
_withdrawSavings(amount);
uint _after = IERC20(mUSD).balanceOf(address(this));
uint _wBefore = IERC20(want).balanceOf(address(this));
MStable(mUSD).redeem(want, normalize(_after.sub(_before)));
uint _wAfter = IERC20(want).balanceOf(address(this));
return _wAfter.sub(_wBefore);
}
function balanceOf() public view returns (uint) {
return IERC20(want).balanceOf(address(this))
.add(normalize(IERC20(mUSD).balanceOf(address(this))))
.add(normalize(balanceSavingsInToken()));
}
function _withdrawSavings(uint amount) internal {
mSavings(mSave).redeem(amount);
}
function balanceSavingsInToken() public view returns (uint256) {
// Mantisa 1e18 to decimals
uint256 b = balanceSavings();
if (b > 0) {
b = b.mul(mSavings(mSave).exchangeRate()).div(1e18);
}
return b;
}
function balanceSavings() public view returns (uint256) {
return mSavings(mSave).creditBalances(address(this));
}
function setGovernance(address _governance) external {
require(msg.sender == governance, "!governance");
governance = _governance;
}
function setController(address _controller) external {
require(msg.sender == governance, "!governance");
controller = _controller;
}
}
|
Mantisa 1e18 to decimals
|
function balanceSavingsInToken() public view returns (uint256) {
uint256 b = balanceSavings();
if (b > 0) {
b = b.mul(mSavings(mSave).exchangeRate()).div(1e18);
}
return b;
}
| 1,845,977
|
./full_match/4/0x6Ee1f92c18182A905009405baDbcBac32B125883/sources/src/utils/MixedDecimal.sol
|
subtract SignedDecimal.signedDecimal by Decimal.decimal, using SignedSafeMath directly
|
function subD(SignedDecimal.signedDecimal memory x, Decimal.decimal memory y)
internal
pure
convertible(y)
returns (SignedDecimal.signedDecimal memory)
{
SignedDecimal.signedDecimal memory t;
t.d = x.d.sub(int256(y.d));
return t;
}
| 760,604
|
pragma solidity ^0.4.25;
pragma experimental ABIEncoderV2;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
// Flight status codees
uint8 private constant STATUS_CODE_UNKNOWN = 0;
uint8 private constant STATUS_CODE_ON_TIME = 10;
uint8 private constant STATUS_CODE_LATE_AIRLINE = 20;
uint8 private constant STATUS_CODE_LATE_WEATHER = 30;
uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40;
uint8 private constant STATUS_CODE_LATE_OTHER = 50;
// uint256 private constant MULTIPLIER = 1.5;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
struct Airline {
bool isRegistered;
bool isFunded;
address airlineAddress;
string name;
}
struct Candidate {
mapping(address => bool) voters;
uint256 noOfVotes;
bool exist;
}
address[] private registeredAirlines;
mapping(address => Airline) registeredAirlinesMapping;
mapping(address => Candidate) votes;
struct Flight {
bool isRegistered;
uint8 statusCode;
uint256 updatedTimestamp;
address airline;
}
mapping(bytes32 => Flight) private flights;
string[] public flightsList;
struct Insurance {
uint256 amount;
bytes32 flightKey;
bool isCredited;
bool isBought;
bool forPayment;
}
struct Passenger {
mapping(bytes32 => Insurance) insurances;
bool isRegistered;
uint256 balance;
}
mapping(address => Passenger) passengers;
address[] private passengersList;
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor(address _firstAirline) public {
contractOwner = msg.sender;
// deploy the first airline
registeredAirlinesMapping[_firstAirline] = Airline({
isRegistered: true,
isFunded: false,
airlineAddress: _firstAirline,
name: "First Airline"
});
}
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational() {
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner() {
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational() external view returns (bool) {
return operational;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus(bool mode) external requireContractOwner {
operational = mode;
}
function isRegisteredAirline(address _address)
external
view
returns (bool)
{
return registeredAirlinesMapping[_address].isRegistered;
}
function isFundedAirline(address _address) external view returns (bool) {
return registeredAirlinesMapping[_address].isFunded;
}
function getVotesOfAirline(address _address)
external
view
returns (uint256)
{
return votes[_address].noOfVotes;
}
function hasVotedAirline(address _address, address _voter)
external
view
returns (bool)
{
return votes[_address].voters[_voter];
}
function isRegisteredFlight(
string _flightName,
uint256 _timestamp,
address _airline
) external view returns (bool) {
bytes32 flightKey = getFlightKey(_airline, _flightName, _timestamp);
return flights[flightKey].isRegistered;
}
function isRegisteredPassenger(address _passenger)
public
view
returns (bool)
{
return passengers[_passenger].isRegistered;
}
function hasBoughtInsurance(bytes32 _flightKey, address _passenger)
public
view
returns (bool)
{
return passengers[_passenger].insurances[_flightKey].isBought;
}
function getInsurance(
address _airline,
string _flightName,
uint256 _timestamp,
address _passenger
)
public
view
returns (
uint256 amount,
bool isCredited,
bool isBought,
bytes32 flightKey,
bool isRegistered,
bool forPayment
)
{
isRegistered = passengers[_passenger].isRegistered;
Passenger passenger = passengers[_passenger];
bytes32 _flightKey = getFlightKey(_airline, _flightName, _timestamp);
Insurance memory insurance = passenger.insurances[_flightKey];
amount = insurance.amount;
isCredited = insurance.isCredited;
isBought = insurance.isBought;
flightKey = insurance.flightKey;
forPayment = insurance.forPayment;
}
function getFlightStatus(
address _airline,
string _flightName,
uint256 _timestamp
) external view returns (uint8 status) {
bytes32 _flightKey = getFlightKey(_airline, _flightName, _timestamp);
status = flights[_flightKey].statusCode;
}
function getFlightsList() external view returns (string[]) {
return flightsList;
}
function getAccountBalance(address _passenger)
external
view
returns (uint256)
{
return passengers[_passenger].balance;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline(
string _name,
bool _isFunded,
bool _isRegistered,
address _address
) external {
Airline memory newAirline = Airline({
name: _name,
isRegistered: _isRegistered,
isFunded: _isFunded,
airlineAddress: _address
});
// this should be called when the airline has paid the ante
//registeredAirlines.push(newAirline);
registeredAirlinesMapping[_address] = newAirline;
}
function getNumberOfRegiseteredAirlines() external view returns (uint256) {
return registeredAirlines.length;
}
function voteAirline(address _address, address _voter) external {
if (votes[_address].exist) {
Candidate storage candidate = votes[_address];
candidate.voters[_voter] = true;
candidate.noOfVotes = candidate.noOfVotes.add(1);
} else {
Candidate storage freshCandidate;
freshCandidate.voters[_voter] = true;
freshCandidate.noOfVotes = 1;
freshCandidate.exist = true;
votes[_address] = freshCandidate;
}
}
function payAnte(address _airline) external payable {
//require(registeredAirlinesMapping[msg.sender], "Not registered");
//require(msg.value >= 10 ether, "Airline does not have enough ethers");
registeredAirlinesMapping[_airline].isFunded = true;
registeredAirlines.push(_airline);
}
function registerFlight(
string _flightName,
uint8 _statusCode,
uint256 _updatedTimestamp,
address _airline
) external {
// require(!flights[_flightName].isRegistered, "Flight already exists.");
bytes32 flightKey = getFlightKey(
_airline,
_flightName,
_updatedTimestamp
);
Flight memory flight = Flight({
isRegistered: true,
statusCode: _statusCode,
updatedTimestamp: _updatedTimestamp,
airline: _airline
});
flights[flightKey] = flight;
flightsList.push(_flightName);
}
// TODO: only allow selected contracts to call this
function updateFlight(
string _flightName,
uint8 _statusCode,
uint256 _updatedTimestamp,
address _airline
) external {
bytes32 flightKey = getFlightKey(
_airline,
_flightName,
_updatedTimestamp
);
flights[flightKey].statusCode = _statusCode;
// this is a side-effect, should be called by the App
if (
_statusCode != STATUS_CODE_UNKNOWN &&
_statusCode != STATUS_CODE_ON_TIME
) {
updatePassengerInsurances(
_flightName,
_statusCode,
_updatedTimestamp,
_airline
);
}
}
function updatePassengerInsurances(
string _flightName,
uint8 _statusCode,
uint256 _updatedTimestamp,
address _airline
) internal {
if (passengersList.length > 0) {
bytes32 flightKey = getFlightKey(
_airline,
_flightName,
_updatedTimestamp
);
for (uint256 i = 0; i < passengersList.length; i++) {
address passenger = passengersList[i];
if (
passengers[passenger].insurances[flightKey].isBought && // passenger has the insurance
!passengers[passenger].insurances[flightKey].forPayment // prevents double payment
) {
creditInsurees(
_airline,
_flightName,
_updatedTimestamp,
passenger
);
}
}
}
}
/**
* @dev Buy insurance for a flight
*
*/
function buy(
address _airline,
string _flightName,
uint256 _timestamp,
uint256 _amount,
address _passenger
) external payable {
bytes32 _flightKey = getFlightKey(_airline, _flightName, _timestamp);
Insurance memory insurance;
insurance.amount = _amount;
insurance.flightKey = _flightKey;
insurance.isBought = true;
insurance.isCredited = false;
insurance.forPayment = false;
// check if passenger has bought insurance
if (isRegisteredPassenger(_passenger)) {
passengers[_passenger].insurances[_flightKey] = insurance;
} else {
Passenger memory passenger;
passenger.isRegistered = true;
passenger.balance = 0;
passengers[_passenger] = passenger;
passengers[_passenger].insurances[_flightKey] = insurance;
passengersList.push(_passenger);
// passenger.insurances[_flightKey] = insurance;
}
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees(
address _airline,
string _flightName,
uint256 _timestamp,
address _passenger
) internal {
bytes32 _flightKey = getFlightKey(_airline, _flightName, _timestamp);
Passenger storage passenger = passengers[_passenger];
uint256 value = passenger.insurances[_flightKey].amount.mul(3).div(2);
passenger.insurances[_flightKey].isCredited = true;
passenger.insurances[_flightKey].forPayment = true;
passenger.balance = passenger.balance.add(value);
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay(address _passenger, uint256 amount) external {
require(isRegisteredPassenger(_passenger), "Should be a passenger");
require(passengers[_passenger].balance > 0, "Should have balance");
require(passengers[_passenger].balance >= amount, "Not enough balance");
passengers[_passenger].balance = passengers[_passenger].balance.sub(
amount
);
_passenger.transfer(amount);
// TODO: delete the passeger from the list and mapping if there are no more insurance
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function fund() public payable {}
function getFlightKey(
address airline,
string memory flight,
uint256 timestamp
) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
/**
* @dev Fallback function for funding smart contract.
*
*/
function() external payable {
fund();
}
}
|
require(!flights[_flightName].isRegistered, "Flight already exists.");
|
function registerFlight(
string _flightName,
uint8 _statusCode,
uint256 _updatedTimestamp,
address _airline
) external {
bytes32 flightKey = getFlightKey(
_airline,
_flightName,
_updatedTimestamp
);
Flight memory flight = Flight({
isRegistered: true,
statusCode: _statusCode,
updatedTimestamp: _updatedTimestamp,
airline: _airline
});
flights[flightKey] = flight;
flightsList.push(_flightName);
}
| 15,844,552
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "../access/Operators.sol";
contract NFTAssets is ERC721, ERC721Enumerable, Pausable, Operators {
string public baseURI = "https://tapfantasy.io/web/nft/info/";
event UpdateBaseURI(address from, string baseUri);
constructor() ERC721("TAP FANTASY SKIN", "TFSKIN") {
}
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function setBaseURI(string memory _baseUri) public onlyOwner {
baseURI = _baseUri;
emit UpdateBaseURI(msg.sender, baseURI);
}
function pause() public onlyOwner {
_pause();
}
function unpause() public onlyOwner {
_unpause();
}
function safeMint(address to, uint256 tokenId) public onlyOper {
_safeMint(to, tokenId);
}
function burn(uint256 tokenId) public {
require(ownerOf(tokenId) == msg.sender, "ERC721: burn of token that is not own" );
_burn(tokenId);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal whenNotPaused override(ERC721, ERC721Enumerable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
// The following functions are overrides required by Solidity.
function supportsInterface(bytes4 interfaceId)
public view override(ERC721, ERC721Enumerable) returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
|
The following functions are overrides required by Solidity.
|
function supportsInterface(bytes4 interfaceId)
public view override(ERC721, ERC721Enumerable) returns (bool)
{
return super.supportsInterface(interfaceId);
}
| 7,326,580
|
./full_match/1/0xeC2bD67ab5b4Fa02A00466366751A21F8c5f0780/sources/NFT.sol
|
Mints Cool Ss/ if presale is active and address is in presale list allow mint the if the sale is not active and the user presale is not active OR the user is not on the whitelist then require the saleIsActive If we haven't set the starting index and this is either 1) the last saleable token or 2) the first token to be sold after the end of pre-sale, set the starting index block
|
function mintNFT(uint numberOfTokens) public payable {
if (!saleIsActive && (!presaleIsActive || !_presaleEligible[msg.sender])) {
require(saleIsActive, "Sale must be active to mint");
}
require(numberOfTokens <= maxPurchase, "Can only mint 20 tokens at a time");
require(totalSupply().add(numberOfTokens) <= MAX_SUPPLY, "Purchase would exceed max supply");
require(sPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct");
for(uint i = 0; i < numberOfTokens; i++) {
uint mintIndex = totalSupply();
if (totalSupply() < MAX_SUPPLY) {
_safeMint(msg.sender, mintIndex + 1);
}
}
if (startingIndexBlock == 0 && (totalSupply() == MAX_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
| 9,705,587
|
pragma solidity ^0.4.18;
/**
* @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 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 view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, 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) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @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);
}
/**
* @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 StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract LongevityToken is StandardToken {
string public name = "Longevity";
string public symbol = "LTY";
uint8 public decimals = 2;
bool public mintingFinished = false;
mapping (address => bool) owners;
mapping (address => bool) minters;
// tap to limit mint speed
struct Tap {
uint256 startTime; // reference time point to start measuring
uint256 tokensIssued; // how much tokens issued from startTime
uint256 mintSpeed; // token fractions per second
}
Tap public mintTap;
event Mint(address indexed to, uint256 amount);
event MintFinished();
event OwnerAdded(address indexed newOwner);
event OwnerRemoved(address indexed removedOwner);
event MinterAdded(address indexed newMinter);
event MinterRemoved(address indexed removedMinter);
event Burn(address indexed burner, uint256 value);
event MintTapSet(uint256 startTime, uint256 mintSpeed);
function LongevityToken() public {
owners[msg.sender] = true;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyMinter public returns (bool) {
require(!mintingFinished);
passThroughTap(_amount);
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner public returns (bool) {
require(!mintingFinished);
mintingFinished = true;
MintFinished();
return true;
}
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
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
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
/**
* @dev Adds administrative role to address
* @param _address The address that will get administrative privileges
*/
function addOwner(address _address) onlyOwner public {
owners[_address] = true;
OwnerAdded(_address);
}
/**
* @dev Removes administrative role from address
* @param _address The address to remove administrative privileges from
*/
function delOwner(address _address) onlyOwner public {
owners[_address] = false;
OwnerRemoved(_address);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owners[msg.sender]);
_;
}
/**
* @dev Adds minter role to address (able to create new tokens)
* @param _address The address that will get minter privileges
*/
function addMinter(address _address) onlyOwner public {
minters[_address] = true;
MinterAdded(_address);
}
/**
* @dev Removes minter role from address
* @param _address The address to remove minter privileges
*/
function delMinter(address _address) onlyOwner public {
minters[_address] = false;
MinterRemoved(_address);
}
/**
* @dev Throws if called by any account other than the minter.
*/
modifier onlyMinter() {
require(minters[msg.sender]);
_;
}
/**
* @dev passThroughTap allows minting tokens within the defined speed limit.
* Throws if requested more than allowed.
*/
function passThroughTap(uint256 _tokensRequested) internal {
require(_tokensRequested <= getTapRemaining());
mintTap.tokensIssued = mintTap.tokensIssued.add(_tokensRequested);
}
/**
* @dev Returns remaining amount of tokens allowed at the moment
*/
function getTapRemaining() public view returns (uint256) {
uint256 tapTime = now.sub(mintTap.startTime).add(1);
uint256 totalTokensAllowed = tapTime.mul(mintTap.mintSpeed);
uint256 tokensRemaining = totalTokensAllowed.sub(mintTap.tokensIssued);
return tokensRemaining;
}
/**
* @dev (Re)sets mint tap parameters
* @param _mintSpeed Allowed token amount to mint per second
*/
function setMintTap(uint256 _mintSpeed) onlyOwner public {
mintTap.startTime = now;
mintTap.tokensIssued = 0;
mintTap.mintSpeed = _mintSpeed;
MintTapSet(mintTap.startTime, mintTap.mintSpeed);
}
}
/**
* @title LongevityCrowdsale
* @dev LongevityCrowdsale is a contract for managing a token crowdsale for Longevity project.
* Crowdsale have phases with start and end timestamps, where investors can make
* token purchases and the crowdsale will assign them tokens based
* on a token per ETH rate and bonuses. Collected funds are forwarded to a wallet
* as they arrive.
*/
contract LongevityCrowdsale {
using SafeMath for uint256;
// The token being sold
LongevityToken public token;
// External wallet where funds get forwarded
address public wallet;
// Crowdsale administrators
mapping (address => bool) public owners;
// External bots updating rates
mapping (address => bool) public bots;
// USD cents per ETH exchange rate
uint256 public rateUSDcETH;
// Phases list, see schedule in constructor
mapping (uint => Phase) phases;
// The total number of phases
uint public totalPhases = 0;
// Description for each phase
struct Phase {
uint256 startTime;
uint256 endTime;
uint256 bonusPercent;
}
// Minimum Deposit in USD cents
uint256 public constant minContributionUSDc = 1000;
// Amount of raised Ethers (in wei).
uint256 public weiRaised;
/**
* 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 bonusPercent free tokens percantage for the phase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 bonusPercent, uint256 amount);
// event for rate update logging
event RateUpdate(uint256 rate);
// event for wallet update
event WalletSet(address indexed wallet);
// owners management events
event OwnerAdded(address indexed newOwner);
event OwnerRemoved(address indexed removedOwner);
// bot management events
event BotAdded(address indexed newBot);
event BotRemoved(address indexed removedBot);
// Phase edit events
event TotalPhasesChanged(uint value);
event SetPhase(uint index, uint256 _startTime, uint256 _endTime, uint256 _bonusPercent);
event DelPhase(uint index);
function LongevityCrowdsale(address _tokenAddress, uint256 _initialRate) public {
require(_tokenAddress != address(0));
token = LongevityToken(_tokenAddress);
rateUSDcETH = _initialRate;
wallet = msg.sender;
owners[msg.sender] = true;
bots[msg.sender] = true;
phases[0].bonusPercent = 40;
phases[0].startTime = 1520453700;
phases[0].endTime = 1520460000;
}
/**
* @dev Update collecting wallet address
* @param _address The address to send collected funds
*/
function setWallet(address _address) onlyOwner public {
wallet = _address;
WalletSet(_address);
}
// fallback function can be used to buy tokens
function () external payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) public payable {
require(beneficiary != address(0));
require(msg.value != 0);
require(isInPhase(now));
uint256 currentBonusPercent = getBonusPercent(now);
uint256 weiAmount = msg.value;
require(calculateUSDcValue(weiAmount) >= minContributionUSDc);
// calculate token amount to be created
uint256 tokens = calculateTokenAmount(weiAmount, currentBonusPercent);
// update state
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, currentBonusPercent, tokens);
forwardFunds();
}
// If phase exists return corresponding bonus for the given date
// else return 0 (percent)
function getBonusPercent(uint256 datetime) public view returns (uint256) {
require(isInPhase(datetime));
for (uint i = 0; i < totalPhases; i++) {
if (datetime >= phases[i].startTime && datetime <= phases[i].endTime) {
return phases[i].bonusPercent;
}
}
return 0;
}
// If phase exists for the given date return true
function isInPhase(uint256 datetime) public view returns (bool) {
for (uint i = 0; i < totalPhases; i++) {
if (datetime >= phases[i].startTime && datetime <= phases[i].endTime) {
return true;
}
}
}
// set rate
function setRate(uint256 _rateUSDcETH) public onlyBot {
// don't allow to change rate more than 10%
assert(_rateUSDcETH < rateUSDcETH.mul(110).div(100));
assert(_rateUSDcETH > rateUSDcETH.mul(90).div(100));
rateUSDcETH = _rateUSDcETH;
RateUpdate(rateUSDcETH);
}
/**
* @dev Adds administrative role to address
* @param _address The address that will get administrative privileges
*/
function addOwner(address _address) onlyOwner public {
owners[_address] = true;
OwnerAdded(_address);
}
/**
* @dev Removes administrative role from address
* @param _address The address to remove administrative privileges from
*/
function delOwner(address _address) onlyOwner public {
owners[_address] = false;
OwnerRemoved(_address);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owners[msg.sender]);
_;
}
/**
* @dev Adds rate updating bot
* @param _address The address of the rate bot
*/
function addBot(address _address) onlyOwner public {
bots[_address] = true;
BotAdded(_address);
}
/**
* @dev Removes rate updating bot address
* @param _address The address of the rate bot
*/
function delBot(address _address) onlyOwner public {
bots[_address] = false;
BotRemoved(_address);
}
/**
* @dev Throws if called by any account other than the bot.
*/
modifier onlyBot() {
require(bots[msg.sender]);
_;
}
// calculate deposit value in USD Cents
function calculateUSDcValue(uint256 _weiDeposit) public view returns (uint256) {
// wei per USD cent
uint256 weiPerUSDc = 1 ether/rateUSDcETH;
// Deposited value converted to USD cents
uint256 depositValueInUSDc = _weiDeposit.div(weiPerUSDc);
return depositValueInUSDc;
}
// calculates how much tokens will beneficiary get
// for given amount of wei
function calculateTokenAmount(uint256 _weiDeposit, uint256 _bonusTokensPercent) public view returns (uint256) {
uint256 mainTokens = calculateUSDcValue(_weiDeposit);
uint256 bonusTokens = mainTokens.mul(_bonusTokensPercent).div(100);
return mainTokens.add(bonusTokens);
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
wallet.transfer(msg.value);
}
//Change number of phases
function setTotalPhases(uint value) onlyOwner public {
totalPhases = value;
TotalPhasesChanged(value);
}
// Set phase: index and values
function setPhase(uint index, uint256 _startTime, uint256 _endTime, uint256 _bonusPercent) onlyOwner public {
require(index <= totalPhases);
phases[index] = Phase(_startTime, _endTime, _bonusPercent);
SetPhase(index, _startTime, _endTime, _bonusPercent);
}
// Delete phase
function delPhase(uint index) onlyOwner public {
require(index <= totalPhases);
delete phases[index];
DelPhase(index);
}
}
|
If phase exists for the given date return true
|
function isInPhase(uint256 datetime) public view returns (bool) {
for (uint i = 0; i < totalPhases; i++) {
if (datetime >= phases[i].startTime && datetime <= phases[i].endTime) {
return true;
}
}
}
| 1,125,062
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.16 <8.10.0;
contract ProvStorage {
//Global variables storing latest transaction count.
uint txNumber_upload = 0;
uint txNumber_download = 0;
string latest_txHash_upload = "";
string latest_txHash_download = "";
string temp_txHash = "origin";
// Upload structure
struct Upload {
//struct for each upload instance
uint txNumber;
string ipfsHash;
string txHash;
string author;
string filename;
uint timestamp;
}
//Download Structure - Download instances also added to chain
struct Download {
uint txNumber;
string ipfsHash;
string txHash;
string filename;
uint timestamp;
string downloader;
//string ip; need to pull from dapp
}
//Mappings
mapping(uint => Upload) public uploads;
mapping(string => Upload) public uploads_t;
//txNumber maps to an Upload instance
mapping(uint => Download) public downloads;
//txNumber_downloads maps to Download instance?
//mapping(address => mapping(uint => Upload)) public address_uploads; //NOT IN USE
//Uploads can also be mapped to an address (the account of the person who created the upload.)
//--- Upload - Download ---
function upload(string memory _ipfsHash, string memory _author, string memory _filename, uint _timestamp) public {
//associate an upload with address and create the instance
txNumber_upload = txNumber_upload +1;
//address_uploads[msg.sender][txNumber] = Upload(_ipfsHash, txHash, _author, _filename, _timestamp);
uploads[txNumber_upload] = Upload(txNumber_upload, _ipfsHash, "empty" , _author, _filename, _timestamp);
//This is new struct mapped with the hash!!!!!! Change this works.
uploads_t[temp_txHash] = Upload(txNumber_upload, _ipfsHash, "empty", _author, _filename, _timestamp);
}
function download(string memory _ipfsHash, string memory _filename, uint _time, string memory _downloader) public {
txNumber_download = txNumber_download +1;
downloads[txNumber_download] = Download(txNumber_upload,_ipfsHash, "empty", _filename, _time, _downloader);
}
//function to update txHash with correct value (blockhash) that gets generated after 'upload' is called
function updateTxHash_upload(string memory _txHash) public {
uploads[txNumber_upload].txHash = _txHash;
//set upload instance to have index as transaction hash
uploads_t[_txHash] = uploads_t[temp_txHash];
uploads_t[_txHash].txHash = _txHash;
latest_txHash_upload = _txHash;
}
//function to update txHash with correct value (blockhash) that gets generated after 'upload' is called
function updateTxHash_download(string memory _txHash) public {
downloads[txNumber_download].txHash = _txHash;
latest_txHash_download = _txHash;
}
//-----------------------------------------------
//---------Upload Get---------
function getTxNumber_up_latest() public view returns (uint){
//return the latest transaction number
return txNumber_upload;
}
function getIPFS_up_latest() public view returns (string memory){
//return the ipfsHash taking transaction ID & msg.sender.
return uploads[txNumber_upload].ipfsHash;
//return getTxHash();
}
function getTxHash_up_latest() public view returns (string memory){
//Return transactionHash
return uploads[txNumber_upload].txHash;
}
function getAuthor_up_latest() public view returns (string memory){
//return author based on txNumber and current account.
return uploads[txNumber_upload].author;
}
function getFileName_up_latest() public view returns (string memory){
//return author based on txNumber and current account.
return uploads[txNumber_upload].filename;
}
function getTimestamp_up_latest() public view returns (uint){
//return author based on txNumber and current account.
return uploads[txNumber_upload].timestamp;
}
//-------------------------------------------------------------
//----- test getters for transaction hash -----
function getIPFS_t() public view returns (string memory){
return uploads_t[latest_txHash_upload].ipfsHash;
}
function getTxHash_t() public view returns (string memory){
return uploads_t[latest_txHash_upload].txHash;
}
function getAuthor_t() public view returns (string memory){
return uploads_t[latest_txHash_upload].author;
}
function getFileName_t() public view returns (string memory){
return uploads_t[latest_txHash_upload].filename;
}
function getTimestamp_t() public view returns (uint){
return uploads_t[latest_txHash_upload].timestamp;
}
//-----
//----------- Download Get LATEST ------------------
function getTxNumber_down_latest() public view returns (uint){
//return the latest transaction number
return txNumber_download;
}
function getIPFS_down_latest() public view returns (string memory){
return downloads[txNumber_download].ipfsHash;
}
function getTxHash_down_latest() public view returns (string memory){
return downloads[txNumber_download].txHash;
}
function getFileName_down_latest() public view returns (string memory){
return downloads[txNumber_download].filename;
}
function getTimestamp_down_latest() public view returns (uint){
return downloads[txNumber_download].timestamp;
}
function getDownloader_latest() public view returns (string memory){
return downloads[txNumber_download].downloader;
}
}
//msg.sender = the address of the acccount currently running contract.
|
return author based on txNumber and current account.
|
function getFileName_up_latest() public view returns (string memory){
return uploads[txNumber_upload].filename;
}
| 2,528,270
|
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.10;
// @dev mock version of v1 price oracle, allowing manually setting return values
contract ProxyPriceOracle {
mapping(address => uint256) public prices;
function setUnderlyingPrice(address ctoken, uint price) external {
prices[ctoken] = price;
}
function getUnderlyingPrice(address ctoken) external view returns (uint) {
return prices[ctoken];
}
}
contract MockAnchorOracle {
struct Anchor {
// floor(block.number / numBlocksPerPeriod) + 1
uint period;
// Price in ETH, scaled by 10**18
uint priceMantissa;
}
mapping(address => uint256) public assetPrices;
function setPrice(address asset, uint price) external {
assetPrices[asset] = price;
}
function setUnderlyingPrice(MockCToken asset, uint price) external {
assetPrices[asset.underlying()] = price;
}
uint public constant numBlocksPerPeriod = 240;
mapping(address => Anchor) public anchors;
function setAnchorPeriod(address asset, uint period) external {
// dont care about anchor price, only period
anchors[asset] = Anchor({period: period, priceMantissa: 1e18});
}
}
contract MockCToken {
address public underlying;
constructor(address underlying_) public {
underlying = underlying_;
}
}
|
dont care about anchor price, only period
|
function setAnchorPeriod(address asset, uint period) external {
}
| 7,226,685
|
./full_match/5/0x95422c7d13F0A80B6CCb47F8346E21396823bfE6/sources/src/contracts/PublicLock/PublicLockV11.sol
|
Delete ownership info and udpate balance for previous owner _tokenId the id of the token to cancel/ get owner delete previous ownership When the token to delete is the last token, the swap operation is unnecessary remove from owner count if thats the only key
|
function _deleteOwnershipRecord(
uint _tokenId
) internal {
address previousOwner = _ownerOf[_tokenId];
uint lastTokenIndex = balanceOf(previousOwner) - 1;
uint index = _ownedKeysIndex[_tokenId];
if (index != lastTokenIndex) {
uint256 lastTokenId = _ownedKeyIds[previousOwner][lastTokenIndex];
}
if(totalKeys(previousOwner) == 1 ) {
numberOfOwners--;
}
}
| 11,630,588
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/****************************************
* @author: squeebo_nft *
* @team: GoldenX *
****************************************
* Blimpie-ERC721 provides low-gas *
* mints + transfers *
****************************************/
import './Blimpie/Delegated.sol';
import './Blimpie/ERC721EnumerableB.sol';
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/finance/PaymentSplitter.sol";
interface IERC721Proxy{
function balanceOf( address account ) external view returns ( uint quantity );
function ownerOf( uint tokenId ) external view returns ( address owner );
}
interface IPPL20{
function burnFromAccount( address account, uint pineapples ) external;
function burnFromTokens( address[] calldata tokenContracts, uint[] calldata tokenIds, uint pineapples ) external;
}
contract SupLadies is Delegated, ERC721EnumerableB, PaymentSplitter {
using Strings for uint;
uint public MAX_ORDER = 19;
uint public MAX_SUPPLY = 3914;
uint public MAX_VOUCHERS = 1957;
uint public ETH_PRICE = 0.1957 ether;
uint public PPL_PRICE = 19.57 ether;
bool public isMintActive = false;
bool public isPineapplesActive = false;
bool public isVoucherMintActive = false;
bool public isVoucherUseActive = false;
address public ahmcAddress = 0x61DB9Dde04F78fD55B0B4331a3d148073A101850;
address public artwAddress = 0x22d202872950782012baC53346EE3DaE3D78E0CB;
address public pineapplesAddress = 0x3e51F6422e41915e96A0808d21Babb83bcd278e5;
mapping(address => uint) public vouchers;
uint public voucherCount;
string private _tokenURIPrefix;
string private _tokenURISuffix;
address[] private addressList = [
0x13d86B7a637B9378d3646FA50De24e4e8fd78393,
0xc9241a5e35424a927536D0cA30C4687852402bCB,
0xB7edf3Cbb58ecb74BdE6298294c7AAb339F3cE4a
];
uint[] private shareList = [
57,
35,
8
];
constructor()
Delegated()
ERC721B("SupLadies", "SL", 0)
PaymentSplitter( addressList, shareList ){
}
//external
function tokenURI(uint tokenId) external view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return string(abi.encodePacked(_tokenURIPrefix, tokenId.toString(), _tokenURISuffix));
}
fallback() external payable {}
function mint( uint quantity ) external payable {
require( isMintActive, "ETH sale is not active" );
require( quantity <= MAX_ORDER, "Order too big" );
require( msg.value >= ETH_PRICE * quantity, "Ether sent is not correct" );
uint256 supply = totalSupply();
require( supply + quantity <= MAX_SUPPLY, "Mint/order exceeds supply" );
for(uint i; i < quantity; ++i){
_safeMint( msg.sender, supply++, "" );
}
}
function mintWithPineapplesAccount( uint quantity ) external {
require( isPineapplesActive, "Pineapple sale is not active" );
require( quantity <= MAX_ORDER, "Order too big" );
uint256 supply = totalSupply();
require( supply + quantity <= MAX_SUPPLY, "Order exceeds supply" );
_requireBalances();
uint totalPineapples = PPL_PRICE * quantity;
IPPL20( pineapplesAddress ).burnFromAccount( msg.sender, totalPineapples);
for(uint i; i < quantity; ++i){
_safeMint( msg.sender, supply++, "" );
}
}
function mintWithPineapplesTokens( uint quantity, address[] calldata tokenContracts, uint[] calldata tokenIds ) external {
require( isPineapplesActive, "Pineapple sale is not active" );
require( quantity <= MAX_ORDER, "Order too big" );
uint256 supply = totalSupply();
require( supply + quantity <= MAX_SUPPLY, "Order exceeds supply" );
_requireBalances();
_requireOwnership( tokenContracts, tokenIds );
uint totalPineapples = PPL_PRICE * quantity;
IPPL20( pineapplesAddress ).burnFromTokens(tokenContracts, tokenIds, totalPineapples);
for(uint i; i < quantity; ++i){
_safeMint( msg.sender, supply++, "" );
}
}
function mintVouchersFromAccount( uint quantity ) external {
require( isVoucherMintActive, "Voucher sale is not active" );
require( quantity <= MAX_ORDER, "Order too big" );
uint256 supply = totalSupply();
require( supply + quantity <= MAX_SUPPLY, "Order exceeds supply" );
require( voucherCount + quantity <= MAX_VOUCHERS, "Order exceeds supply" );
_requireBalances();
uint totalPineapples = PPL_PRICE * quantity;
IPPL20( pineapplesAddress ).burnFromAccount( msg.sender, totalPineapples);
voucherCount += quantity;
vouchers[ msg.sender ] += quantity;
}
function mintVouchersFromTokens( uint quantity, address[] calldata tokenContracts, uint[] calldata tokenIds ) external {
require( isVoucherMintActive, "Voucher sale is not active" );
require( quantity <= MAX_ORDER, "Order too big" );
uint256 supply = totalSupply();
require( supply + quantity <= MAX_SUPPLY, "Order exceeds supply" );
require( voucherCount + quantity <= MAX_VOUCHERS, "Order exceeds supply" );
_requireBalances();
_requireOwnership( tokenContracts, tokenIds );
uint totalPineapples = PPL_PRICE * quantity;
IPPL20( pineapplesAddress ).burnFromTokens(tokenContracts, tokenIds, totalPineapples);
voucherCount += quantity;
vouchers[ msg.sender ] += quantity;
}
function useVouchers( uint quantity ) external {
require( isVoucherUseActive, "Voucher mint is not active" );
require( quantity <= MAX_ORDER, "Order too big" );
uint256 supply = totalSupply();
require( supply + quantity <= MAX_SUPPLY, "Order exceeds supply" );
require( quantity <= vouchers[ msg.sender ], "Order exceeds vouchers" );
voucherCount -= quantity;
vouchers[ msg.sender ] -= quantity;
for(uint i = 0; i < quantity; ++i){
_safeMint( msg.sender, supply++, "" );
}
}
//onlyDelegates
function mintTo(uint[] calldata quantity, address[] calldata recipient) external payable onlyDelegates{
require(quantity.length == recipient.length, "Must provide equal quantities and recipients" );
uint totalQuantity = 0;
uint256 supply = totalSupply();
for(uint i = 0; i < quantity.length; ++i){
totalQuantity += quantity[i];
}
require( supply + totalQuantity < MAX_SUPPLY, "Mint/order exceeds supply" );
for(uint i; i < recipient.length; ++i){
for(uint j; j < quantity[i]; ++j){
_safeMint( recipient[i], supply++, "" );
}
}
}
function mintVouchersTo(uint[] calldata quantity, address[] calldata recipient) external payable onlyDelegates{
require(quantity.length == recipient.length, "Must provide equal quantities and recipients" );
uint totalQuantity = 0;
uint256 supply = totalSupply();
for(uint i = 0; i < quantity.length; ++i){
totalQuantity += quantity[i];
}
require( supply + totalQuantity < MAX_VOUCHERS, "Vouchers exceeds supply" );
for(uint i; i < recipient.length; ++i){
voucherCount += quantity[i];
vouchers[ recipient[i] ] += quantity[i];
}
}
function setActive(bool isActive_, bool isPineapplesActive_, bool isVoucherMintActive_, bool isVoucherUseActive_) external onlyDelegates{
require( isMintActive != isActive_ ||
isPineapplesActive != isPineapplesActive_ ||
isVoucherMintActive != isVoucherMintActive_ ||
isVoucherUseActive != isVoucherUseActive_, "New value matches old" );
isMintActive = isActive_;
isPineapplesActive = isPineapplesActive_;
isVoucherMintActive = isVoucherMintActive_;
isVoucherUseActive = isVoucherUseActive_;
}
function setBaseURI(string calldata prefix, string calldata suffix) external onlyDelegates{
_tokenURIPrefix = prefix;
_tokenURISuffix = suffix;
}
function setContracts(address pineapplesAddress_, address ahmcAddress_, address artwAddress_ ) external onlyDelegates {
pineapplesAddress = pineapplesAddress_;
ahmcAddress = ahmcAddress_;
artwAddress = artwAddress_;
}
function setMaxSupply(uint maxOrder, uint maxSupply, uint maxVouchers) external onlyDelegates{
require( MAX_ORDER != maxOrder || MAX_SUPPLY != maxSupply || MAX_VOUCHERS != maxVouchers, "New value matches old" );
require( maxSupply >= totalSupply(), "Specified supply is lower than current balance" );
MAX_ORDER = maxOrder;
MAX_SUPPLY = maxSupply;
MAX_VOUCHERS = maxVouchers;
}
function setPrice(uint ethPrice, uint pplPrice ) external onlyDelegates{
require( ETH_PRICE != ethPrice || PPL_PRICE != pplPrice, "New value matches old" );
ETH_PRICE = ethPrice;
PPL_PRICE = pplPrice;
}
//private
function _requireBalances() private view {
uint ahmc = IERC721( ahmcAddress ).balanceOf( msg.sender );
if( ahmc >= 2 )
return;
uint artw = IERC721( artwAddress ).balanceOf( msg.sender );
if( artw >= 11 )
return;
if( ahmc > 0 && artw >= 5 )
return;
revert( "Not enough AHMC/ARTW tokens" );
}
function _requireOwnership( address[] calldata tokenContracts, uint[] calldata tokenIds ) private view {
for( uint i; i < tokenContracts.length; ++i ){
require( msg.sender == IERC721( tokenContracts[i] ).ownerOf( tokenIds[i] ), "Invalid owner of token" );
}
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.0;
interface IBatch {
function isOwnerOf( address account, uint[] calldata tokenIds ) external view returns( bool );
function transferBatch( address from, address to, uint[] calldata tokenIds, bytes calldata data ) external;
function walletOfOwner( address account ) external view returns( uint[] memory );
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.0;
import "./ERC721B.sol";
import "./IBatch.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/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 ERC721EnumerableB is ERC721B, IBatch, IERC721Enumerable {
mapping(address => uint[]) internal _balances;
function balanceOf(address owner) public view virtual override(ERC721B,IERC721) returns (uint) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner].length;
}
function isOwnerOf( address account, uint[] calldata tokenIds ) external view override returns( bool ){
for(uint i; i < tokenIds.length; ++i ){
if( _owners[ tokenIds[i] ] != account )
return false;
}
return true;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721B) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint index) public view virtual override returns (uint tokenId) {
require(index < ERC721B.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _balances[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint) {
return _owners.length - _offset;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint index) public view virtual override returns (uint) {
require(index < totalSupply(), "ERC721Enumerable: global index out of bounds");
return index + _offset;
}
function walletOfOwner( address account ) external view override returns( uint[] memory ){
return _balances[ account ];
}
function transferBatch( address from, address to, uint[] calldata tokenIds, bytes calldata data ) external override{
for(uint i; i < tokenIds.length; ++i ){
safeTransferFrom( from, to, tokenIds[i], data );
}
}
//internal
function _beforeTokenTransfer(
address from,
address to,
uint tokenId
) internal override virtual {
address zero = address(0);
if( from != zero ){
//find this token and remove it
uint length = _balances[from].length;
for( uint i; i < length; ++i ){
if( _balances[from][i] == tokenId ){
_balances[from][i] = _balances[from][length - 1];
_balances[from].pop();
break;
}
}
}
if( to != zero )
_balances[to].push( tokenId );
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.0;
/********************
* @author: Squeebo *
********************/
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
abstract contract ERC721B is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
string private _name;
string private _symbol;
uint internal _offset;
// Mapping from token ID to owner address
address[] internal _owners;
// Mapping from token ID to approved address
mapping(uint => 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_, uint offset) {
_name = name_;
_symbol = symbol_;
_offset = offset;
for(uint i; i < _offset; ++i ){
_owners.push(address(0));
}
}
//public
function balanceOf(address owner) public view virtual override returns (uint) {
require(owner != address(0), "ERC721: balance query for the zero address");
uint count = 0;
uint length = _owners.length;
for( uint i = 0; i < length; ++i ){
if( owner == _owners[i] )
++count;
}
return count;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function next() public view returns( uint ){
return _owners.length;
}
function ownerOf(uint tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function approve(address to, uint tokenId) public virtual override {
address owner = ERC721B.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);
}
function getApproved(uint tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
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);
}
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
function transferFrom(
address from,
address to,
uint 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,
uint tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
//internal
function _safeTransfer(
address from,
address to,
uint tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
function _exists(uint tokenId) internal view virtual returns (bool) {
return tokenId < _owners.length && _owners[tokenId] != address(0);
}
function _isApprovedOrOwner(address spender, uint tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721B.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
function _safeMint(address to, uint tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
function _safeMint(
address to,
uint tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
function _mint(address to, uint 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);
_owners.push(to);
emit Transfer(address(0), to, tokenId);
}
function _burn(uint tokenId) internal virtual {
address owner = ERC721B.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_owners[tokenId] = address(0);
emit Transfer(owner, address(0), tokenId);
}
function _transfer(
address from,
address to,
uint tokenId
) internal virtual {
require(ERC721B.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);
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
function _approve(address to, uint tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721B.ownerOf(tokenId), to, tokenId);
}
function _checkOnERC721Received(
address from,
address to,
uint 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;
}
}
function _beforeTokenTransfer(
address from,
address to,
uint tokenId
) internal virtual {}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.0;
/********************
* @author: Squeebo *
********************/
import "@openzeppelin/contracts/access/Ownable.sol";
contract Delegated is Ownable{
mapping(address => bool) internal _delegates;
constructor(){
_delegates[owner()] = true;
}
modifier onlyDelegates {
require(_delegates[msg.sender], "Invalid delegate" );
_;
}
//onlyOwner
function isDelegate( address addr ) external view onlyOwner returns ( bool ){
return _delegates[addr];
}
function setDelegate( address addr, bool isDelegate_ ) external onlyOwner{
_delegates[addr] = isDelegate_;
}
function transferOwnership(address newOwner) public virtual override onlyOwner {
_delegates[newOwner] = true;
super.transferOwnership( newOwner );
}
}
// 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 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 "./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 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;
/**
* @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;
/**
* @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;
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;
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;
/**
* @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 "../../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
pragma solidity ^0.8.0;
import "../utils/Address.sol";
import "../utils/Context.sol";
import "../utils/math/SafeMath.sol";
/**
* @title PaymentSplitter
* @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware
* that the Ether will be split in this way, since it is handled transparently by the contract.
*
* The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each
* account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim
* an amount proportional to the percentage of total shares they were assigned.
*
* `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the
* accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release}
* function.
*/
contract PaymentSplitter is Context {
event PayeeAdded(address account, uint256 shares);
event PaymentReleased(address to, uint256 amount);
event PaymentReceived(address from, uint256 amount);
uint256 private _totalShares;
uint256 private _totalReleased;
mapping(address => uint256) private _shares;
mapping(address => uint256) private _released;
address[] private _payees;
/**
* @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at
* the matching position in the `shares` array.
*
* All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no
* duplicates in `payees`.
*/
constructor(address[] memory payees, uint256[] memory shares_) payable {
require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch");
require(payees.length > 0, "PaymentSplitter: no payees");
for (uint256 i = 0; i < payees.length; i++) {
_addPayee(payees[i], shares_[i]);
}
}
/**
* @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully
* reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the
* reliability of the events, and not the actual splitting of Ether.
*
* To learn more about this see the Solidity documentation for
* https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback
* functions].
*/
receive() external payable virtual {
emit PaymentReceived(_msgSender(), msg.value);
}
/**
* @dev Getter for the total shares held by payees.
*/
function totalShares() public view returns (uint256) {
return _totalShares;
}
/**
* @dev Getter for the total amount of Ether already released.
*/
function totalReleased() public view returns (uint256) {
return _totalReleased;
}
/**
* @dev Getter for the amount of shares held by an account.
*/
function shares(address account) public view returns (uint256) {
return _shares[account];
}
/**
* @dev Getter for the amount of Ether already released to a payee.
*/
function released(address account) public view returns (uint256) {
return _released[account];
}
/**
* @dev Getter for the address of the payee number `index`.
*/
function payee(uint256 index) public view returns (address) {
return _payees[index];
}
/**
* @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the
* total shares and their previous withdrawals.
*/
function release(address payable account) public virtual {
require(_shares[account] > 0, "PaymentSplitter: account has no shares");
uint256 totalReceived = address(this).balance + _totalReleased;
uint256 payment = (totalReceived * _shares[account]) / _totalShares - _released[account];
require(payment != 0, "PaymentSplitter: account is not due payment");
_released[account] = _released[account] + payment;
_totalReleased = _totalReleased + payment;
Address.sendValue(account, payment);
emit PaymentReleased(account, payment);
}
/**
* @dev Add a new payee to the contract.
* @param account The address of the payee to add.
* @param shares_ The number of shares owned by the payee.
*/
function _addPayee(address account, uint256 shares_) private {
require(account != address(0), "PaymentSplitter: account is the zero address");
require(shares_ > 0, "PaymentSplitter: shares are 0");
require(_shares[account] == 0, "PaymentSplitter: account already has shares");
_payees.push(account);
_shares[account] = shares_;
_totalShares = _totalShares + shares_;
emit PayeeAdded(account, shares_);
}
}
// SPDX-License-Identifier: MIT
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() {
_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);
}
}
|
internalfind this token and remove it
|
function _beforeTokenTransfer(
address from,
address to,
uint tokenId
) internal override virtual {
address zero = address(0);
if( from != zero ){
uint length = _balances[from].length;
for( uint i; i < length; ++i ){
if( _balances[from][i] == tokenId ){
_balances[from][i] = _balances[from][length - 1];
_balances[from].pop();
break;
}
}
}
if( to != zero )
_balances[to].push( tokenId );
}
| 338,780
|
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
/**
* @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);
}
interface IERC20Query {
/**
* @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 amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
}
/**
* @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 Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*/
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-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*/
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);
}
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
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using 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 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");
}
}
}
/**
* @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;
}
}
}
/**
* @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;
}
}
/**
* @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 initial owner.
*/
function initializeOwnable(address ownerAddr_) internal {
_setOwner(ownerAddr_);
}
/**
* @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 Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) external 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);
}
}
interface IWrappedToken {
function initialize(string calldata name, string calldata symbol, uint8 decimals, address owner, address admin) external;
function mintTo(address recipient, uint256 amount) external returns (bool);
function burnFrom(address account, uint256 amount) external returns (bool);
}
struct OriginalToken {
uint256 chainId;
address addr;
}
contract EthTeleportAgent is Ownable, Initializable {
using SafeERC20 for IERC20;
using Address for address;
mapping(uint256/*fromChainId*/ => mapping(uint256/*fromChainTeleportId*/ => bool/*finished*/)) public finishedTeleports;
mapping(uint256/*original chain id*/ => mapping(address/*original token address*/ => address/*wrapped token address*/)) public originalToWrappedTokens;
mapping(address/*wrapped token address*/ => OriginalToken) public wrappedToOriginalTokens;
address public signOwner;
address public feeOwner;
address public wrappedTokenImplementation;
address public wrappedTokenAdmin;
uint256 public teleportIdGenerator;
uint256 public teleportFee;
string private constant ERROR_ALREADY_EXECUTED = "already executed";
string private constant ERROR_MINT_FAILED = "mint failed";
event SetSignOwner(
address indexed oldValue,
address indexed newValue);
event SetFeeOwner(
address indexed oldValue,
address indexed newValue);
event SetTeleportFee(
uint256 oldValue,
uint256 newValue);
event SetWrappedTokenAdmin(
address indexed oldValue,
address indexed newValue);
event WrappedTokenCreated(
address indexed sponsor,
uint256 originalTokenChainId,
address indexed originalTokenAddr,
address indexed wrappedTokenAddr,
string name,
string symbol,
uint8 decimals);
event TeleportStarted(
uint256 teleportId,
address indexed sender,
uint256 originalTokenChainId,
address indexed originalTokenAddr,
address indexed tokenAddr,
uint256 amount,
uint256 toChainId,
address recipient,
uint256 feeAmount);
event TeleportFinished(
address indexed recipient,
uint256 fromChainId,
uint256 fromChainTeleportId,
uint256 originalTokenChainId,
address indexed originalTokenAddr,
address indexed tokenAddr,
uint256 amount);
event TeleportCancelStarted(
uint256 fromChainId,
uint256 fromChainTeleportId);
event TeleportCancelFinished(
uint256 teleportId,
address tokenAddr,
uint256 amount,
address recipient);
function initialize(
address payable _ownerAddr,
address _signOwner,
address _feeOwner,
uint256 _teleportFee,
address _wrappedTokenImpl,
address _wrappedTokenAdmin) external virtual initializer {
_ensureNotZeroAddress(_ownerAddr);
_ensureNotZeroAddress(_signOwner);
_ensureNotZeroAddress(_feeOwner);
_ensureNotZeroAddress(_wrappedTokenImpl);
initializeOwnable(_ownerAddr);
signOwner = _signOwner;
emit SetSignOwner(address(0), _signOwner);
feeOwner = _feeOwner;
emit SetFeeOwner(address(0), _feeOwner);
teleportFee = _teleportFee;
emit SetTeleportFee(0, _teleportFee);
wrappedTokenImplementation = _wrappedTokenImpl;
wrappedTokenAdmin = _wrappedTokenAdmin;
emit SetWrappedTokenAdmin(address(0), _wrappedTokenAdmin);
}
function setSignOwner(address _signOwner) onlyOwner external {
_ensureNotZeroAddress(_signOwner);
require(signOwner != _signOwner, ERROR_ALREADY_EXECUTED);
emit SetSignOwner(signOwner, _signOwner);
signOwner = _signOwner;
}
function setFeeOwner(address _feeOwner) onlyOwner external {
_ensureNotZeroAddress(_feeOwner);
require(feeOwner != _feeOwner, ERROR_ALREADY_EXECUTED);
emit SetFeeOwner(feeOwner, _feeOwner);
feeOwner = _feeOwner;
}
function setTeleportFee(uint256 _teleportFee) onlyOwner external {
require(teleportFee != _teleportFee, ERROR_ALREADY_EXECUTED);
emit SetTeleportFee(teleportFee, _teleportFee);
teleportFee = _teleportFee;
}
function setWrappedTokenAdmin(address _wrappedTokenAdmin) onlyOwner external {
_ensureNotZeroAddress(_wrappedTokenAdmin);
require(wrappedTokenAdmin != _wrappedTokenAdmin, ERROR_ALREADY_EXECUTED);
emit SetWrappedTokenAdmin(wrappedTokenAdmin, _wrappedTokenAdmin);
wrappedTokenAdmin = _wrappedTokenAdmin;
}
/**
* @dev This function is called by the oracle to create wrapped token in present chain.
* Wrapped token will represent the original token from another chain.
* This function is optional but it will reduce the cost of the first {teleportFinish} function call
* for given token pair.
*/
function createWrappedToken(
uint256 _originalTokenChainId,
address _originalTokenAddr,
string calldata _name,
string calldata _symbol,
uint8 _decimals) onlyOwner external {
_createWrappedToken(
_originalTokenChainId,
_originalTokenAddr,
_name,
_symbol,
_decimals);
}
/**
* @dev This function is called by the user to create wrapped token in present chain.
* Wrapped token will represent the original token from another chain.
* This function is optional but it will reduce the cost of the first {teleportFinish} function call
* for given token pair.
* All parameters of this function are signed with oracle private key. The signature is passed in
* {_signature} parameter.
*/
function createWrappedToken(
uint256 _originalTokenChainId,
address _originalTokenAddr,
string calldata _name,
string calldata _symbol,
uint8 _decimals,
bytes calldata _signature) external {
string memory message = string(abi.encodePacked(
_toAsciiString(_msgSender()), ";",
_uintToString(_originalTokenChainId), ";",
_toAsciiString(_originalTokenAddr), ";",
_name, ";",
_symbol, ";",
_uintToString(_decimals)));
_verify(message, _signature);
_createWrappedToken(
_originalTokenChainId,
_originalTokenAddr,
_name,
_symbol,
_decimals);
}
function _createWrappedToken(
uint256 _originalTokenChainId,
address _originalTokenAddr,
string memory _name,
string memory _symbol,
uint8 _decimals) private returns (address) {
_ensureNotZeroAddress(_originalTokenAddr);
require(block.chainid != _originalTokenChainId, "can't create wrapped token in original chain");
require(originalToWrappedTokens[_originalTokenChainId][_originalTokenAddr] == address(0), "already created");
address msgSender = _msgSender();
address wrappedToken = _deployMinimalProxy(wrappedTokenImplementation);
IWrappedToken(wrappedToken).initialize(_name, _symbol, _decimals, address(this), wrappedTokenAdmin);
originalToWrappedTokens[_originalTokenChainId][_originalTokenAddr] = wrappedToken;
wrappedToOriginalTokens[wrappedToken] = OriginalToken({chainId: _originalTokenChainId, addr: _originalTokenAddr});
emit WrappedTokenCreated(
msgSender,
_originalTokenChainId,
_originalTokenAddr,
wrappedToken,
_name,
_symbol,
_decimals);
return wrappedToken;
}
/**
* @dev Anyone can call this function to start the token teleportation process.
* It either freezes the {_tokenAddr} tokens on the bridge or burns them and emits a signal to the oracle.
*/
function teleportStart(address _tokenAddr, uint256 _amount, uint256 _toChainId, address _recipient) payable external {
_ensureNotZeroAddress(_tokenAddr);
_ensureNotZeroAddress(_recipient);
require(_amount > 0, "zero amount");
require(msg.value >= teleportFee, "fee mismatch");
if (msg.value != 0) {
(bool sent, ) = feeOwner.call{value: msg.value}("");
require(sent, "fee send failed");
}
address msgSender = _msgSender();
OriginalToken storage originalToken = wrappedToOriginalTokens[_tokenAddr];
if (originalToken.addr == address(0)) { // teleportable token {_tokenAddr} is original token
IERC20(_tokenAddr).safeTransferFrom(msgSender, address(this), _amount);
emit TeleportStarted(
++teleportIdGenerator,
msgSender,
block.chainid,
_tokenAddr,
_tokenAddr,
_amount,
_toChainId,
_recipient,
msg.value);
return;
}
// teleportable token {_tokenAddr} is wrapped token
require(IWrappedToken(_tokenAddr).burnFrom(msgSender, _amount), "burn failed");
emit TeleportStarted(
++teleportIdGenerator,
msgSender,
originalToken.chainId,
originalToken.addr,
_tokenAddr,
_amount,
_toChainId,
_recipient,
msg.value);
}
/**
* @dev This function is called by the oracle to finish the token teleportation process.
* The required admount of tokens is minted or unfreezed to {_toAddress} address in present chain.
*/
function teleportFinish(
uint256 _fromChainId,
uint256 _fromChainTeleportId,
uint256 _originalTokenChainId,
address _originalTokenAddr,
string memory _name,
string memory _symbol,
uint8 _decimals,
address _recipient,
uint256 _amount) onlyOwner external {
_teleportFinish(
_fromChainId,
_fromChainTeleportId,
_originalTokenChainId,
_originalTokenAddr,
_name,
_symbol,
_decimals,
_recipient,
_amount);
}
/**
* @dev This function is called by the user to finish the token teleportation process.
* All parameters of this function are signed with oracle private key. The signature is passed in
* {_signature} parameter.
* The required admount of tokens is minted or unfreezed to {_toAddress} address in present chain.
*/
function teleportFinish(
uint256 _fromChainId,
uint256 _fromChainTeleportId,
uint256 _originalTokenChainId,
address _originalTokenAddr,
string memory _name,
string memory _symbol,
uint8 _decimals,
uint256 _amount,
bytes memory _signature) external {
address recipient = _msgSender();
string memory message = string(abi.encodePacked(
_toAsciiString(recipient), ";",
_uintToString(_fromChainId), ";",
_uintToString(_fromChainTeleportId), ";",
_uintToString(_originalTokenChainId), ";",
_toAsciiString(_originalTokenAddr), ";",
_name, ";",
_symbol, ";",
_uintToString(_decimals), ";",
_uintToString(_amount)));
_verify(message, _signature);
_teleportFinish(
_fromChainId,
_fromChainTeleportId,
_originalTokenChainId,
_originalTokenAddr,
_name,
_symbol,
_decimals,
recipient,
_amount);
}
function _teleportFinish(
uint256 _fromChainId,
uint256 _fromChainTeleportId,
uint256 _originalTokenChainId,
address _originalTokenAddr,
string memory _name,
string memory _symbol,
uint8 _decimals,
address _recipient,
uint256 _amount) private {
_ensureNotZeroAddress(_originalTokenAddr);
_ensureNotZeroAddress(_recipient);
require(!finishedTeleports[_fromChainId][_fromChainTeleportId], ERROR_ALREADY_EXECUTED);
finishedTeleports[_fromChainId][_fromChainTeleportId] = true;
address tokenAddr;
if (_originalTokenChainId == block.chainid) {
IERC20(_originalTokenAddr).safeTransfer(_recipient, _amount);
tokenAddr = _originalTokenAddr;
} else {
tokenAddr = originalToWrappedTokens[_originalTokenChainId][_originalTokenAddr];
if (tokenAddr == address(0)) {
tokenAddr = _createWrappedToken(
_originalTokenChainId,
_originalTokenAddr,
_name,
_symbol,
_decimals);
}
require(IWrappedToken(tokenAddr).mintTo(_recipient, _amount), ERROR_MINT_FAILED);
}
emit TeleportFinished(
_recipient,
_fromChainId,
_fromChainTeleportId,
_originalTokenChainId,
_originalTokenAddr,
tokenAddr,
_amount);
}
function teleportCancelStart(uint256 _fromChainId, uint256 _fromChainTeleportId) onlyOwner external {
require(!finishedTeleports[_fromChainId][_fromChainTeleportId], ERROR_ALREADY_EXECUTED);
finishedTeleports[_fromChainId][_fromChainTeleportId] = true;
emit TeleportCancelStarted(_fromChainId, _fromChainTeleportId);
}
function teleportCancelFinish(
uint256 _teleportId,
address _tokenAddr,
uint256 _amount,
address _recipient) onlyOwner external {
OriginalToken storage originalToken = wrappedToOriginalTokens[_tokenAddr];
if (originalToken.addr == address(0)) { // {_tokenAddr} is original token
IERC20(_tokenAddr).safeTransfer(_recipient, _amount);
} else { // {_tokenAddr} is wrapped token
require(IWrappedToken(_tokenAddr).mintTo(_recipient, _amount), ERROR_MINT_FAILED);
}
emit TeleportCancelFinished(_teleportId, _tokenAddr, _amount, _recipient);
}
function _deployMinimalProxy(address _logic) private 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)
}
}
function _verify(string memory _message, bytes memory _sig) private view {
bytes32 messageHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", keccak256(abi.encodePacked(_message))));
address messageSigner = _recover(messageHash, _sig);
require(messageSigner == signOwner, "verification failed");
}
function _recover(bytes32 _hash, bytes memory _sig) private pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
require(_sig.length == 65, "_recover: invalid sig size");
assembly {
r := mload(add(_sig, 32))
s := mload(add(_sig, 64))
v := byte(0, mload(add(_sig, 96)))
}
if (v < 27) {
v += 27;
}
require(v == 27 || v == 28, "_recover: invalid sig");
return ecrecover(_hash, v, r, s);
}
function _uintToString(uint _i) private pure returns (string memory) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len;
while (_i != 0) {
k = k - 1;
uint8 temp = (48 + uint8(_i - _i / 10 * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(bstr);
}
function _toAsciiString(address _addr) private pure returns (string memory) {
bytes memory s = new bytes(40);
for (uint i = 0; i < 20; i++) {
bytes1 b = bytes1(uint8(uint(uint160(_addr)) / (2 ** (8 * (19 - i)))));
bytes1 hi = bytes1(uint8(b) / 16);
bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi));
s[2 * i] = _char(hi);
s[2 * i + 1] = _char(lo);
}
return string(s);
}
function _char(bytes1 value) private pure returns (bytes1) {
return (uint8(value) < 10) ? bytes1(uint8(value) + 0x30) : bytes1(uint8(value) + 0x57);
}
function _ensureNotZeroAddress(address _address) private pure {
require(_address != address(0), "zero address");
}
}
|
This function is called by the user to create wrapped token in present chain. Wrapped token will represent the original token from another chain. This function is optional but it will reduce the cost of the first {teleportFinish} function call for given token pair. All parameters of this function are signed with oracle private key. The signature is passed in {_signature} parameter./
|
function createWrappedToken(
uint256 _originalTokenChainId,
address _originalTokenAddr,
string calldata _name,
string calldata _symbol,
uint8 _decimals,
bytes calldata _signature) external {
string memory message = string(abi.encodePacked(
_toAsciiString(_msgSender()), ";",
_uintToString(_originalTokenChainId), ";",
_toAsciiString(_originalTokenAddr), ";",
_name, ";",
_symbol, ";",
_uintToString(_decimals)));
_verify(message, _signature);
_createWrappedToken(
_originalTokenChainId,
_originalTokenAddr,
_name,
_symbol,
_decimals);
}
| 10,086,393
|
./full_match/43114/0x9E4E36a00F7043ec6aC08f81c40438052CCFfD02/sources/MasterChef.sol
|
Deposit LP tokens to MasterChef for VAST allocation.
|
function deposit(uint256 _pid, uint256 _amount) external nonReentrant {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
payOrLockupPending(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accVastPerShare).div(1e18).sub(user.rewardDebt);
if (pending > 0) {
safeVastTransfer(msg.sender, pending);
}
}
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accVastPerShare).div(1e18).sub(user.rewardDebt);
if (pending > 0) {
safeVastTransfer(msg.sender, pending);
}
}
if (_amount > 0) {
uint256 balanceBefore = pool.lpToken.balanceOf(address(this));
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
_amount = pool.lpToken.balanceOf(address(this)) - balanceBefore;
if (pool.depositFeeBP > 0) {
uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000);
pool.lpToken.safeTransfer(feeAddress, depositFee);
user.amount = user.amount.add(_amount).sub(depositFee);
pool.lpSupply = pool.lpSupply.add(_amount).sub(depositFee);
user.amount = user.amount.add(_amount);
pool.lpSupply = pool.lpSupply.add(_amount);
}
}
user.rewardDebt = user.amount.mul(pool.accVastPerShare).div(1e18);
emit Deposit(msg.sender, _pid, _amount);
if (_amount > 0) {
uint256 balanceBefore = pool.lpToken.balanceOf(address(this));
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
_amount = pool.lpToken.balanceOf(address(this)) - balanceBefore;
if (pool.depositFeeBP > 0) {
uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000);
pool.lpToken.safeTransfer(feeAddress, depositFee);
user.amount = user.amount.add(_amount).sub(depositFee);
pool.lpSupply = pool.lpSupply.add(_amount).sub(depositFee);
user.amount = user.amount.add(_amount);
pool.lpSupply = pool.lpSupply.add(_amount);
}
}
user.rewardDebt = user.amount.mul(pool.accVastPerShare).div(1e18);
emit Deposit(msg.sender, _pid, _amount);
} else {
}
| 4,533,087
|
pragma solidity ^0.4.24;
import "./Ownable.sol";
import "./stringUtil.sol";
//import "github.com/Arachnid/solidity-stringutils/strings.sol";
contract VoteContract is Ownable, StringUtil {
//using strings for *;
struct voter {
string name;
bool voted;
}
struct vote {
mapping(uint => candidate) candidates;
uint candidateSeq;
mapping(address => voter) voters;
int voteCnt;
bool isEnd;
string voteName;
}
struct candidate {
string name;
string imgPath;
address[] voters;
}
mapping(uint256 => vote) voteHst;
uint256 voteSeq = 0;
function addCandidate(uint256 vSeq, string memory _name, string memory _imgPath) public onlyOwner {
//require(voteHst[voteSeq].candidates[candidateSeq].voters.length > 0, "이미 기투표자가 존재합니다.");
uint seq = voteHst[vSeq].candidateSeq;
voteHst[vSeq].candidates[seq].name = _name;
voteHst[vSeq].candidates[seq].imgPath = _imgPath;
voteHst[vSeq].candidateSeq += 1;
}
function addVote(string memory vName) public onlyOwner {
voteHst[voteSeq].isEnd = false;
voteHst[voteSeq].voteName = vName;
voteHst[voteSeq].voteCnt = 0;
voteSeq += 1;
}
function voting(uint256 vSeq, uint cSeq, string memory _name) public {
voteHst[vSeq].voters[msg.sender].name = _name;
voteHst[vSeq].voters[msg.sender].voted = true;
voteHst[vSeq].voteCnt += 1;
voteHst[vSeq].candidates[cSeq].voters.push(msg.sender);
}
function getVoteCount(uint256 vSeq) public view returns (int) {
return voteHst[vSeq].voteCnt;
}
function isVoted(uint256 vSeq, address vt) public view returns (uint256 _vSeq, bool _isVoted){
_vSeq = vSeq;
_isVoted = voteHst[vSeq].voters[vt].voted;
}
function getVoteName(uint256 vSeq) public view returns (uint256 key, string value){
key = vSeq;
value = voteHst[vSeq].voteName;
}
function getVoteSeq() public view returns(uint256){
return voteSeq;
}
function getWinner(uint256 vSeq) public view returns (string winnerName, uint cSeq) {
int voteCnt = -1;
for(uint i = 0; i < voteHst[vSeq].candidateSeq; i++){
int vCnt = int(voteHst[vSeq].candidates[i].voters.length);
if(voteCnt < vCnt) {
voteCnt = vCnt;
winnerName = voteHst[vSeq].candidates[i].name;
cSeq = i;
}
}
}
function getVoters(uint256 vSeq, uint256 cSeq, uint inx) public view onlyOwner returns (address) {
return voteHst[vSeq].candidates[cSeq].voters[inx];
}
function getCandidateList(uint256 vSeq, uint256 cSeq) public view returns (string _name, string _imgPath) {
_name = voteHst[vSeq].candidates[cSeq].name;
_imgPath = voteHst[vSeq].candidates[cSeq].imgPath;
}
function getCandidateWithVotedList(uint256 vSeq, uint256 cSeq, address vt) public view returns (uint256 _cSeq, string _name, string _imgPath, bool _isVoted) {
_cSeq = cSeq;
_name = voteHst[vSeq].candidates[cSeq].name;
_imgPath = voteHst[vSeq].candidates[cSeq].imgPath;
_isVoted = false;
uint _vCnt = voteHst[vSeq].candidates[cSeq].voters.length;
for(uint i = 0; i < _vCnt; i++){
if(voteHst[vSeq].candidates[cSeq].voters[i] == vt){
_isVoted = true;
break;
}
}
}
function getCandidateCnt(uint256 vSeq) public view returns (uint) {
return voteHst[vSeq].candidateSeq;
}
function getVotesCount() public view returns (string list){
string memory labelkey = "label";
string memory datakey = "data";
for(uint i = 0; i < voteSeq; i++){
string memory jstr = "";
jstr = jsonStr(labelkey, voteHst[i].voteName);
int dataInt = voteHst[i].voteCnt;
string memory data = "";
if(dataInt == 0){
data = "0";
}
else{
data = uintToString(uint(voteHst[i].voteCnt));
}
jstr = jsonInt(jstr, datakey, data);
jstr = compJsonStr(jstr);
if(i == 0){
list = jstr;
}
else{
list = arrayAddJson(list, jstr);
}
}
list = compArrayJson(list);
}
function initVoteData() public onlyOwner{
addVote("test");
addVote("test2");
addCandidate(0, "test-penguin", "/img/penguin.jpg");
addCandidate(0, "test-penguin2", "/img/penguin2.jpg");
addCandidate(0, "test-penguin3", "/img/penguin3.jpg");
addCandidate(0, "test-penguin4", "/img/penguin4.jpg");
addCandidate(1, "test2-penguin", "/img/penguin.jpg");
addCandidate(1, "test2-penguin2", "/img/penguin2.jpg");
addCandidate(1, "test2-penguin3", "/img/penguin3.jpg");
addCandidate(1, "test2-penguin4", "/img/penguin4.jpg");
}
function getCandidateVoteCount(uint256 vSeq) public view returns (string list){
string memory labelkey = "label";
string memory datakey = "data";
string memory winnerKey = "winner";
uint cSeq = voteHst[vSeq].candidateSeq;
string memory winnername = "";
uint _cSeq = 0;
(winnername, _cSeq) = getWinner(vSeq);
for(uint i = 0; i < cSeq; i++){
string memory jstr = "";
jstr = jsonStr(labelkey, voteHst[vSeq].candidates[i].name);
uint dataInt = voteHst[vSeq].candidates[i].voters.length;
string memory data = "";
if(dataInt == 0){
data = "0";
}
else{
data = uintToString(dataInt);
}
jstr = jsonInt(jstr, datakey, data);
if(_cSeq == i){
jstr = jsonStr(jstr, winnerKey, "Y");
}
else{
jstr = jsonStr(jstr, winnerKey, "N");
}
jstr = compJsonStr(jstr);
if(i == 0){
list = jstr;
}
else{
list = arrayAddJson(list, jstr);
}
}
list = compArrayJson(list);
}
}
|
require(voteHst[voteSeq].candidates[candidateSeq].voters.length > 0, "이미 기투표자가 존재합니다.");
|
function addCandidate(uint256 vSeq, string memory _name, string memory _imgPath) public onlyOwner {
uint seq = voteHst[vSeq].candidateSeq;
voteHst[vSeq].candidates[seq].name = _name;
voteHst[vSeq].candidates[seq].imgPath = _imgPath;
voteHst[vSeq].candidateSeq += 1;
}
| 1,795,820
|
./full_match/80001/0xB447B59d547Ba4BCD85269d6b700a84A01bb381f/sources/contracts/Battle.sol
|
Both players attack Both players defend No action required Player 1 attacks, player 2 defends Player 2 attacks, player 1 defends Player 1 attacks, player 2 does nothing Player 1 does nothing, player 2 attacks Player 1 defends, player 2 does nothing Player 1 does nothing, player 2 defends USE_SKILL logic here. Player 1 does nothing Player 2 does nothing Check if the battle has ended and declare a winner If no character has lost all their health, reset the move submissions for the next round.
|
function _resolveRound(
uint256 battleId,
uint256 _skillId0,
uint256 _skillId1
) private {
BattleData storage battle = battles[battleId];
bytes32 battleKeyA = keccak256(
abi.encodePacked(battleId, battle.players[0])
);
bytes32 battleKeyB = keccak256(
abi.encodePacked(battleId, battle.players[1])
);
CharacterProxy storage proxyA = characterProxies[battleKeyA][
battle.players[0]
];
CharacterProxy storage proxyB = characterProxies[battleKeyB][
battle.players[1]
];
_resolveStatusEffects(proxyA);
console.log("proxyA");
_resolveStatusEffects(proxyB);
console.log("proxyB");
if (proxyA.isStunned) {
battle.moves[0] = uint256(Move.DO_NOTHING);
console.log("Player 1 is stunned, miss a turn");
}
if (proxyB.isStunned) {
battle.moves[1] = uint256(Move.DO_NOTHING);
console.log("Player 2 is stunned, miss a turn");
}
battle.moves[0] == uint256(Move.ATTACK) &&
battle.moves[1] == uint256(Move.ATTACK)
) {
console.log("Both players attack");
uint256 damageA = calculateAttackDamage(proxyA.attack);
uint256 damageB = calculateAttackDamage(proxyB.attack);
proxyB.health = proxyB.health > damageA
? proxyB.health - damageA
: 0;
proxyA.health = proxyA.health > damageB
? proxyA.health - damageB
: 0;
proxyA.mana -= 3;
proxyB.mana -= 3;
} else if (
battle.moves[0] == uint256(Move.DEFEND) &&
battle.moves[1] == uint256(Move.DEFEND)
) {
console.log("Both players defend");
proxyA.mana += 3;
proxyB.mana += 3;
} else if (
battle.moves[0] == uint256(Move.ATTACK) &&
battle.moves[1] == uint256(Move.DEFEND)
) {
console.log("Player 1 attacks, player 2 defends");
uint256 damageA = calculateAttackDamage(proxyA.attack);
if (proxyB.defense < damageA) {
uint256 damage = damageA - proxyB.defense;
proxyB.health = proxyB.health > damage
? proxyB.health - damage
: 0;
}
proxyA.mana -= 3;
proxyB.mana += 3;
} else if (
battle.moves[0] == uint256(Move.DEFEND) &&
battle.moves[1] == uint256(Move.ATTACK)
) {
console.log("Player 2 attacks, player 1 defends");
uint256 damageB = calculateAttackDamage(proxyB.attack);
if (proxyA.defense < damageB) {
uint256 damage = damageB - proxyA.defense;
proxyA.health = proxyA.health > damage
? proxyA.health - damage
: 0;
}
proxyA.mana += 3;
proxyB.mana -= 3;
} else if (
battle.moves[0] == uint256(Move.ATTACK) &&
battle.moves[1] == uint256(Move.DO_NOTHING)
) {
console.log("Player 1 attacks, player 2 does nothing");
uint256 damageA = calculateAttackDamage(proxyA.attack);
proxyB.health = proxyB.health > damageA
? proxyB.health - damageA
: 0;
proxyA.mana -= 3;
} else if (
battle.moves[0] == uint256(Move.DO_NOTHING) &&
battle.moves[1] == uint256(Move.ATTACK)
) {
console.log("Player 1 does nothing, player 2 attacks");
uint256 damageB = calculateAttackDamage(proxyB.attack);
proxyA.health = proxyA.health > damageB
? proxyA.health - damageB
: 0;
proxyB.mana -= 3;
} else if (
battle.moves[0] == uint256(Move.DEFEND) &&
battle.moves[1] == uint256(Move.DO_NOTHING)
) {
console.log("Player 1 defends, player 2 does nothing");
proxyA.mana += 3;
} else if (
battle.moves[0] == uint256(Move.DO_NOTHING) &&
battle.moves[1] == uint256(Move.DEFEND)
) {
console.log("Player 1 defends, player 2 does nothing");
proxyB.mana += 3;
}
if (battle.moves[0] == uint256(Move.USE_SKILL)) {
_executeSkill(proxyA, _skillId0, proxyB);
}
if (battle.moves[1] == uint256(Move.USE_SKILL)) {
_executeSkill(proxyB, _skillId1, proxyA);
}
battleId,
battle.players[0],
proxyA.health,
battle.players[1],
proxyB.health
);
console.log("Player 1 Health: ", proxyA.health);
console.log("Player 2 Health: ", proxyB.health);
console.log("Player 1 Mana: ", proxyA.mana);
console.log("Player 2 Mana: ", proxyB.mana);
if (proxyA.health == 0 || proxyB.health == 0) {
address winner = proxyA.health > proxyB.health
? battle.players[0]
: battle.players[1];
_endBattle(battleId, winner);
battle.moveSubmitted[0] = false;
battle.moveSubmitted[1] = false;
}
}
| 852,429
|
./full_match/1/0x9d11FBc78BA0d95eEbA144870d8B633489ab3dE1/sources/anyswapRouterAttact.sol
|
return 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
|
function underlying() external view returns (address) {
return underlying_token;
}
| 17,085,212
|
// Sources flattened with hardhat v2.5.0 https://hardhat.org
// File @openzeppelin/contracts/token/ERC20/IERC20.sol@v4.2.0
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File contracts/libs/TransferHelper.sol
// GPL-3.0-or-later
pragma solidity ^0.8.6;
// 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,uint)')));
(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,uint)')));
(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,uint)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
// File contracts/interfaces/IHedgeSwap.sol
// GPL-3.0-or-later
pragma solidity ^0.8.6;
/// @dev DCU分发合约
interface IHedgeSwap {
// /// @dev 通过存入nest来初始化资金池,没存入x个nest,资金池增加x个dcu和x个nest,同时用户得到x个dcu
// /// @param amount 存入数量
// function deposit(uint amount) external;
/// @dev 使用确定数量的nest兑换dcu
/// @param nestAmount nest数量
/// @return dcuAmount 兑换到的dcu数量
function swapForDCU(uint nestAmount) external returns (uint dcuAmount);
/// @dev 使用确定数量的dcu兑换nest
/// @param dcuAmount dcu数量
/// @return nestAmount 兑换到的nest数量
function swapForNEST(uint dcuAmount) external returns (uint nestAmount);
/// @dev 使用nest兑换确定数量的dcu
/// @param dcuAmount 预期得到的dcu数量
/// @return nestAmount 支付的nest数量
function swapExactDCU(uint dcuAmount) external returns (uint nestAmount);
/// @dev 使用dcu兑换确定数量的nest
/// @param nestAmount 预期得到的nest数量
/// @return dcuAmount 支付的dcu数量
function swapExactNEST(uint nestAmount) external returns (uint dcuAmount);
}
// File contracts/interfaces/IHedgeMapping.sol
// GPL-3.0-or-later
pragma solidity ^0.8.6;
/// @dev The interface defines methods for Hedge builtin contract address mapping
interface IHedgeMapping {
/// @dev Set the built-in contract address of the system
/// @param dcuToken Address of dcu token contract
/// @param hedgeDAO IHedgeDAO implementation contract address
/// @param hedgeOptions IHedgeOptions implementation contract address
/// @param hedgeFutures IHedgeFutures implementation contract address
/// @param hedgeVaultForStaking IHedgeVaultForStaking implementation contract address
/// @param nestPriceFacade INestPriceFacade implementation contract address
function setBuiltinAddress(
address dcuToken,
address hedgeDAO,
address hedgeOptions,
address hedgeFutures,
address hedgeVaultForStaking,
address nestPriceFacade
) external;
/// @dev Get the built-in contract address of the system
/// @return dcuToken Address of dcu token contract
/// @return hedgeDAO IHedgeDAO implementation contract address
/// @return hedgeOptions IHedgeOptions implementation contract address
/// @return hedgeFutures IHedgeFutures implementation contract address
/// @return hedgeVaultForStaking IHedgeVaultForStaking implementation contract address
/// @return nestPriceFacade INestPriceFacade implementation contract address
function getBuiltinAddress() external view returns (
address dcuToken,
address hedgeDAO,
address hedgeOptions,
address hedgeFutures,
address hedgeVaultForStaking,
address nestPriceFacade
);
/// @dev Get address of dcu token contract
/// @return Address of dcu token contract
function getDCUTokenAddress() external view returns (address);
/// @dev Get IHedgeDAO implementation contract address
/// @return IHedgeDAO implementation contract address
function getHedgeDAOAddress() external view returns (address);
/// @dev Get IHedgeOptions implementation contract address
/// @return IHedgeOptions implementation contract address
function getHedgeOptionsAddress() external view returns (address);
/// @dev Get IHedgeFutures implementation contract address
/// @return IHedgeFutures implementation contract address
function getHedgeFuturesAddress() external view returns (address);
/// @dev Get IHedgeVaultForStaking implementation contract address
/// @return IHedgeVaultForStaking implementation contract address
function getHedgeVaultForStakingAddress() external view returns (address);
/// @dev Get INestPriceFacade implementation contract address
/// @return INestPriceFacade implementation contract address
function getNestPriceFacade() external view returns (address);
/// @dev Registered address. The address registered here is the address accepted by Hedge system
/// @param key The key
/// @param addr Destination address. 0 means to delete the registration information
function registerAddress(string calldata key, address addr) external;
/// @dev Get registered address
/// @param key The key
/// @return Destination address. 0 means empty
function checkAddress(string calldata key) external view returns (address);
}
// File contracts/interfaces/IHedgeGovernance.sol
// GPL-3.0-or-later
pragma solidity ^0.8.6;
/// @dev This interface defines the governance methods
interface IHedgeGovernance is IHedgeMapping {
/// @dev Set governance authority
/// @param addr Destination address
/// @param flag Weight. 0 means to delete the governance permission of the target address. Weight is not
/// implemented in the current system, only the difference between authorized and unauthorized.
/// Here, a uint96 is used to represent the weight, which is only reserved for expansion
function setGovernance(address addr, uint flag) external;
/// @dev Get governance rights
/// @param addr Destination address
/// @return Weight. 0 means to delete the governance permission of the target address. Weight is not
/// implemented in the current system, only the difference between authorized and unauthorized.
/// Here, a uint96 is used to represent the weight, which is only reserved for expansion
function getGovernance(address addr) external view returns (uint);
/// @dev Check whether the target address has governance rights for the given target
/// @param addr Destination address
/// @param flag Permission weight. The permission of the target address must be greater than this weight
/// to pass the check
/// @return True indicates permission
function checkGovernance(address addr, uint flag) external view returns (bool);
}
// File contracts/interfaces/IHedgeDAO.sol
// GPL-3.0-or-later
pragma solidity ^0.8.6;
/// @dev This interface defines the DAO methods
interface IHedgeDAO {
/// @dev Application Flag Changed event
/// @param addr DAO application contract address
/// @param flag Authorization flag, 1 means authorization, 0 means cancel authorization
event ApplicationChanged(address addr, uint flag);
/// @dev Set DAO application
/// @param addr DAO application contract address
/// @param flag Authorization flag, 1 means authorization, 0 means cancel authorization
function setApplication(address addr, uint flag) external;
/// @dev Check DAO application flag
/// @param addr DAO application contract address
/// @return Authorization flag, 1 means authorization, 0 means cancel authorization
function checkApplication(address addr) external view returns (uint);
/// @dev Add reward
/// @param pool Destination pool
function addETHReward(address pool) external payable;
/// @dev The function returns eth rewards of specified pool
/// @param pool Destination pool
function totalETHRewards(address pool) external view returns (uint);
/// @dev Settlement
/// @param pool Destination pool. Indicates which pool to pay with
/// @param tokenAddress Token address of receiving funds (0 means ETH)
/// @param to Address to receive
/// @param value Amount to receive
function settle(address pool, address tokenAddress, address to, uint value) external payable;
}
// File contracts/HedgeBase.sol
// GPL-3.0-or-later
pragma solidity ^0.8.6;
/// @dev Base contract of Hedge
contract HedgeBase {
/// @dev IHedgeGovernance implementation contract address
address public _governance;
/// @dev To support open-zeppelin/upgrades
/// @param governance IHedgeGovernance implementation contract address
function initialize(address governance) public virtual {
require(_governance == address(0), "Hedge:!initialize");
_governance = governance;
}
/// @dev Rewritten in the implementation contract, for load other contract addresses. Call
/// super.update(newGovernance) when overriding, and override method without onlyGovernance
/// @param newGovernance IHedgeGovernance implementation contract address
function update(address newGovernance) public virtual {
address governance = _governance;
require(governance == msg.sender || IHedgeGovernance(governance).checkGovernance(msg.sender, 0), "Hedge:!gov");
_governance = newGovernance;
}
/// @dev Migrate funds from current contract to HedgeDAO
/// @param tokenAddress Destination token address.(0 means eth)
/// @param value Migrate amount
function migrate(address tokenAddress, uint value) external onlyGovernance {
address to = IHedgeGovernance(_governance).getHedgeDAOAddress();
if (tokenAddress == address(0)) {
IHedgeDAO(to).addETHReward { value: value } (address(0));
} else {
TransferHelper.safeTransfer(tokenAddress, to, value);
}
}
//---------modifier------------
modifier onlyGovernance() {
require(IHedgeGovernance(_governance).checkGovernance(msg.sender, 0), "Hedge:!gov");
_;
}
modifier noContract() {
require(msg.sender == tx.origin, "Hedge:!contract");
_;
}
}
// File contracts/HedgeFrequentlyUsed.sol
// GPL-3.0-or-later
pragma solidity ^0.8.6;
/// @dev Base contract of Hedge
contract HedgeFrequentlyUsed is HedgeBase {
// Address of DCU contract
address constant DCU_TOKEN_ADDRESS = 0xf56c6eCE0C0d6Fbb9A53282C0DF71dBFaFA933eF;
// Address of NestPriceFacade contract
address constant NEST_PRICE_FACADE_ADDRESS = 0xB5D2890c061c321A5B6A4a4254bb1522425BAF0A;
// USDT代币地址
address constant USDT_TOKEN_ADDRESS = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
// USDT代币的基数
uint constant USDT_BASE = 1000000;
}
// File @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol@v4.2.0
// MIT
pragma solidity ^0.8.0;
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// File @openzeppelin/contracts/utils/Context.sol@v4.2.0
// 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;
}
}
// File @openzeppelin/contracts/token/ERC20/ERC20.sol@v4.2.0
// MIT
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// File contracts/DCU.sol
// GPL-3.0-or-later
pragma solidity ^0.8.6;
/// @dev DCU代币
contract DCU is HedgeBase, ERC20("Decentralized Currency Unit", "DCU") {
// 保存挖矿权限地址
mapping(address=>uint) _minters;
constructor() {
}
modifier onlyMinter {
require(_minters[msg.sender] == 1, "DCU:not minter");
_;
}
/// @dev 设置挖矿权限
/// @param account 目标账号
/// @param flag 挖矿权限标记,只有1表示可以挖矿
function setMinter(address account, uint flag) external onlyGovernance {
_minters[account] = flag;
}
/// @dev 检查挖矿权限
/// @param account 目标账号
/// @return flag 挖矿权限标记,只有1表示可以挖矿
function checkMinter(address account) external view returns (uint) {
return _minters[account];
}
/// @dev 铸币
/// @param to 接受地址
/// @param value 铸币数量
function mint(address to, uint value) external onlyMinter {
_mint(to, value);
}
/// @dev 销毁
/// @param from 目标地址
/// @param value 销毁数量
function burn(address from, uint value) external onlyMinter {
_burn(from, value);
}
}
// File contracts/HedgeSwap.sol
// GPL-3.0-or-later
pragma solidity ^0.8.6;
/// @dev DCU分发合约
contract HedgeSwap is HedgeFrequentlyUsed, IHedgeSwap {
// NEST代币地址
address constant NEST_TOKEN_ADDRESS = 0x04abEdA201850aC0124161F037Efd70c74ddC74C;
// K值,初始化存入1500万nest,同时增发1500万dcu到资金池
uint constant K = 15000000 ether * 15000000 ether;
constructor() {
}
/// @dev Swap token
/// @param src Src token address
/// @param dest Dest token address
/// @param to The target address receiving the ETH
/// @param payback As the charging fee may change, it is suggested that the caller pay more fees,
/// and the excess fees will be returned through this address
/// @return amountOut The real amount of ETH transferred out of pool
/// @return mined The amount of CoFi which will be mind by this trade
function swap(
address src,
address dest,
uint /*amountIn*/,
address to,
address payback
) external payable returns (
uint amountOut,
uint mined
) {
if (msg.value > 0) {
// payable(payback).transfer(msg.value);
TransferHelper.safeTransferETH(payback, msg.value);
}
// K值是固定常量,伪造amountIn没有意义
if (src == NEST_TOKEN_ADDRESS && dest == DCU_TOKEN_ADDRESS) {
amountOut = _swap(NEST_TOKEN_ADDRESS, DCU_TOKEN_ADDRESS, to);
} else if (src == DCU_TOKEN_ADDRESS && dest == NEST_TOKEN_ADDRESS) {
amountOut = _swap(DCU_TOKEN_ADDRESS, NEST_TOKEN_ADDRESS, to);
} else {
revert("HS:pair not allowed");
}
mined = 0;
}
/// @dev 使用确定数量的nest兑换dcu
/// @param nestAmount nest数量
/// @return dcuAmount 兑换到的dcu数量
function swapForDCU(uint nestAmount) external override returns (uint dcuAmount) {
TransferHelper.safeTransferFrom(NEST_TOKEN_ADDRESS, msg.sender, address(this), nestAmount);
dcuAmount = _swap(NEST_TOKEN_ADDRESS, DCU_TOKEN_ADDRESS, msg.sender);
}
/// @dev 使用确定数量的dcu兑换nest
/// @param dcuAmount dcu数量
/// @return nestAmount 兑换到的nest数量
function swapForNEST(uint dcuAmount) external override returns (uint nestAmount) {
TransferHelper.safeTransferFrom(DCU_TOKEN_ADDRESS, msg.sender, address(this), dcuAmount);
nestAmount = _swap(DCU_TOKEN_ADDRESS, NEST_TOKEN_ADDRESS, msg.sender);
}
/// @dev 使用nest兑换确定数量的dcu
/// @param dcuAmount 预期得到的dcu数量
/// @return nestAmount 支付的nest数量
function swapExactDCU(uint dcuAmount) external override returns (uint nestAmount) {
nestAmount = _swapExact(NEST_TOKEN_ADDRESS, DCU_TOKEN_ADDRESS, dcuAmount, msg.sender);
}
/// @dev 使用dcu兑换确定数量的nest
/// @param nestAmount 预期得到的nest数量
/// @return dcuAmount 支付的dcu数量
function swapExactNEST(uint nestAmount) external override returns (uint dcuAmount) {
dcuAmount = _swapExact(DCU_TOKEN_ADDRESS, NEST_TOKEN_ADDRESS, nestAmount, msg.sender);
}
// 使用确定数量的token兑换目标token
function _swap(address src, address dest, address to) private returns (uint amountOut) {
uint balance0 = IERC20(src).balanceOf(address(this));
uint balance1 = IERC20(dest).balanceOf(address(this));
amountOut = balance1 - K / balance0;
TransferHelper.safeTransfer(dest, to, amountOut);
}
// 使用token兑换预期数量的token
function _swapExact(address src, address dest, uint amountOut, address to) private returns (uint amountIn) {
uint balance0 = IERC20(src).balanceOf(address(this));
uint balance1 = IERC20(dest).balanceOf(address(this));
amountIn = K / (balance1 - amountOut) - balance0;
TransferHelper.safeTransferFrom(src, msg.sender, address(this), amountIn);
TransferHelper.safeTransfer(dest, to, amountOut);
}
}
|
DCU分发合约 / 通过存入nest来初始化资金池,没存入x个nest,资金池增加x个dcu和x个nest,同时用户得到x个dcu / amount 存入数量 function deposit(uint amount) external;
|
interface IHedgeSwap {
function swapForDCU(uint nestAmount) external returns (uint dcuAmount);
function swapForNEST(uint dcuAmount) external returns (uint nestAmount);
function swapExactDCU(uint dcuAmount) external returns (uint nestAmount);
function swapExactNEST(uint nestAmount) external returns (uint dcuAmount);
}
| 14,659,972
|
pragma solidity ^0.4.23;
/*
* Creator: LYF (Lyfcoin)
*/
/*
* 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;
}
/**
* Lyfcoin smart contract.
*/
contract LYFToken is AbstractToken {
/**
* Maximum allowed number of tokens in circulation.
* tokenSupply = tokensIActuallyWant * (10 ^ decimals)
*/
uint256 constant MAX_TOKEN_COUNT = 120000000 * (10**8);
/**
* Address of the owner of this smart contract.
*/
address private owner;
/**
* 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 LYFToken () {
owner = 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 = "Lyfcoin";
string constant public symbol = "LYF";
uint8 constant public decimals = 8;
/**
* 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);
}
/**
* Create _value new tokens and give new created tokens to msg.sender.
* May only be called by smart contract owner.
*
* @param _value number of tokens to create
* @return true if tokens were created successfully, false otherwise
*/
function createTokens(uint256 _value)
returns (bool success) {
require (msg.sender == owner);
if (_value > 0) {
if (_value > safeSub (MAX_TOKEN_COUNT, tokenCount)) return false;
accounts [msg.sender] = safeAdd (accounts [msg.sender], _value);
tokenCount = safeAdd (tokenCount, _value);
// adding transfer event and _from address as null address
emit Transfer(0x0, msg.sender, _value);
return true;
}
return false;
}
/**
* 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);
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);
}
|
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 = "Lyfcoin";
string constant public symbol = "LYF";
uint8 constant public decimals = 8;
| 7,893,321
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.8.0;
import "./IBeneficiaryVaults.sol";
import "./IBeneficiaryRegistry.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/cryptography/MerkleProof.sol";
contract BeneficiaryVaults is IBeneficiaryVaults, Ownable, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 public immutable pop;
IBeneficiaryRegistry public beneficiaryRegistry;
uint256 public totalVaultedBalance = 0;
Vault[3] private vaults;
enum VaultStatus {Initialized, Open, Closed}
struct Vault {
uint256 totalAllocated;
uint256 currentBalance;
uint256 unclaimedShare;
mapping(address => bool) claimed;
bytes32 merkleRoot;
uint256 endTime;
VaultStatus status;
}
event VaultInitialized(uint8 vaultId, bytes32 merkleRoot);
event VaultOpened(uint8 vaultId);
event VaultClosed(uint8 vaultId);
event RewardsDistributed(uint256 amount);
event RewardAllocated(uint8 vaultId, uint256 amount);
event RewardClaimed(uint8 vaultId, address beneficiary, uint256 amount);
event BeneficiaryRegistryChanged(
IBeneficiaryRegistry from,
IBeneficiaryRegistry to
);
modifier vaultExists(uint8 vaultId_) {
require(vaultId_ < 3, "Invalid vault id");
require(vaults[vaultId_].endTime > 0, "Uninitialized vault slot");
_;
}
constructor(IERC20 pop_, IBeneficiaryRegistry beneficiaryRegistry_) {
pop = pop_;
beneficiaryRegistry = beneficiaryRegistry_;
}
/**
* @notice Overrides existing BeneficiaryRegistry contract
* @param beneficiaryRegistry_ Address of new BeneficiaryRegistry contract
* @dev Must implement IBeneficiaryRegistry and cannot be same as existing
*/
function setBeneficiaryRegistry(IBeneficiaryRegistry beneficiaryRegistry_)
public
onlyOwner
{
require(
beneficiaryRegistry != beneficiaryRegistry_,
"Same BeneficiaryRegistry"
);
IBeneficiaryRegistry _beneficiaryRegistry = beneficiaryRegistry;
beneficiaryRegistry = beneficiaryRegistry_;
emit BeneficiaryRegistryChanged(_beneficiaryRegistry, beneficiaryRegistry);
}
/**
* @notice Initializes a vault for beneficiary claims
* @param vaultId_ Vault ID in range 0-2
* @param endTime_ Unix timestamp in seconds after which a vault can be closed
* @param merkleRoot_ Merkle root to support claims
* @dev Vault cannot be initialized if it is currently in an open state, otherwise existing data is reset*
*/
function initializeVault(
uint8 vaultId_,
uint256 endTime_,
bytes32 merkleRoot_
) public onlyOwner {
require(vaultId_ < 3, "Invalid vault id");
require(endTime_ > block.timestamp, "Invalid end block");
require(
vaults[vaultId_].status != VaultStatus.Open,
"Vault must not be open"
);
delete vaults[vaultId_];
Vault storage v = vaults[vaultId_];
v.totalAllocated = 0;
v.currentBalance = 0;
v.unclaimedShare = 100e18;
v.merkleRoot = merkleRoot_;
v.endTime = endTime_;
v.status = VaultStatus.Initialized;
emit VaultInitialized(vaultId_, merkleRoot_);
}
/**
* @notice Open a vault it can receive rewards and accept claims
* @dev Vault must be in an initialized state
* @param vaultId_ Vault ID in range 0-2
*/
function openVault(uint8 vaultId_) public onlyOwner vaultExists(vaultId_) {
require(
vaults[vaultId_].status == VaultStatus.Initialized,
"Vault must be initialized"
);
vaults[vaultId_].status = VaultStatus.Open;
emit VaultOpened(vaultId_);
}
/**
* @notice Close an open vault and redirect rewards to other vaults
* @dev Vault must be in an open state
* @param vaultId_ Vault ID in range 0-2
*/
function closeVault(uint8 vaultId_) public onlyOwner vaultExists(vaultId_) {
require(vaults[vaultId_].status == VaultStatus.Open, "Vault must be open");
require(block.timestamp >= vaults[vaultId_].endTime, "Vault has not ended");
uint256 _remainingBalance = vaults[vaultId_].currentBalance;
vaults[vaultId_].currentBalance = 0;
vaults[vaultId_].status = VaultStatus.Closed;
if (_remainingBalance > 0) {
totalVaultedBalance = totalVaultedBalance.sub(_remainingBalance);
_allocateRewards(_remainingBalance);
}
emit VaultClosed(vaultId_);
}
/**
* @notice Verifies a valid claim with no cost
* @param vaultId_ Vault ID in range 0-2
* @param proof_ Merkle proof of path to leaf element
* @param beneficiary_ Beneficiary address encoded in leaf element
* @param share_ Beneficiary expected share encoded in leaf element
* @return Returns boolean true or false if claim is valid
*/
function verifyClaim(
uint8 vaultId_,
bytes32[] memory proof_,
address beneficiary_,
uint256 share_
) public view vaultExists(vaultId_) returns (bool) {
require(msg.sender == beneficiary_, "Sender must be beneficiary");
require(vaults[vaultId_].status == VaultStatus.Open, "Vault must be open");
require(
beneficiaryRegistry.beneficiaryExists(beneficiary_) == true,
"Beneficiary does not exist"
);
return
MerkleProof.verify(
proof_,
vaults[vaultId_].merkleRoot,
bytes32(keccak256(abi.encodePacked(beneficiary_, share_)))
);
}
/**
* @notice Transfers POP tokens only once to beneficiary on successful claim
* @dev Applies any outstanding rewards before processing claim
* @param vaultId_ Vault ID in range 0-2
* @param proof_ Merkle proof of path to leaf element
* @param beneficiary_ Beneficiary address encoded in leaf element
* @param share_ Beneficiary expected share encoded in leaf element
*/
function claimReward(
uint8 vaultId_,
bytes32[] memory proof_,
address beneficiary_,
uint256 share_
) public nonReentrant vaultExists(vaultId_) {
require(
verifyClaim(vaultId_, proof_, beneficiary_, share_) == true,
"Invalid claim"
);
require(hasClaimed(vaultId_, beneficiary_) == false, "Already claimed");
uint256 _reward =
vaults[vaultId_].currentBalance.mul(share_).div(
vaults[vaultId_].unclaimedShare
);
require(_reward > 0, "No reward");
totalVaultedBalance = totalVaultedBalance.sub(_reward);
vaults[vaultId_].currentBalance = vaults[vaultId_].currentBalance.sub(
_reward
);
vaults[vaultId_].unclaimedShare = vaults[vaultId_].unclaimedShare.sub(
share_
);
vaults[vaultId_].claimed[beneficiary_] = true;
pop.transfer(beneficiary_, _reward);
emit RewardClaimed(vaultId_, beneficiary_, _reward);
}
/**
* @notice Distribute unallocated POP token balance to vaults
* @dev Requires at least one open vault
*/
function distributeRewards() public nonReentrant {
uint8 _openVaultCount = _getOpenVaultCount();
require(_openVaultCount > 0, "No open vaults");
uint256 _availableReward =
pop.balanceOf(address(this)).sub(totalVaultedBalance);
_allocateRewards(_availableReward);
emit RewardsDistributed(_availableReward);
}
function _allocateRewards(uint256 amount_) internal {
require(amount_ > 0, "Invalid amount");
uint8 _openVaultCount = _getOpenVaultCount();
if (_openVaultCount == 0) return;
totalVaultedBalance = totalVaultedBalance.add(amount_);
//@todo handle dust after div
uint256 _allocation = amount_.div(_openVaultCount);
for (uint8 _vaultId = 0; _vaultId < vaults.length; _vaultId++) {
if (vaults[_vaultId].status == VaultStatus.Open) {
vaults[_vaultId].totalAllocated = vaults[_vaultId].totalAllocated.add(
_allocation
);
vaults[_vaultId].currentBalance = vaults[_vaultId].currentBalance.add(
_allocation
);
emit RewardAllocated(_vaultId, _allocation);
}
}
}
function getVault(uint8 vaultId_)
public
view
vaultExists(vaultId_)
returns (
uint256 totalAllocated,
uint256 currentBalance,
uint256 unclaimedShare,
bytes32 merkleRoot,
uint256 endTime,
VaultStatus status
)
{
totalAllocated = vaults[vaultId_].totalAllocated;
currentBalance = vaults[vaultId_].currentBalance;
unclaimedShare = vaults[vaultId_].unclaimedShare;
merkleRoot = vaults[vaultId_].merkleRoot;
endTime = vaults[vaultId_].endTime;
status = vaults[vaultId_].status;
}
function hasClaimed(uint8 vaultId_, address beneficiary_)
public
view
vaultExists(vaultId_)
returns (bool)
{
return vaults[vaultId_].claimed[beneficiary_];
}
function _getOpenVaultCount() internal view returns (uint8) {
uint8 _openVaultCount = 0;
for (uint8 i = 0; i < vaults.length; i++) {
if (vaults[i].status == VaultStatus.Open) {
_openVaultCount++;
}
}
return _openVaultCount;
}
}
|
Close an open vault and redirect rewards to other vaults Vault must be in an open state vaultId_ Vault ID in range 0-2/
|
function closeVault(uint8 vaultId_) public onlyOwner vaultExists(vaultId_) {
require(vaults[vaultId_].status == VaultStatus.Open, "Vault must be open");
require(block.timestamp >= vaults[vaultId_].endTime, "Vault has not ended");
uint256 _remainingBalance = vaults[vaultId_].currentBalance;
vaults[vaultId_].currentBalance = 0;
vaults[vaultId_].status = VaultStatus.Closed;
if (_remainingBalance > 0) {
totalVaultedBalance = totalVaultedBalance.sub(_remainingBalance);
_allocateRewards(_remainingBalance);
}
emit VaultClosed(vaultId_);
}
| 5,418,909
|
./full_match/1/0x196a4cd6c6A1441A46C5D884DE148Fe6e1E950F7/sources/contracts/usdy/allowlist/AllowlistUpgradeable.sol
|
Gets a list term indexes that are valid for a user to be on the allowlist/
|
function getValidTermIndexes()
external
view
override
returns (uint256[] memory)
{
return validIndexes;
}
| 8,469,143
|
/**
*Submitted for verification at Etherscan.io on 2022-01-19
*/
//SPDX-License-Identifier: lgplv3 OR MIT
// File: @openzeppelin/contracts/proxy/Proxy.sol
// OpenZeppelin Contracts v4.4.1 (proxy/Proxy.sol)
pragma solidity ^0.8.0;
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
* and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_beforeFallback();
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback() external payable virtual {
_fallback();
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
* is empty.
*/
receive() external payable virtual {
_fallback();
}
/**
* @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
* call, or as part of the Solidity `fallback` or `receive` functions.
*
* If overriden should call `super._beforeFallback()`.
*/
function _beforeFallback() internal virtual {}
}
// File: @openzeppelin/contracts/proxy/beacon/IBeacon.sol
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/utils/StorageSlot.sol
// OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
// File: @openzeppelin/contracts/proxy/ERC1967/ERC1967Upgrade.sol
// OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967Upgrade {
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallSecure(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
address oldImplementation = _getImplementation();
// Initial upgrade and setup call
_setImplementation(newImplementation);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(newImplementation, data);
}
// Perform rollback test if not already in progress
StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot(_ROLLBACK_SLOT);
if (!rollbackTesting.value) {
// Trigger rollback using upgradeTo from the new implementation
rollbackTesting.value = true;
Address.functionDelegateCall(
newImplementation,
abi.encodeWithSignature("upgradeTo(address)", oldImplementation)
);
rollbackTesting.value = false;
// Check rollback was effective
require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
// Finally reset to the new implementation and log the upgrade
_upgradeTo(newImplementation);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
Address.isContract(IBeacon(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
}
}
}
// File: @openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol
// OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Proxy.sol)
pragma solidity ^0.8.0;
/**
* @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
* implementation address that can be changed. This address is stored in storage in the location specified by
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
* implementation behind the proxy.
*/
contract ERC1967Proxy is Proxy, ERC1967Upgrade {
/**
* @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
*
* If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded
* function call, and allows initializating the storage of the proxy like a Solidity constructor.
*/
constructor(address _logic, bytes memory _data) payable {
assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
_upgradeToAndCall(_logic, _data, false);
}
/**
* @dev Returns the current implementation address.
*/
function _implementation() internal view virtual override returns (address impl) {
return ERC1967Upgrade._getImplementation();
}
}
// File: @openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol
// OpenZeppelin Contracts v4.4.1 (proxy/transparent/TransparentUpgradeableProxy.sol)
pragma solidity ^0.8.0;
/**
* @dev This contract implements a proxy that is upgradeable by an admin.
*
* To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector
* clashing], which can potentially be used in an attack, this contract uses the
* https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two
* things that go hand in hand:
*
* 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if
* that call matches one of the admin functions exposed by the proxy itself.
* 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the
* implementation. If the admin tries to call a function on the implementation it will fail with an error that says
* "admin cannot fallback to proxy target".
*
* These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing
* the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due
* to sudden errors when trying to call a function from the proxy implementation.
*
* Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way,
* you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.
*/
contract TransparentUpgradeableProxy is ERC1967Proxy {
/**
* @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and
* optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}.
*/
constructor(
address _logic,
address admin_,
bytes memory _data
) payable ERC1967Proxy(_logic, _data) {
assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1));
_changeAdmin(admin_);
}
/**
* @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.
*/
modifier ifAdmin() {
if (msg.sender == _getAdmin()) {
_;
} else {
_fallback();
}
}
/**
* @dev Returns the current admin.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
* https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function admin() external ifAdmin returns (address admin_) {
admin_ = _getAdmin();
}
/**
* @dev Returns the current implementation.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
* https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
*/
function implementation() external ifAdmin returns (address implementation_) {
implementation_ = _implementation();
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}.
*/
function changeAdmin(address newAdmin) external virtual ifAdmin {
_changeAdmin(newAdmin);
}
/**
* @dev Upgrade the implementation of the proxy.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}.
*/
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeToAndCall(newImplementation, bytes(""), false);
}
/**
* @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified
* by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the
* proxied contract.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin {
_upgradeToAndCall(newImplementation, data, true);
}
/**
* @dev Returns the current admin.
*/
function _admin() internal view virtual returns (address) {
return _getAdmin();
}
/**
* @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}.
*/
function _beforeFallback() internal virtual override {
require(msg.sender != _getAdmin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target");
super._beforeFallback();
}
}
// File: contracts/ERC721TokenReceiver.sol
pragma solidity ^0.8.0;
contract ERC721TokenReceiver {
function onERC721Received(
address,
address,
uint256,
bytes memory
) external pure returns (bytes4) {
return ERC721TokenReceiver.onERC721Received.selector;
}
}
// File: contracts/MultiSigWallet.sol
pragma solidity ^0.8.0;
/// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution.
/// @author Stefan George - <[email protected]>
contract MultiSigWallet {
/*
* Events
*/
event Confirmation(address indexed sender, uint indexed transactionId);
event Revocation(address indexed sender, uint indexed transactionId);
event Submission(uint indexed transactionId);
event Execution(uint indexed transactionId);
event ExecutionFailure(uint indexed transactionId);
event Deposit(address indexed sender, uint value);
event OwnerAddition(address indexed owner);
event OwnerRemoval(address indexed owner);
event RequirementChange(uint required);
/*
* Constants
*/
uint constant public MAX_OWNER_COUNT = 50;
/*
* Storage
*/
mapping(uint => Transaction) public transactions;
mapping(uint => mapping(address => bool)) public confirmations;
mapping(address => bool) public isOwner;
address[] public owners;
uint public required;
uint public transactionCount;
struct Transaction {
address destination;
uint value;
bytes data;
bool executed;
}
/*
* Modifiers
*/
modifier onlyWallet() {
require(msg.sender == address(this));
_;
}
modifier ownerDoesNotExist(address owner) {
require(!isOwner[owner]);
_;
}
modifier ownerExists(address owner) {
require(isOwner[owner]);
_;
}
modifier transactionExists(uint transactionId) {
require(transactions[transactionId].destination != (address)(0));
_;
}
modifier confirmed(uint transactionId, address owner) {
require(confirmations[transactionId][owner]);
_;
}
modifier notConfirmed(uint transactionId, address owner) {
require(!confirmations[transactionId][owner]);
_;
}
modifier notExecuted(uint transactionId) {
require(!transactions[transactionId].executed);
_;
}
modifier notNull(address _address) {
require(_address != (address)(0));
_;
}
modifier validRequirement(uint ownerCount, uint _required) {
require(ownerCount <= MAX_OWNER_COUNT
&& _required <= ownerCount
&& _required != 0
&& ownerCount != 0);
_;
}
/// @dev Fallback function allows to deposit ether.
fallback() external payable
{
if (msg.value > 0)
emit Deposit(msg.sender, msg.value);
}
receive() external payable
{
if (msg.value > 0)
emit Deposit(msg.sender, msg.value);
}
/*
* Public functions
*/
/// @dev Contract constructor sets initial owners and required number of confirmations.
/// @param _owners List of initial owners.
/// @param _required Number of required confirmations.
constructor(address[] memory _owners, uint _required)
// validRequirement(_owners.length, _required)
{
required = 0;
if (_owners.length > 0 || _required > 0){
initialize(_owners, _required);
}
}
function initialize(address[] memory _owners, uint _required) internal
validRequirement(_owners.length, _required)
{
require(required == 0, "MS00");
for (uint i = 0; i < _owners.length; i++) {
require(!isOwner[_owners[i]] && _owners[i] != (address)(0));
isOwner[_owners[i]] = true;
}
owners = _owners;
required = _required;
}
/// @dev Allows to add a new owner. Transaction has to be sent by wallet.
/// @param owner Address of new owner.
function addOwner(address owner)
public virtual
onlyWallet
ownerDoesNotExist(owner)
notNull(owner)
validRequirement(owners.length + 1, required)
{
isOwner[owner] = true;
owners.push(owner);
emit OwnerAddition(owner);
}
/// @dev Allows to remove an owner. Transaction has to be sent by wallet.
/// @param owner Address of owner.
function removeOwner(address owner)
public virtual
onlyWallet
ownerExists(owner)
{
require (owners.length > 1, "owners.length must larger than 1");
isOwner[owner] = false;
for (uint i = 0; i < owners.length; i++)
if (owners[i] == owner) {
owners[i] = owners[owners.length - 1];
owners.pop();
break;
}
// owners.length -= 1;
if (required > owners.length)
changeRequirement(owners.length);
emit OwnerRemoval(owner);
}
/// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet.
/// @param owner Address of owner to be replaced.
/// @param newOwner Address of new owner.
function replaceOwner(address owner, address newOwner)
public virtual
onlyWallet
ownerExists(owner)
ownerDoesNotExist(newOwner)
{
for (uint i = 0; i < owners.length; i++)
if (owners[i] == owner) {
owners[i] = newOwner;
break;
}
isOwner[owner] = false;
isOwner[newOwner] = true;
emit OwnerRemoval(owner);
emit OwnerAddition(newOwner);
}
/// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet.
/// @param _required Number of required confirmations.
function changeRequirement(uint _required)
public virtual
onlyWallet
validRequirement(owners.length, _required)
{
required = _required;
emit RequirementChange(_required);
}
/// @dev Allows an owner to submit and confirm a transaction.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return transactionId Returns transaction ID.
function submitTransaction(address destination, uint value, bytes memory data)
public
returns (uint transactionId)
{
transactionId = addTransaction(destination, value, data);
confirmTransaction(transactionId);
}
/// @dev Allows an owner to confirm a transaction.
/// @param transactionId Transaction ID.
function confirmTransaction(uint transactionId)
public payable
ownerExists(msg.sender)
transactionExists(transactionId)
notConfirmed(transactionId, msg.sender)
{
confirmations[transactionId][msg.sender] = true;
emit Confirmation(msg.sender, transactionId);
executeTransaction(transactionId);
}
/// @dev Allows an owner to revoke a confirmation for a transaction.
/// @param transactionId Transaction ID.
function revokeConfirmation(uint transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
confirmations[transactionId][msg.sender] = false;
emit Revocation(msg.sender, transactionId);
}
/// @dev Allows anyone to execute a confirmed transaction.
/// @param transactionId Transaction ID.
function executeTransaction(uint transactionId)
public payable virtual
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
if (isConfirmed(transactionId)) {
Transaction storage txn = transactions[transactionId];
txn.executed = true;
if (external_call(txn.destination, txn.value, txn.data.length, txn.data))
emit Execution(transactionId);
else {
emit ExecutionFailure(transactionId);
txn.executed = false;
}
}
}
// call has been separated into its own function in order to take advantage
// of the Solidity's code generator to produce a loop that copies tx.data into memory.
function external_call(address destination, uint value, uint dataLength, bytes memory data) internal returns (bool) {
//return tx.destination.call.gas(gasleft()-34710).value(tx.value)(tx.data);
bool result;
uint __gas = gasleft() - 34710;
assembly {
let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention)
let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that
// 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)
result := call(
__gas,
destination,
value,
d,
dataLength, // Size of the input (in bytes) - this is what fixes the padding problem
x,
0 // Output is ignored, therefore the output size is zero
)
}
return result;
}
/// @dev Returns the confirmation status of a transaction.
/// @param transactionId Transaction ID.
/// @return confirmedResult Confirmation status.
function isConfirmed(uint transactionId)
public
view
returns (bool confirmedResult)
{
confirmedResult=false;
uint count = 0;
for (uint i = 0; i < owners.length; i++) {
if (confirmations[transactionId][owners[i]])
count += 1;
if (count == required){
confirmedResult=true;
return confirmedResult;
}
}
}
/*
* Internal functions
*/
/// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return transactionId Returns transaction ID.
function addTransaction(address destination, uint value, bytes memory data)
internal
notNull(destination)
returns (uint transactionId)
{
transactionId = transactionCount;
transactions[transactionId] = Transaction({
destination : destination,
value : value,
data : data,
executed : false
});
transactionCount += 1;
emit Submission(transactionId);
}
/*
* Web3 call functions
*/
/// @dev Returns number of confirmations of a transaction.
/// @param transactionId Transaction ID.
/// @return count Number of confirmations.
function getConfirmationCount(uint transactionId)
public
view
returns (uint count)
{
for (uint i = 0; i < owners.length; i++)
if (confirmations[transactionId][owners[i]])
count += 1;
}
/// @dev Returns total number of transactions after filers are applied.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return count Total number of transactions after filters are applied.
function getTransactionCount(bool pending, bool executed)
public
view
returns (uint count)
{
for (uint i = 0; i < transactionCount; i++)
if (pending && !transactions[i].executed
|| executed && transactions[i].executed)
count += 1;
}
/// @dev Returns list of owners.
/// @return List of owner addresses.
function getOwners()
public
view
returns (address[] memory)
{
return owners;
}
/// @dev Returns array with owner addresses, which confirmed transaction.
/// @param transactionId Transaction ID.
/// @return _confirmations Returns array of owner addresses.
function getConfirmations(uint transactionId)
public
view
returns (address[] memory _confirmations)
{
address[] memory confirmationsTemp = new address[](owners.length);
uint count = 0;
uint i;
for (i = 0; i < owners.length; i++)
if (confirmations[transactionId][owners[i]]) {
confirmationsTemp[count] = owners[i];
count += 1;
}
_confirmations = new address[](count);
for (i = 0; i < count; i++)
_confirmations[i] = confirmationsTemp[i];
}
/// @dev Returns list of transaction IDs in defined range.
/// @param from Index start position of transaction array.
/// @param to Index end position of transaction array.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return _transactionIds Returns array of transaction IDs.
function getTransactionIds(uint from, uint to, bool pending, bool executed)
public
view
returns (uint[] memory _transactionIds)
{
uint[] memory transactionIdsTemp = new uint[](transactionCount);
uint count = 0;
uint i;
for (i = 0; i < transactionCount; i++)
if (pending && !transactions[i].executed
|| executed && transactions[i].executed)
{
transactionIdsTemp[count] = i;
count += 1;
}
_transactionIds = new uint[](to - from);
for (i = from; i < to; i++)
_transactionIds[i - from] = transactionIdsTemp[i];
}
}
// File: contracts/MultiSigWalletWithPermit.sol
pragma solidity ^0.8.0;
/// @title MultiSigWalletWithPermit wallet with permit -
/// @author [email protected]
contract MultiSigWalletWithPermit is MultiSigWallet {
mapping(bytes4 => bool) internal supportedInterfaces;
bool internal ownersImmutable = true;
bool internal initialized = false;
modifier notImmutable() {
require(!ownersImmutable, "MS01");
_;
}
function addOwner(address owner) public override notImmutable {
super.addOwner(owner);
}
function removeOwner(address owner) public override notImmutable {
super.removeOwner(owner);
}
function replaceOwner(address owner, address newOwner)
public
override
notImmutable
{
super.replaceOwner(owner, newOwner);
}
function changeRequirement(uint256 _required) public override notImmutable {
super.changeRequirement(_required);
}
function supportsInterface(bytes4 interfaceID)
external
view
returns (bool)
{
return supportedInterfaces[interfaceID];
}
function setSupportsInterface(bytes4 interfaceID, bool support)
external
onlyWallet
{
supportedInterfaces[interfaceID] = support;
}
/*
* Public functions
*/
/// @dev Contract constructor sets initial owners, required number of confirmations.
/// @param _owners List of initial owners.
/// @param _required Number of required confirmations.
/// @param _immutable is owners immutable
constructor(
address[] memory _owners,
uint256 _required,
bool _immutable
) MultiSigWallet(_owners, _required) {
if (_required > 0) {
initialized = true;
setup0(_immutable);
}
}
function setup(
address[] memory _owners,
uint256 _required,
bool _immutable
) public {
require(!initialized, "MS02");
initialized = true;
super.initialize(_owners, _required);
setup0(_immutable);
}
function setup0(bool _immutable) private {
ownersImmutable = _immutable;
supportedInterfaces[0x01ffc9a7] = true;
uint256 chainId;
assembly {
chainId := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
// keccak256(
// "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
// ),
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f,
// keccak256(bytes("MultiSigWalletWithPermit")),
0x911a814036e00323c4ca54d47b0a363338990ca044824eba7a28205763e6115a,
// keccak256(bytes("1")),
0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6,
chainId,
address(this)
)
);
}
bytes32 public DOMAIN_SEPARATOR;
bytes32 public constant PERMIT_TYPEHASH =
0x8d14977a529be0cde9be2de41261d56c536e10c2bfb3f797a663ac4f3676d2fe;
/*
* executeTxWithPermits
*/
/// @dev delegate call
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @param nonce Transaction ID.
/// @return newTransactionId Returns transaction ID.
function executeTxWithPermits(
address destination,
uint256 value,
bytes memory data,
uint256 nonce,
bytes32[] memory rs,
bytes32[] memory ss,
uint8[] memory vs
) public returns (uint256 newTransactionId) {
require(isOwner[msg.sender], "MS90");
require(rs.length == ss.length, "MS91");
require(rs.length == vs.length, "MS92");
require(nonce == transactionCount, "MS93");
require(rs.length + 1 == required, "MS94");
require(destination != address(0), "MS95");
newTransactionId = addTransaction(destination, value, data);
confirmations[newTransactionId][msg.sender] = true;
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
PERMIT_TYPEHASH,
msg.sender,
destination,
value,
keccak256(data),
nonce
)
)
)
);
for (uint8 i = 0; i < rs.length; ++i) {
address owner = ecrecover(digest, vs[i], rs[i], ss[i]);
require(owner != address(0), "MS03");
require(isOwner[owner], "MS04");
confirmations[newTransactionId][owner] = true;
}
if (isConfirmed(newTransactionId)) {
executeTransactionInner(destination, value, data, newTransactionId);
} else {
revert("MS06");
}
}
function executeTransactionInner(
address destination,
uint256 value,
bytes memory data,
uint256 transactionId
) private {
require(address(this).balance >= value, "MS07");
(bool success, bytes memory returndata) = destination.call{
value: value
}(data);
if (success) {
transactions[transactionId].executed = true;
emit Execution(transactionId);
} else {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert("MS08");
}
}
}
}
// File: contracts/ERC1155TokenReceiver.sol
pragma solidity ^0.8.0;
contract ERC1155TokenReceiver {
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes calldata
) external pure returns (bytes4) {
return ERC1155TokenReceiver.onERC1155Received.selector;
}
function onERC1155BatchReceived(
address,
address,
uint256[] calldata,
uint256[] calldata,
bytes calldata
) external pure returns (bytes4) {
return ERC1155TokenReceiver.onERC1155BatchReceived.selector;
}
}
// File: contracts/MultiSigV1.sol
pragma solidity ^0.8.0;
/// @title MultiSigV1
/// @author [email protected]
contract MultiSigV1 is
MultiSigWalletWithPermit,
ERC721TokenReceiver,
ERC1155TokenReceiver
{
constructor(address[] memory _owners, uint256 _required,
bool _immutable)
MultiSigWalletWithPermit(_owners, _required, _immutable)
{}
function eipFeatures() public pure returns (uint256[3] memory fs) {
fs = [uint256(165), uint256(721), uint256(1155)];
}
function version() public pure returns (uint256) {
return 1;
}
}
// File: contracts/UpgradeableMultiSignWalletFactory.sol
pragma solidity ^0.8.0;
contract UpgradeableMultiSignWalletFactory {
event UpgradeableMultiSignWalletDeployed(
address indexed admin,
address indexed proxy,
address indexed impl
);
function create(
address[] memory _owners,
uint256 _required,
bool _immutable,
address _impl
) public returns (address wallet) {
MultiSigWalletWithPermit proxyAdmin = new MultiSigWalletWithPermit{
salt: keccak256(
abi.encodePacked(_owners, _required, msg.sender, _immutable)
)
}(_owners, _required, true);
bytes32 newsalt = keccak256(
abi.encodePacked(_owners, _required, msg.sender)
);
TransparentUpgradeableProxy proxy = new TransparentUpgradeableProxy{
salt: newsalt
}(_impl, address(proxyAdmin), "");
setup(_owners, _required, _immutable, address(proxy));
wallet = address(proxy);
emit UpgradeableMultiSignWalletDeployed(
address(proxyAdmin),
address(proxy),
_impl
);
}
function setup(
address[] memory _owners,
uint256 _required,
bool _immutable,
address proxy
) internal {
MultiSigWalletWithPermit walletImpl = (
MultiSigWalletWithPermit(payable(proxy))
);
walletImpl.setup(_owners, _required, _immutable);
}
}
|
Allows anyone to execute a confirmed transaction. transactionId Transaction ID.
|
function executeTransaction(uint transactionId)
public payable virtual
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
if (isConfirmed(transactionId)) {
Transaction storage txn = transactions[transactionId];
txn.executed = true;
if (external_call(txn.destination, txn.value, txn.data.length, txn.data))
emit Execution(transactionId);
else {
emit ExecutionFailure(transactionId);
txn.executed = false;
}
}
}
| 2,278,049
|
//Address: 0x2cc6ca9c3023a6a876fd54a03f68281c7aad0e8b
//Contract name: ICOPreSale
//Balance: 0 Ether
//Verification Date: 6/14/2018
//Transacion Count: 6
// CODE STARTS HERE
pragma solidity ^0.4.13;
contract ComplianceService {
function validate(address _from, address _to, uint256 _amount) public returns (bool allowed) {
return true;
}
}
contract ERC20 {
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _amount) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
function totalSupply() public constant returns (uint);
}
contract HardcodedWallets {
// **** DATA
address public walletFounder1; // founder #1 wallet, CEO, compulsory
address public walletFounder2; // founder #2 wallet
address public walletFounder3; // founder #3 wallet
address public walletCommunityReserve; // Distribution wallet
address public walletCompanyReserve; // Distribution wallet
address public walletTeamAdvisors; // Distribution wallet
address public walletBountyProgram; // Distribution wallet
// **** FUNCTIONS
/**
* @notice Constructor, set up the compliance officer oracle wallet
*/
constructor() public {
// set up the founders' oracle wallets
walletFounder1 = 0x5E69332F57Ac45F5fCA43B6b007E8A7b138c2938; // founder #1 (CEO) wallet
walletFounder2 = 0x852f9a94a29d68CB95Bf39065BED6121ABf87607; // founder #2 wallet
walletFounder3 = 0x0a339965e52dF2c6253989F5E9173f1F11842D83; // founder #3 wallet
// set up the wallets for distribution of the total supply of tokens
walletCommunityReserve = 0xB79116a062939534042d932fe5DF035E68576547;
walletCompanyReserve = 0xA6845689FE819f2f73a6b9C6B0D30aD6b4a006d8;
walletTeamAdvisors = 0x0227038b2560dF1abf3F8C906016Af0040bc894a;
walletBountyProgram = 0xdd401Df9a049F6788cA78b944c64D21760757D73;
}
}
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 System {
using SafeMath for uint256;
address owner;
// **** MODIFIERS
// @notice To limit functions usage to contract owner
modifier onlyOwner() {
if (msg.sender != owner) {
error('System: onlyOwner function called by user that is not owner');
} else {
_;
}
}
// **** FUNCTIONS
// @notice Calls whenever an error occurs, logs it or reverts transaction
function error(string _error) internal {
revert(_error);
// in case revert with error msg is not yet fully supported
// emit Error(_error);
// throw;
}
// @notice For debugging purposes when using solidity online browser, remix and sandboxes
function whoAmI() public constant returns (address) {
return msg.sender;
}
// @notice Get the current timestamp from last mined block
function timestamp() public constant returns (uint256) {
return block.timestamp;
}
// @notice Get the balance in weis of this contract
function contractBalance() public constant returns (uint256) {
return address(this).balance;
}
// @notice System constructor, defines owner
constructor() public {
// This is the constructor, so owner should be equal to msg.sender, and this method should be called just once
owner = msg.sender;
// make sure owner address is configured
if(owner == 0x0) error('System constructor: Owner address is 0x0'); // Never should happen, but just in case...
}
// **** EVENTS
// @notice A generic error log
event Error(string _error);
// @notice For debug purposes
event DebugUint256(uint256 _data);
}
contract Escrow is System, HardcodedWallets {
using SafeMath for uint256;
// **** DATA
mapping (address => uint256) public deposited;
uint256 nextStage;
// Circular reference to ICO contract
address public addressSCICO;
// Circular reference to Tokens contract
address public addressSCTokens;
Tokens public SCTokens;
// **** FUNCTIONS
/**
* @notice Constructor, set up the state
*/
constructor() public {
// copy totalSupply from Tokens to save gas
uint256 totalSupply = 1350000000 ether;
deposited[this] = totalSupply.mul(50).div(100);
deposited[walletCommunityReserve] = totalSupply.mul(20).div(100);
deposited[walletCompanyReserve] = totalSupply.mul(14).div(100);
deposited[walletTeamAdvisors] = totalSupply.mul(15).div(100);
deposited[walletBountyProgram] = totalSupply.mul(1).div(100);
}
function deposit(uint256 _amount) public returns (bool) {
// only ICO could deposit
if (msg.sender != addressSCICO) {
error('Escrow: not allowed to deposit');
return false;
}
deposited[this] = deposited[this].add(_amount);
return true;
}
/**
* @notice Withdraw funds from the tokens contract
*/
function withdraw(address _address, uint256 _amount) public onlyOwner returns (bool) {
if (deposited[_address]<_amount) {
error('Escrow: not enough balance');
return false;
}
deposited[_address] = deposited[_address].sub(_amount);
return SCTokens.transfer(_address, _amount);
}
/**
* @notice Withdraw funds from the tokens contract
*/
function fundICO(uint256 _amount, uint8 _stage) public returns (bool) {
if(nextStage !=_stage) {
error('Escrow: ICO stage already funded');
return false;
}
if (msg.sender != addressSCICO || tx.origin != owner) {
error('Escrow: not allowed to fund the ICO');
return false;
}
if (deposited[this]<_amount) {
error('Escrow: not enough balance');
return false;
}
bool success = SCTokens.transfer(addressSCICO, _amount);
if(success) {
deposited[this] = deposited[this].sub(_amount);
nextStage++;
emit FundICO(addressSCICO, _amount);
}
return success;
}
/**
* @notice The owner can specify which ICO contract is allowed to transfer tokens while timelock is on
*/
function setMyICOContract(address _SCICO) public onlyOwner {
addressSCICO = _SCICO;
}
/**
* @notice Set the tokens contract
*/
function setTokensContract(address _addressSCTokens) public onlyOwner {
addressSCTokens = _addressSCTokens;
SCTokens = Tokens(_addressSCTokens);
}
/**
* @notice Returns balance of given address
*/
function balanceOf(address _address) public constant returns (uint256 balance) {
return deposited[_address];
}
// **** EVENTS
// Triggered when an investor buys some tokens directly with Ethers
event FundICO(address indexed _addressICO, uint256 _amount);
}
contract RefundVault is HardcodedWallets, System {
using SafeMath for uint256;
enum State { Active, Refunding, Closed }
// **** DATA
mapping (address => uint256) public deposited;
mapping (address => uint256) public tokensAcquired;
State public state;
// Circular reference to ICO contract
address public addressSCICO;
// **** MODIFIERS
// @notice To limit functions usage to contract owner
modifier onlyICOContract() {
if (msg.sender != addressSCICO) {
error('RefundVault: onlyICOContract function called by user that is not ICOContract');
} else {
_;
}
}
// **** FUNCTIONS
/**
* @notice Constructor, set up the state
*/
constructor() public {
state = State.Active;
}
function weisDeposited(address _investor) public constant returns (uint256) {
return deposited[_investor];
}
function getTokensAcquired(address _investor) public constant returns (uint256) {
return tokensAcquired[_investor];
}
/**
* @notice Registers how many tokens have each investor and how many ethers they spent (When ICOing through PayIn this function is not called)
*/
function deposit(address _investor, uint256 _tokenAmount) onlyICOContract public payable returns (bool) {
if (state != State.Active) {
error('deposit: state != State.Active');
return false;
}
deposited[_investor] = deposited[_investor].add(msg.value);
tokensAcquired[_investor] = tokensAcquired[_investor].add(_tokenAmount);
return true;
}
/**
* @notice When ICO finalizes funds are transferred to founders' wallets
*/
function close() onlyICOContract public returns (bool) {
if (state != State.Active) {
error('close: state != State.Active');
return false;
}
state = State.Closed;
walletFounder1.transfer(address(this).balance.mul(33).div(100)); // Forwards 33% to 1st founder wallet
walletFounder2.transfer(address(this).balance.mul(50).div(100)); // Forwards 33% to 2nd founder wallet
walletFounder3.transfer(address(this).balance); // Forwards 34% to 3rd founder wallet
emit Closed(); // Event log
return true;
}
/**
* @notice When ICO finalizes owner toggles refunding
*/
function enableRefunds() onlyICOContract public returns (bool) {
if (state != State.Active) {
error('enableRefunds: state != State.Active');
return false;
}
state = State.Refunding;
emit RefundsEnabled(); // Event log
return true;
}
/**
* @notice ICO Smart Contract can call this function for the investor to refund
*/
function refund(address _investor) onlyICOContract public returns (bool) {
if (state != State.Refunding) {
error('refund: state != State.Refunding');
return false;
}
if (deposited[_investor] == 0) {
error('refund: no deposit to refund');
return false;
}
uint256 depositedValue = deposited[_investor];
deposited[_investor] = 0;
tokensAcquired[_investor] = 0; // tokens should have been returned previously to the ICO
_investor.transfer(depositedValue);
emit Refunded(_investor, depositedValue); // Event log
return true;
}
/**
* @notice To allow ICO contracts to check whether RefundVault is ready to refund investors
*/
function isRefunding() public constant returns (bool) {
return (state == State.Refunding);
}
/**
* @notice The owner must specify which ICO contract is allowed call for refunds
*/
function setMyICOContract(address _SCICO) public onlyOwner {
require(address(this).balance == 0);
addressSCICO = _SCICO;
}
// **** EVENTS
// Triggered when ICO contract closes the vault and forwards funds to the founders' wallets
event Closed();
// Triggered when ICO contract initiates refunding
event RefundsEnabled();
// Triggered when an investor claims (through ICO contract) and gets its funds
event Refunded(address indexed beneficiary, uint256 weiAmount);
}
contract Haltable is System {
bool public halted;
// **** MODIFIERS
modifier stopInEmergency {
if (halted) {
error('Haltable: stopInEmergency function called and contract is halted');
} else {
_;
}
}
modifier onlyInEmergency {
if (!halted) {
error('Haltable: onlyInEmergency function called and contract is not halted');
} {
_;
}
}
// **** FUNCTIONS
// called by the owner on emergency, triggers stopped state
function halt() external onlyOwner {
halted = true;
emit Halt(true, msg.sender, timestamp()); // Event log
}
// called by the owner on end of emergency, returns to normal state
function unhalt() external onlyOwner onlyInEmergency {
halted = false;
emit Halt(false, msg.sender, timestamp()); // Event log
}
// **** EVENTS
// @notice Triggered when owner halts contract
event Halt(bool _switch, address _halter, uint256 _timestamp);
}
contract ICO is HardcodedWallets, Haltable {
// **** DATA
// Linked Contracts
Tokens public SCTokens; // The token being sold
RefundVault public SCRefundVault; // The vault for softCap refund
Whitelist public SCWhitelist; // The whitelist of allowed wallets to buy tokens on ICO
Escrow public SCEscrow; // Escrow service
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
bool public isFinalized = false;
uint256 public weisPerBigToken; // how many weis a buyer pays to get a big token (10^18 tokens)
uint256 public weisPerEther;
uint256 public tokensPerEther; // amount of tokens with multiplier received on ICO when paying with 1 Ether, discounts included
uint256 public bigTokensPerEther; // amount of tokens w/omultiplier received on ICO when paying with 1 Ether, discounts included
uint256 public weisRaised; // amount of Weis raised
uint256 public etherHardCap; // Max amount of Ethers to raise
uint256 public tokensHardCap; // Max amount of Tokens for sale
uint256 public weisHardCap; // Max amount of Weis raised
uint256 public weisMinInvestment; // Min amount of Weis to perform a token sale
uint256 public etherSoftCap; // Min amount of Ethers for sale to ICO become successful
uint256 public tokensSoftCap; // Min amount of Tokens for sale to ICO become successful
uint256 public weisSoftCap; // Min amount of Weis raised to ICO become successful
uint256 public discount; // Applies to token price when investor buys tokens. It is a number between 0-100
uint256 discountedPricePercentage;
uint8 ICOStage;
// **** MODIFIERS
// **** FUNCTIONS
// fallback function can be used to buy tokens
function () payable public {
buyTokens();
}
/**
* @notice Token purchase function direclty through ICO Smart Contract. Beneficiary = msg.sender
*/
function buyTokens() public stopInEmergency payable returns (bool) {
if (msg.value == 0) {
error('buyTokens: ZeroPurchase');
return false;
}
uint256 tokenAmount = buyTokensLowLevel(msg.sender, msg.value);
// Send the investor's ethers to the vault
if (!SCRefundVault.deposit.value(msg.value)(msg.sender, tokenAmount)) {
revert('buyTokens: unable to transfer collected funds from ICO contract to Refund Vault'); // Revert needed to refund investor on error
// error('buyTokens: unable to transfer collected funds from ICO contract to Refund Vault');
// return false;
}
emit BuyTokens(msg.sender, msg.value, tokenAmount); // Event log
return true;
}
/**
* @notice Token purchase function through Oracle PayIn by MarketPay.io API
*/
/* // Deactivated to save ICO contract deployment gas cost
function buyTokensOraclePayIn(address _beneficiary, uint256 _weisAmount) public onlyCustodyFiat stopInEmergency returns (bool) {
uint256 tokenAmount = buyTokensLowLevel(_beneficiary, _weisAmount);
emit BuyTokensOraclePayIn(msg.sender, _beneficiary, _weisAmount, tokenAmount); // Event log
return true;
}*/
/**
* @notice Low level token purchase function, w/o ether transfer from investor
*/
function buyTokensLowLevel(address _beneficiary, uint256 _weisAmount) private stopInEmergency returns (uint256 tokenAmount) {
if (_beneficiary == 0x0) {
revert('buyTokensLowLevel: _beneficiary == 0x0'); // Revert needed to refund investor on error
// error('buyTokensLowLevel: _beneficiary == 0x0');
// return 0;
}
if (timestamp() < startTime || timestamp() > endTime) {
revert('buyTokensLowLevel: Not withinPeriod'); // Revert needed to refund investor on error
// error('buyTokensLowLevel: Not withinPeriod');
// return 0;
}
if (!SCWhitelist.isInvestor(_beneficiary)) {
revert('buyTokensLowLevel: Investor is not registered on the whitelist'); // Revert needed to refund investor on error
// error('buyTokensLowLevel: Investor is not registered on the whitelist');
// return 0;
}
if (isFinalized) {
revert('buyTokensLowLevel: ICO is already finalized'); // Revert needed to refund investor on error
// error('buyTokensLowLevel: ICO is already finalized');
// return 0;
}
// Verify whether enough ether has been sent to buy the min amount of investment
if (_weisAmount < weisMinInvestment) {
revert('buyTokensLowLevel: Minimal investment not reached. Not enough ethers to perform the minimal purchase'); // Revert needed to refund investor on error
// error('buyTokensLowLevel: Minimal investment not reached. Not enough ethers to perform the minimal purchase');
// return 0;
}
// Verify whether there are enough tokens to sell
if (weisRaised.add(_weisAmount) > weisHardCap) {
revert('buyTokensLowLevel: HardCap reached. Not enough tokens on ICO contract to perform this purchase'); // Revert needed to refund investor on error
// error('buyTokensLowLevel: HardCap reached. Not enough tokens on ICO contract to perform this purchase');
// return 0;
}
// Calculate token amount to be sold
tokenAmount = _weisAmount.mul(weisPerEther).div(weisPerBigToken);
// Applying discount
tokenAmount = tokenAmount.mul(100).div(discountedPricePercentage);
// Update state
weisRaised = weisRaised.add(_weisAmount);
// Send the tokens to the investor
if (!SCTokens.transfer(_beneficiary, tokenAmount)) {
revert('buyTokensLowLevel: unable to transfer tokens from ICO contract to beneficiary'); // Revert needed to refund investor on error
// error('buyTokensLowLevel: unable to transfer tokens from ICO contract to beneficiary');
// return 0;
}
emit BuyTokensLowLevel(msg.sender, _beneficiary, _weisAmount, tokenAmount); // Event log
return tokenAmount;
}
/**
* @return true if ICO event has ended
*/
/* // Deactivated to save ICO contract deployment gas cost
function hasEnded() public constant returns (bool) {
return timestamp() > endTime;
}*/
/**
* @notice Called by owner to alter the ICO deadline
*/
function updateEndTime(uint256 _endTime) onlyOwner public returns (bool) {
endTime = _endTime;
emit UpdateEndTime(_endTime); // Event log
}
/**
* @notice Must be called by owner before or after ICO ends, to check whether soft cap is reached and transfer collected funds
*/
function finalize(bool _forceRefund) onlyOwner public returns (bool) {
if (isFinalized) {
error('finalize: ICO is already finalized.');
return false;
}
if (weisRaised >= weisSoftCap && !_forceRefund) {
if (!SCRefundVault.close()) {
error('finalize: SCRefundVault.close() failed');
return false;
}
} else {
if (!SCRefundVault.enableRefunds()) {
error('finalize: SCRefundVault.enableRefunds() failed');
return false;
}
if(_forceRefund) {
emit ForceRefund(); // Event log
}
}
// Move remaining ICO tokens back to the Escrow
uint256 balanceAmount = SCTokens.balanceOf(this);
if (!SCTokens.transfer(address(SCEscrow), balanceAmount)) {
error('finalize: unable to return remaining ICO tokens');
return false;
}
// Adjust Escrow balance correctly
if(!SCEscrow.deposit(balanceAmount)) {
error('finalize: unable to return remaining ICO tokens');
return false;
}
isFinalized = true;
emit Finalized(); // Event log
return true;
}
/**
* @notice If ICO is unsuccessful, investors can claim refunds here
*/
function claimRefund() public stopInEmergency returns (bool) {
if (!isFinalized) {
error('claimRefund: ICO is not yet finalized.');
return false;
}
if (!SCRefundVault.isRefunding()) {
error('claimRefund: RefundVault state != State.Refunding');
return false;
}
// Before transfering the ETHs to the investor, get back the tokens bought on ICO
uint256 tokenAmount = SCRefundVault.getTokensAcquired(msg.sender);
emit GetBackTokensOnRefund(msg.sender, this, tokenAmount); // Event Log
if (!SCTokens.refundTokens(msg.sender, tokenAmount)) {
error('claimRefund: unable to transfer investor tokens to ICO contract before refunding');
return false;
}
if (!SCRefundVault.refund(msg.sender)) {
error('claimRefund: SCRefundVault.refund() failed');
return false;
}
return true;
}
function fundICO() public onlyOwner {
if (!SCEscrow.fundICO(tokensHardCap, ICOStage)) {
revert('ICO funding failed');
}
}
// **** EVENTS
// Triggered when an investor buys some tokens directly with Ethers
event BuyTokens(address indexed _purchaser, uint256 _value, uint256 _amount);
// Triggered when Owner says some investor has requested tokens on PayIn MarketPay.io API
event BuyTokensOraclePayIn(address indexed _purchaser, address indexed _beneficiary, uint256 _weisAmount, uint256 _tokenAmount);
// Triggered when an investor buys some tokens directly with Ethers or through payin Oracle
event BuyTokensLowLevel(address indexed _purchaser, address indexed _beneficiary, uint256 _value, uint256 _amount);
// Triggered when an SC owner request to end the ICO, transferring funds to founders wallet or ofeering them as a refund
event Finalized();
// Triggered when an SC owner request to end the ICO and allow transfer of funds to founders wallets as a refund
event ForceRefund();
// Triggered when RefundVault is created
//event AddressSCRefundVault(address _scAddress);
// Triggered when investor refund and their tokens got back to ICO contract
event GetBackTokensOnRefund(address _from, address _to, uint256 _amount);
// Triggered when Owner updates ICO deadlines
event UpdateEndTime(uint256 _endTime);
}
contract ICOPreSale is ICO {
/**
* @notice ICO constructor. Definition of ICO parameters and subcontracts autodeployment
*/
constructor(address _SCEscrow, address _SCTokens, address _SCWhitelist, address _SCRefundVault) public {
if (_SCTokens == 0x0) {
revert('Tokens Constructor: _SCTokens == 0x0');
}
if (_SCWhitelist == 0x0) {
revert('Tokens Constructor: _SCWhitelist == 0x0');
}
if (_SCRefundVault == 0x0) {
revert('Tokens Constructor: _SCRefundVault == 0x0');
}
SCTokens = Tokens(_SCTokens);
SCWhitelist = Whitelist(_SCWhitelist);
SCRefundVault = RefundVault(_SCRefundVault);
weisPerEther = 1 ether; // 10e^18 multiplier
// Deadline
startTime = timestamp();
endTime = timestamp().add(24 days); // from 8th June to 2th July 2018
// Token Price
bigTokensPerEther = 7500; // tokens (w/o multiplier) got for 1 ether
tokensPerEther = bigTokensPerEther.mul(weisPerEther); // tokens (with multiplier) got for 1 ether
discount = 45; // pre-sale 45%
discountedPricePercentage = 100;
discountedPricePercentage = discountedPricePercentage.sub(discount);
weisMinInvestment = weisPerEther.mul(1);
// 2018-05-10: alvaro.ariet@lacomunity.com Los Hardcap que indicas no son los últimos comentados. Los correctos serían:
// Pre-Sale: 8.470 ETH
// 1st Tier: 8.400 ETH
// 2nd Tier: 68.600 ETH
// HardCap
// etherHardCap = 8500; // As of 2018-05-09 => Hardcap pre sale: 8.500 ETH
// As of 2018-05-10 => Pre-Sale: 8.470 ETH
etherHardCap = 8067; // As of 2018-05-24 => Pre-Sale: 8067 ETH
tokensHardCap = tokensPerEther.mul(etherHardCap).mul(100).div(discountedPricePercentage);
weisPerBigToken = weisPerEther.div(bigTokensPerEther);
// weisHardCap = weisPerBigToken.mul(tokensHardCap).div(weisPerEther);
weisHardCap = weisPerEther.mul(etherHardCap);
// SoftCap
etherSoftCap = 750; // As of 2018-05-09 => Softcap pre sale: 750 ETH
weisSoftCap = weisPerEther.mul(etherSoftCap);
SCEscrow = Escrow(_SCEscrow);
ICOStage = 0;
}
}
contract Tokens is HardcodedWallets, ERC20, Haltable {
// **** DATA
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public _totalSupply;
// Public variables of the token, all used for display
string public name;
string public symbol;
uint8 public decimals;
string public standard = 'H0.1'; // HumanStandardToken is a specialisation of ERC20 defining these parameters
// Timelock
uint256 public timelockEndTime;
// Circular reference to ICO contract
address public addressSCICO;
// Circular reference to Escrow contract
address public addressSCEscrow;
// Reference to ComplianceService contract
address public addressSCComplianceService;
ComplianceService public SCComplianceService;
// **** MODIFIERS
// @notice To limit token transfers while timelocked
modifier notTimeLocked() {
if (now < timelockEndTime && msg.sender != addressSCICO && msg.sender != addressSCEscrow) {
error('notTimeLocked: Timelock still active. Function is yet unavailable.');
} else {
_;
}
}
// **** FUNCTIONS
/**
* @notice Constructor: set up token properties and owner token balance
*/
constructor(address _addressSCEscrow, address _addressSCComplianceService) public {
name = "TheRentalsToken";
symbol = "TRT";
decimals = 18; // 18 decimal places, the same as ETH
// initialSupply = 2000000000 ether; // 2018-04-21: ICO summary.docx: ...Dicho valor generaría un Total Supply de 2.000 millones de TRT.
_totalSupply = 1350000000 ether; // 2018-05-10: alvaro.ariet@lacomunity.com ...tenemos una emisión de 1.350 millones de Tokens
timelockEndTime = timestamp().add(45 days); // Default timelock
addressSCEscrow = _addressSCEscrow;
addressSCComplianceService = _addressSCComplianceService;
SCComplianceService = ComplianceService(addressSCComplianceService);
// Token distribution
balances[_addressSCEscrow] = _totalSupply;
emit Transfer(0x0, _addressSCEscrow, _totalSupply);
}
/**
* @notice Get the token total supply
*/
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
/**
* @notice Get the token balance of a wallet with address _owner
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
/**
* @notice Send _amount amount of tokens to address _to
*/
function transfer(address _to, uint256 _amount) public notTimeLocked stopInEmergency returns (bool success) {
if (balances[msg.sender] < _amount) {
error('transfer: the amount to transfer is higher than your token balance');
return false;
}
if(!SCComplianceService.validate(msg.sender, _to, _amount)) {
error('transfer: not allowed by the compliance service');
return false;
}
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(msg.sender, _to, _amount); // Event log
return true;
}
/**
* @notice Send _amount amount of tokens from address _from to address _to
* @notice The transferFrom method is used for a withdraw workflow, allowing contracts to send
* @notice tokens on your behalf, for example to "deposit" to a contract address and/or to charge
* @notice fees in sub-currencies; the command should fail unless the _from account has
* @notice deliberately authorized the sender of the message via some mechanism
*/
function transferFrom(address _from, address _to, uint256 _amount) public notTimeLocked stopInEmergency returns (bool success) {
if (balances[_from] < _amount) {
error('transferFrom: the amount to transfer is higher than the token balance of the source');
return false;
}
if (allowed[_from][msg.sender] < _amount) {
error('transferFrom: the amount to transfer is higher than the maximum token transfer allowed by the source');
return false;
}
if(!SCComplianceService.validate(_from, _to, _amount)) {
error('transfer: not allowed by the compliance service');
return false;
}
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); // Event log
return true;
}
/**
* @notice Allow _spender to withdraw from your account, multiple times, up to the _amount amount.
* @notice If this function is called again it overwrites the current allowance with _amount.
*/
function approve(address _spender, uint256 _amount) public returns (bool success) {
allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount); // Event log
return true;
}
/**
* @notice Returns the amount which _spender is still allowed to withdraw from _owner
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
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) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @notice This is out of ERC20 standard but it is necessary to build market escrow contracts of assets
* @notice Send _amount amount of tokens to from tx.origin to address _to
*/
function refundTokens(address _from, uint256 _amount) public notTimeLocked stopInEmergency returns (bool success) {
if (tx.origin != _from) {
error('refundTokens: tx.origin did not request the refund directly');
return false;
}
if (addressSCICO != msg.sender) {
error('refundTokens: caller is not the current ICO address');
return false;
}
if (balances[_from] < _amount) {
error('refundTokens: the amount to transfer is higher than your token balance');
return false;
}
if(!SCComplianceService.validate(_from, addressSCICO, _amount)) {
error('transfer: not allowed by the compliance service');
return false;
}
balances[_from] = balances[_from].sub(_amount);
balances[addressSCICO] = balances[addressSCICO].add(_amount);
emit Transfer(_from, addressSCICO, _amount); // Event log
return true;
}
/**
* @notice The owner can specify which ICO contract is allowed to transfer tokens while timelock is on
*/
function setMyICOContract(address _SCICO) public onlyOwner {
addressSCICO = _SCICO;
}
function setComplianceService(address _addressSCComplianceService) public onlyOwner {
addressSCComplianceService = _addressSCComplianceService;
SCComplianceService = ComplianceService(addressSCComplianceService);
}
/**
* @notice Called by owner to alter the token timelock
*/
function updateTimeLock(uint256 _timelockEndTime) onlyOwner public returns (bool) {
timelockEndTime = _timelockEndTime;
emit UpdateTimeLock(_timelockEndTime); // Event log
return true;
}
// **** EVENTS
// Triggered when tokens are transferred
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
// Triggered when someone approves a spender to move its tokens
event Approval(address indexed _owner, address indexed _spender, uint256 _amount);
// Triggered when Owner updates token timelock
event UpdateTimeLock(uint256 _timelockEndTime);
}
contract Whitelist is HardcodedWallets, System {
// **** DATA
mapping (address => bool) public walletsICO;
mapping (address => bool) public managers;
// Checks whether a given wallet is authorized to ICO investing
function isInvestor(address _wallet) public constant returns (bool) {
return (walletsICO[_wallet]);
}
/**
* @notice Registers an investor
*/
function addInvestor(address _wallet) external isManager returns (bool) {
// Checks whether this wallet has been previously added as an investor
if (walletsICO[_wallet]) {
error('addInvestor: this wallet has been previously granted as ICO investor');
return false;
}
walletsICO[_wallet] = true;
emit AddInvestor(_wallet, timestamp()); // Event log
return true;
}
modifier isManager(){
if (managers[msg.sender] || msg.sender == owner) {
_;
} else {
error("isManager: called by user that is not owner or manager");
}
}
// adds an address that will have the right to add investors
function addManager(address _managerAddr) external onlyOwner returns (bool) {
if(managers[_managerAddr]){
error("addManager: manager account already exists.");
return false;
}
managers[_managerAddr] = true;
emit AddManager(_managerAddr, timestamp());
}
// removes a manager address
function delManager(address _managerAddr) external onlyOwner returns (bool) {
if(!managers[_managerAddr]){
error("delManager: manager account not found.");
return false;
}
delete managers[_managerAddr];
emit DelManager(_managerAddr, timestamp());
}
// **** EVENTS
// Triggered when a wallet is granted to become an ICO investor
event AddInvestor(address indexed _wallet, uint256 _timestamp);
// Triggered when a manager is added
event AddManager(address indexed _managerAddr, uint256 _timestamp);
// Triggered when a manager is removed
event DelManager(address indexed _managerAddr, uint256 _timestamp);
}
|
This is out of ERC20 standard but it is necessary to build market escrow contracts of assets Send _amount amount of tokens to from tx.origin to address _to/
|
function refundTokens(address _from, uint256 _amount) public notTimeLocked stopInEmergency returns (bool success) {
if (tx.origin != _from) {
error('refundTokens: tx.origin did not request the refund directly');
return false;
}
if (addressSCICO != msg.sender) {
error('refundTokens: caller is not the current ICO address');
return false;
}
if (balances[_from] < _amount) {
error('refundTokens: the amount to transfer is higher than your token balance');
return false;
}
if(!SCComplianceService.validate(_from, addressSCICO, _amount)) {
error('transfer: not allowed by the compliance service');
return false;
}
balances[_from] = balances[_from].sub(_amount);
balances[addressSCICO] = balances[addressSCICO].add(_amount);
return true;
}
| 6,402,619
|
./partial_match/4/0xFC6eDF92D8168837551eD55ebbE093efD7CaB2bC/sources/MasterDAO.sol
|
ADD | NEW LP TOKEN POOL
|
function add(uint256 _allocPoint, IERC20 _rewardToken, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
rewardToken: _rewardToken,
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accGDAOPerShare: 0
}));
}
| 8,755,911
|
./partial_match/1/0xA62fcF90dCdA0f2E942749a121eF2F81c7f1C162/sources/AntexToken.sol
|
exclude liquidity wallet
|
function calculateBNBReward(address ofAddress) public view returns (uint256) {
uint256 totalBalanceSupply = uint256(_tTotal)
.sub(balanceOf(address(0)))
.sub(balanceOf(address(pancakePair)));
return Utils.calculateBNBReward(
balanceOf(address(ofAddress)),
address(this).balance,
totalBalanceSupply
);
}
| 4,043,892
|
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
// File: contracts/lib/AddressUtil.sol
// Copyright 2017 Loopring Technology Limited.
/// @title Utility Functions for addresses
/// @author Daniel Wang - <daniel@loopring.org>
/// @author Brecht Devos - <brecht@loopring.org>
library AddressUtil
{
using AddressUtil for *;
function isContract(
address addr
)
internal
view
returns (bool)
{
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(addr) }
return (codehash != 0x0 &&
codehash != 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470);
}
function toPayable(
address addr
)
internal
pure
returns (address payable)
{
return payable(addr);
}
// Works like address.send but with a customizable gas limit
// Make sure your code is safe for reentrancy when using this function!
function sendETH(
address to,
uint amount,
uint gasLimit
)
internal
returns (bool success)
{
if (amount == 0) {
return true;
}
address payable recipient = to.toPayable();
/* solium-disable-next-line */
(success, ) = recipient.call{value: amount, gas: gasLimit}("");
}
// Works like address.transfer but with a customizable gas limit
// Make sure your code is safe for reentrancy when using this function!
function sendETHAndVerify(
address to,
uint amount,
uint gasLimit
)
internal
returns (bool success)
{
success = to.sendETH(amount, gasLimit);
require(success, "TRANSFER_FAILURE");
}
// Works like call but is slightly more efficient when data
// needs to be copied from memory to do the call.
function fastCall(
address to,
uint gasLimit,
uint value,
bytes memory data
)
internal
returns (bool success, bytes memory returnData)
{
if (to != address(0)) {
assembly {
// Do the call
success := call(gasLimit, to, value, add(data, 32), mload(data), 0, 0)
// Copy the return data
let size := returndatasize()
returnData := mload(0x40)
mstore(returnData, size)
returndatacopy(add(returnData, 32), 0, size)
// Update free memory pointer
mstore(0x40, add(returnData, add(32, size)))
}
}
}
// Like fastCall, but throws when the call is unsuccessful.
function fastCallAndVerify(
address to,
uint gasLimit,
uint value,
bytes memory data
)
internal
returns (bytes memory returnData)
{
bool success;
(success, returnData) = fastCall(to, gasLimit, value, data);
if (!success) {
assembly {
revert(add(returnData, 32), mload(returnData))
}
}
}
}
// File: contracts/lib/MathUint.sol
// Copyright 2017 Loopring Technology Limited.
/// @title Utility Functions for uint
/// @author Daniel Wang - <daniel@loopring.org>
library MathUint
{
using MathUint for uint;
function mul(
uint a,
uint b
)
internal
pure
returns (uint c)
{
c = a * b;
require(a == 0 || c / a == b, "MUL_OVERFLOW");
}
function sub(
uint a,
uint b
)
internal
pure
returns (uint)
{
require(b <= a, "SUB_UNDERFLOW");
return a - b;
}
function add(
uint a,
uint b
)
internal
pure
returns (uint c)
{
c = a + b;
require(c >= a, "ADD_OVERFLOW");
}
function add64(
uint64 a,
uint64 b
)
internal
pure
returns (uint64 c)
{
c = a + b;
require(c >= a, "ADD_OVERFLOW");
}
}
// File: contracts/thirdparty/BytesUtil.sol
//Mainly taken from https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol
library BytesUtil {
function concat(
bytes memory _preBytes,
bytes memory _postBytes
)
internal
pure
returns (bytes memory)
{
bytes memory tempBytes;
assembly {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// Store the length of the first bytes array at the beginning of
// the memory for tempBytes.
let length := mload(_preBytes)
mstore(tempBytes, length)
// Maintain a memory counter for the current write location in the
// temp bytes array by adding the 32 bytes for the array length to
// the starting location.
let mc := add(tempBytes, 0x20)
// Stop copying when the memory counter reaches the length of the
// first bytes array.
let end := add(mc, length)
for {
// Initialize a copy counter to the start of the _preBytes data,
// 32 bytes into its memory.
let cc := add(_preBytes, 0x20)
} lt(mc, end) {
// Increase both counters by 32 bytes each iteration.
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// Write the _preBytes data into the tempBytes memory 32 bytes
// at a time.
mstore(mc, mload(cc))
}
// Add the length of _postBytes to the current length of tempBytes
// and store it as the new length in the first 32 bytes of the
// tempBytes memory.
length := mload(_postBytes)
mstore(tempBytes, add(length, mload(tempBytes)))
// Move the memory counter back from a multiple of 0x20 to the
// actual end of the _preBytes data.
mc := end
// Stop copying when the memory counter reaches the new combined
// length of the arrays.
end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
// Update the free-memory pointer by padding our last write location
// to 32 bytes: add 31 bytes to the end of tempBytes to move to the
// next 32 byte block, then round down to the nearest multiple of
// 32. If the sum of the length of the two arrays is zero then add
// one before rounding down to leave a blank 32 bytes (the length block with 0).
mstore(0x40, and(
add(add(end, iszero(add(length, mload(_preBytes)))), 31),
not(31) // Round down to the nearest 32 bytes.
))
}
return tempBytes;
}
function slice(
bytes memory _bytes,
uint _start,
uint _length
)
internal
pure
returns (bytes memory)
{
require(_bytes.length >= (_start + _length));
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) {
require(_bytes.length >= (_start + 20));
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint8(bytes memory _bytes, uint _start) internal pure returns (uint8) {
require(_bytes.length >= (_start + 1));
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function toUint16(bytes memory _bytes, uint _start) internal pure returns (uint16) {
require(_bytes.length >= (_start + 2));
uint16 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x2), _start))
}
return tempUint;
}
function toUint24(bytes memory _bytes, uint _start) internal pure returns (uint24) {
require(_bytes.length >= (_start + 3));
uint24 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x3), _start))
}
return tempUint;
}
function toUint32(bytes memory _bytes, uint _start) internal pure returns (uint32) {
require(_bytes.length >= (_start + 4));
uint32 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x4), _start))
}
return tempUint;
}
function toUint64(bytes memory _bytes, uint _start) internal pure returns (uint64) {
require(_bytes.length >= (_start + 8));
uint64 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x8), _start))
}
return tempUint;
}
function toUint96(bytes memory _bytes, uint _start) internal pure returns (uint96) {
require(_bytes.length >= (_start + 12));
uint96 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0xc), _start))
}
return tempUint;
}
function toUint128(bytes memory _bytes, uint _start) internal pure returns (uint128) {
require(_bytes.length >= (_start + 16));
uint128 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x10), _start))
}
return tempUint;
}
function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) {
require(_bytes.length >= (_start + 32));
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function toBytes4(bytes memory _bytes, uint _start) internal pure returns (bytes4) {
require(_bytes.length >= (_start + 4));
bytes4 tempBytes4;
assembly {
tempBytes4 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes4;
}
function toBytes20(bytes memory _bytes, uint _start) internal pure returns (bytes20) {
require(_bytes.length >= (_start + 20));
bytes20 tempBytes20;
assembly {
tempBytes20 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes20;
}
function toBytes32(bytes memory _bytes, uint _start) internal pure returns (bytes32) {
require(_bytes.length >= (_start + 32));
bytes32 tempBytes32;
assembly {
tempBytes32 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes32;
}
function toAddressUnsafe(bytes memory _bytes, uint _start) internal pure returns (address) {
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint8Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint8) {
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function toUint16Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint16) {
uint16 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x2), _start))
}
return tempUint;
}
function toUint24Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint24) {
uint24 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x3), _start))
}
return tempUint;
}
function toUint32Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint32) {
uint32 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x4), _start))
}
return tempUint;
}
function toUint64Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint64) {
uint64 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x8), _start))
}
return tempUint;
}
function toUint96Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint96) {
uint96 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0xc), _start))
}
return tempUint;
}
function toUint128Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint128) {
uint128 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x10), _start))
}
return tempUint;
}
function toUintUnsafe(bytes memory _bytes, uint _start) internal pure returns (uint256) {
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function toBytes4Unsafe(bytes memory _bytes, uint _start) internal pure returns (bytes4) {
bytes4 tempBytes4;
assembly {
tempBytes4 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes4;
}
function toBytes20Unsafe(bytes memory _bytes, uint _start) internal pure returns (bytes20) {
bytes20 tempBytes20;
assembly {
tempBytes20 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes20;
}
function toBytes32Unsafe(bytes memory _bytes, uint _start) internal pure returns (bytes32) {
bytes32 tempBytes32;
assembly {
tempBytes32 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes32;
}
function fastSHA256(
bytes memory data
)
internal
view
returns (bytes32)
{
bytes32[] memory result = new bytes32[](1);
bool success;
assembly {
let ptr := add(data, 32)
success := staticcall(sub(gas(), 2000), 2, ptr, mload(data), add(result, 32), 32)
}
require(success, "SHA256_FAILED");
return result[0];
}
}
// File: contracts/core/iface/IAgentRegistry.sol
// Copyright 2017 Loopring Technology Limited.
interface IAgent{}
abstract contract IAgentRegistry
{
/// @dev Returns whether an agent address is an agent of an account owner
/// @param owner The account owner.
/// @param agent The agent address
/// @return True if the agent address is an agent for the account owner, else false
function isAgent(
address owner,
address agent
)
external
virtual
view
returns (bool);
/// @dev Returns whether an agent address is an agent of all account owners
/// @param owners The account owners.
/// @param agent The agent address
/// @return True if the agent address is an agent for the account owner, else false
function isAgent(
address[] calldata owners,
address agent
)
external
virtual
view
returns (bool);
/// @dev Returns whether an agent address is a universal agent.
/// @param agent The agent address
/// @return True if the agent address is a universal agent, else false
function isUniversalAgent(address agent)
public
virtual
view
returns (bool);
}
// File: contracts/lib/Ownable.sol
// Copyright 2017 Loopring Technology Limited.
/// @title Ownable
/// @author Brecht Devos - <brecht@loopring.org>
/// @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.
constructor()
{
owner = msg.sender;
}
/// @dev Throws if called by any account other than the owner.
modifier onlyOwner()
{
require(msg.sender == owner, "UNAUTHORIZED");
_;
}
/// @dev Allows the current owner to transfer control of the contract to a
/// new owner.
/// @param newOwner The address to transfer ownership to.
function transferOwnership(
address newOwner
)
public
virtual
onlyOwner
{
require(newOwner != address(0), "ZERO_ADDRESS");
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
function renounceOwnership()
public
onlyOwner
{
emit OwnershipTransferred(owner, address(0));
owner = address(0);
}
}
// File: contracts/lib/Claimable.sol
// Copyright 2017 Loopring Technology Limited.
/// @title Claimable
/// @author Brecht Devos - <brecht@loopring.org>
/// @dev Extension for the Ownable contract, where the ownership needs
/// to be claimed. This allows the new owner to accept the transfer.
contract Claimable is Ownable
{
address public pendingOwner;
/// @dev Modifier throws if called by any account other than the pendingOwner.
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner, "UNAUTHORIZED");
_;
}
/// @dev Allows the current owner to set the pendingOwner address.
/// @param newOwner The address to transfer ownership to.
function transferOwnership(
address newOwner
)
public
override
onlyOwner
{
require(newOwner != address(0) && newOwner != owner, "INVALID_ADDRESS");
pendingOwner = newOwner;
}
/// @dev Allows the pendingOwner address to finalize the transfer.
function claimOwnership()
public
onlyPendingOwner
{
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
// File: contracts/core/iface/IBlockVerifier.sol
// Copyright 2017 Loopring Technology Limited.
/// @title IBlockVerifier
/// @author Brecht Devos - <brecht@loopring.org>
abstract contract IBlockVerifier is Claimable
{
// -- Events --
event CircuitRegistered(
uint8 indexed blockType,
uint16 blockSize,
uint8 blockVersion
);
event CircuitDisabled(
uint8 indexed blockType,
uint16 blockSize,
uint8 blockVersion
);
// -- Public functions --
/// @dev Sets the verifying key for the specified circuit.
/// Every block permutation needs its own circuit and thus its own set of
/// verification keys. Only a limited number of block sizes per block
/// type are supported.
/// @param blockType The type of the block
/// @param blockSize The number of requests handled in the block
/// @param blockVersion The block version (i.e. which circuit version needs to be used)
/// @param vk The verification key
function registerCircuit(
uint8 blockType,
uint16 blockSize,
uint8 blockVersion,
uint[18] calldata vk
)
external
virtual;
/// @dev Disables the use of the specified circuit.
/// @param blockType The type of the block
/// @param blockSize The number of requests handled in the block
/// @param blockVersion The block version (i.e. which circuit version needs to be used)
function disableCircuit(
uint8 blockType,
uint16 blockSize,
uint8 blockVersion
)
external
virtual;
/// @dev Verifies blocks with the given public data and proofs.
/// Verifying a block makes sure all requests handled in the block
/// are correctly handled by the operator.
/// @param blockType The type of block
/// @param blockSize The number of requests handled in the block
/// @param blockVersion The block version (i.e. which circuit version needs to be used)
/// @param publicInputs The hash of all the public data of the blocks
/// @param proofs The ZK proofs proving that the blocks are correct
/// @return True if the block is valid, false otherwise
function verifyProofs(
uint8 blockType,
uint16 blockSize,
uint8 blockVersion,
uint[] calldata publicInputs,
uint[] calldata proofs
)
external
virtual
view
returns (bool);
/// @dev Checks if a circuit with the specified parameters is registered.
/// @param blockType The type of the block
/// @param blockSize The number of requests handled in the block
/// @param blockVersion The block version (i.e. which circuit version needs to be used)
/// @return True if the circuit is registered, false otherwise
function isCircuitRegistered(
uint8 blockType,
uint16 blockSize,
uint8 blockVersion
)
external
virtual
view
returns (bool);
/// @dev Checks if a circuit can still be used to commit new blocks.
/// @param blockType The type of the block
/// @param blockSize The number of requests handled in the block
/// @param blockVersion The block version (i.e. which circuit version needs to be used)
/// @return True if the circuit is enabled, false otherwise
function isCircuitEnabled(
uint8 blockType,
uint16 blockSize,
uint8 blockVersion
)
external
virtual
view
returns (bool);
}
// File: contracts/core/iface/IDepositContract.sol
// Copyright 2017 Loopring Technology Limited.
/// @title IDepositContract.
/// @dev Contract storing and transferring funds for an exchange.
///
/// ERC1155 tokens can be supported by registering pseudo token addresses calculated
/// as `address(keccak256(real_token_address, token_params))`. Then the custom
/// deposit contract can look up the real token address and paramsters with the
/// pseudo token address before doing the transfers.
/// @author Brecht Devos - <brecht@loopring.org>
interface IDepositContract
{
/// @dev Returns if a token is suppoprted by this contract.
function isTokenSupported(address token)
external
view
returns (bool);
/// @dev Transfers tokens from a user to the exchange. This function will
/// be called when a user deposits funds to the exchange.
/// In a simple implementation the funds are simply stored inside the
/// deposit contract directly. More advanced implementations may store the funds
/// in some DeFi application to earn interest, so this function could directly
/// call the necessary functions to store the funds there.
///
/// This function needs to throw when an error occurred!
///
/// This function can only be called by the exchange.
///
/// @param from The address of the account that sends the tokens.
/// @param token The address of the token to transfer (`0x0` for ETH).
/// @param amount The amount of tokens to transfer.
/// @param extraData Opaque data that can be used by the contract to handle the deposit
/// @return amountReceived The amount to deposit to the user's account in the Merkle tree
function deposit(
address from,
address token,
uint96 amount,
bytes calldata extraData
)
external
payable
returns (uint96 amountReceived);
/// @dev Transfers tokens from the exchange to a user. This function will
/// be called when a withdrawal is done for a user on the exchange.
/// In the simplest implementation the funds are simply stored inside the
/// deposit contract directly so this simply transfers the requested tokens back
/// to the user. More advanced implementations may store the funds
/// in some DeFi application to earn interest so the function would
/// need to get those tokens back from the DeFi application first before they
/// can be transferred to the user.
///
/// This function needs to throw when an error occurred!
///
/// This function can only be called by the exchange.
///
/// @param from The address from which 'amount' tokens are transferred.
/// @param to The address to which 'amount' tokens are transferred.
/// @param token The address of the token to transfer (`0x0` for ETH).
/// @param amount The amount of tokens transferred.
/// @param extraData Opaque data that can be used by the contract to handle the withdrawal
function withdraw(
address from,
address to,
address token,
uint amount,
bytes calldata extraData
)
external
payable;
/// @dev Transfers tokens (ETH not supported) for a user using the allowance set
/// for the exchange. This way the approval can be used for all functionality (and
/// extended functionality) of the exchange.
/// Should NOT be used to deposit/withdraw user funds, `deposit`/`withdraw`
/// should be used for that as they will contain specialised logic for those operations.
/// This function can be called by the exchange to transfer onchain funds of users
/// necessary for Agent functionality.
///
/// This function needs to throw when an error occurred!
///
/// This function can only be called by the exchange.
///
/// @param from The address of the account that sends the tokens.
/// @param to The address to which 'amount' tokens are transferred.
/// @param token The address of the token to transfer (ETH is and cannot be suppported).
/// @param amount The amount of tokens transferred.
function transfer(
address from,
address to,
address token,
uint amount
)
external
payable;
/// @dev Checks if the given address is used for depositing ETH or not.
/// Is used while depositing to send the correct ETH amount to the deposit contract.
///
/// Note that 0x0 is always registered for deposting ETH when the exchange is created!
/// This function allows additional addresses to be used for depositing ETH, the deposit
/// contract can implement different behaviour based on the address value.
///
/// @param addr The address to check
/// @return True if the address is used for depositing ETH, else false.
function isETH(address addr)
external
view
returns (bool);
}
// File: contracts/core/iface/ILoopringV3.sol
// Copyright 2017 Loopring Technology Limited.
/// @title ILoopringV3
/// @author Brecht Devos - <brecht@loopring.org>
/// @author Daniel Wang - <daniel@loopring.org>
abstract contract ILoopringV3 is Claimable
{
// == Events ==
event ExchangeStakeDeposited(address exchangeAddr, uint amount);
event ExchangeStakeWithdrawn(address exchangeAddr, uint amount);
event ExchangeStakeBurned(address exchangeAddr, uint amount);
event SettingsUpdated(uint time);
// == Public Variables ==
mapping (address => uint) internal exchangeStake;
uint public totalStake;
address public blockVerifierAddress;
uint public forcedWithdrawalFee;
uint public tokenRegistrationFeeLRCBase;
uint public tokenRegistrationFeeLRCDelta;
uint8 public protocolTakerFeeBips;
uint8 public protocolMakerFeeBips;
address payable public protocolFeeVault;
// == Public Functions ==
/// @dev Returns the LRC token address
/// @return the LRC token address
function lrcAddress()
external
view
virtual
returns (address);
/// @dev Updates the global exchange settings.
/// This function can only be called by the owner of this contract.
///
/// Warning: these new values will be used by existing and
/// new Loopring exchanges.
function updateSettings(
address payable _protocolFeeVault, // address(0) not allowed
address _blockVerifierAddress, // address(0) not allowed
uint _forcedWithdrawalFee
)
external
virtual;
/// @dev Updates the global protocol fee settings.
/// This function can only be called by the owner of this contract.
///
/// Warning: these new values will be used by existing and
/// new Loopring exchanges.
function updateProtocolFeeSettings(
uint8 _protocolTakerFeeBips,
uint8 _protocolMakerFeeBips
)
external
virtual;
/// @dev Gets the amount of staked LRC for an exchange.
/// @param exchangeAddr The address of the exchange
/// @return stakedLRC The amount of LRC
function getExchangeStake(
address exchangeAddr
)
public
virtual
view
returns (uint stakedLRC);
/// @dev Burns a certain amount of staked LRC for a specific exchange.
/// This function is meant to be called only from exchange contracts.
/// @return burnedLRC The amount of LRC burned. If the amount is greater than
/// the staked amount, all staked LRC will be burned.
function burnExchangeStake(
uint amount
)
external
virtual
returns (uint burnedLRC);
/// @dev Stakes more LRC for an exchange.
/// @param exchangeAddr The address of the exchange
/// @param amountLRC The amount of LRC to stake
/// @return stakedLRC The total amount of LRC staked for the exchange
function depositExchangeStake(
address exchangeAddr,
uint amountLRC
)
external
virtual
returns (uint stakedLRC);
/// @dev Withdraws a certain amount of staked LRC for an exchange to the given address.
/// This function is meant to be called only from within exchange contracts.
/// @param recipient The address to receive LRC
/// @param requestedAmount The amount of LRC to withdraw
/// @return amountLRC The amount of LRC withdrawn
function withdrawExchangeStake(
address recipient,
uint requestedAmount
)
external
virtual
returns (uint amountLRC);
/// @dev Gets the protocol fee values for an exchange.
/// @return takerFeeBips The protocol taker fee
/// @return makerFeeBips The protocol maker fee
function getProtocolFeeValues(
)
public
virtual
view
returns (
uint8 takerFeeBips,
uint8 makerFeeBips
);
}
// File: contracts/core/iface/ExchangeData.sol
// Copyright 2017 Loopring Technology Limited.
/// @title ExchangeData
/// @dev All methods in this lib are internal, therefore, there is no need
/// to deploy this library independently.
/// @author Daniel Wang - <daniel@loopring.org>
/// @author Brecht Devos - <brecht@loopring.org>
library ExchangeData
{
// -- Enums --
enum TransactionType
{
NOOP,
DEPOSIT,
WITHDRAWAL,
TRANSFER,
SPOT_TRADE,
ACCOUNT_UPDATE,
AMM_UPDATE,
SIGNATURE_VERIFICATION
}
// -- Structs --
struct Token
{
address token;
}
struct ProtocolFeeData
{
uint32 syncedAt; // only valid before 2105 (85 years to go)
uint8 takerFeeBips;
uint8 makerFeeBips;
uint8 previousTakerFeeBips;
uint8 previousMakerFeeBips;
}
// General auxiliary data for each conditional transaction
struct AuxiliaryData
{
uint txIndex;
bool approved;
bytes data;
}
// This is the (virtual) block the owner needs to submit onchain to maintain the
// per-exchange (virtual) blockchain.
struct Block
{
uint8 blockType;
uint16 blockSize;
uint8 blockVersion;
bytes data;
uint256[8] proof;
// Whether we should store the @BlockInfo for this block on-chain.
bool storeBlockInfoOnchain;
// Block specific data that is only used to help process the block on-chain.
// It is not used as input for the circuits and it is not necessary for data-availability.
// This bytes array contains the abi encoded AuxiliaryData[] data.
bytes auxiliaryData;
// Arbitrary data, mainly for off-chain data-availability, i.e.,
// the multihash of the IPFS file that contains the block data.
bytes offchainData;
}
struct BlockInfo
{
// The time the block was submitted on-chain.
uint32 timestamp;
// The public data hash of the block (the 28 most significant bytes).
bytes28 blockDataHash;
}
// Represents an onchain deposit request.
struct Deposit
{
uint96 amount;
uint64 timestamp;
}
// A forced withdrawal request.
// If the actual owner of the account initiated the request (we don't know who the owner is
// at the time the request is being made) the full balance will be withdrawn.
struct ForcedWithdrawal
{
address owner;
uint64 timestamp;
}
struct Constants
{
uint SNARK_SCALAR_FIELD;
uint MAX_OPEN_FORCED_REQUESTS;
uint MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE;
uint TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS;
uint MAX_NUM_ACCOUNTS;
uint MAX_NUM_TOKENS;
uint MIN_AGE_PROTOCOL_FEES_UNTIL_UPDATED;
uint MIN_TIME_IN_SHUTDOWN;
uint TX_DATA_AVAILABILITY_SIZE;
uint MAX_AGE_DEPOSIT_UNTIL_WITHDRAWABLE_UPPERBOUND;
}
// This is the prime number that is used for the alt_bn128 elliptic curve, see EIP-196.
uint public constant SNARK_SCALAR_FIELD = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
uint public constant MAX_OPEN_FORCED_REQUESTS = 4096;
uint public constant MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE = 15 days;
uint public constant TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS = 7 days;
uint public constant MAX_NUM_ACCOUNTS = 2 ** 32;
uint public constant MAX_NUM_TOKENS = 2 ** 16;
uint public constant MIN_AGE_PROTOCOL_FEES_UNTIL_UPDATED = 7 days;
uint public constant MIN_TIME_IN_SHUTDOWN = 30 days;
// The amount of bytes each rollup transaction uses in the block data for data-availability.
// This is the maximum amount of bytes of all different transaction types.
uint32 public constant MAX_AGE_DEPOSIT_UNTIL_WITHDRAWABLE_UPPERBOUND = 15 days;
uint32 public constant ACCOUNTID_PROTOCOLFEE = 0;
uint public constant TX_DATA_AVAILABILITY_SIZE = 68;
uint public constant TX_DATA_AVAILABILITY_SIZE_PART_1 = 29;
uint public constant TX_DATA_AVAILABILITY_SIZE_PART_2 = 39;
struct AccountLeaf
{
uint32 accountID;
address owner;
uint pubKeyX;
uint pubKeyY;
uint32 nonce;
uint feeBipsAMM;
}
struct BalanceLeaf
{
uint16 tokenID;
uint96 balance;
uint96 weightAMM;
uint storageRoot;
}
struct MerkleProof
{
ExchangeData.AccountLeaf accountLeaf;
ExchangeData.BalanceLeaf balanceLeaf;
uint[48] accountMerkleProof;
uint[24] balanceMerkleProof;
}
struct BlockContext
{
bytes32 DOMAIN_SEPARATOR;
uint32 timestamp;
}
// Represents the entire exchange state except the owner of the exchange.
struct State
{
uint32 maxAgeDepositUntilWithdrawable;
bytes32 DOMAIN_SEPARATOR;
ILoopringV3 loopring;
IBlockVerifier blockVerifier;
IAgentRegistry agentRegistry;
IDepositContract depositContract;
// The merkle root of the offchain data stored in a Merkle tree. The Merkle tree
// stores balances for users using an account model.
bytes32 merkleRoot;
// List of all blocks
mapping(uint => BlockInfo) blocks;
uint numBlocks;
// List of all tokens
Token[] tokens;
// A map from a token to its tokenID + 1
mapping (address => uint16) tokenToTokenId;
// A map from an accountID to a tokenID to if the balance is withdrawn
mapping (uint32 => mapping (uint16 => bool)) withdrawnInWithdrawMode;
// A map from an account to a token to the amount withdrawable for that account.
// This is only used when the automatic distribution of the withdrawal failed.
mapping (address => mapping (uint16 => uint)) amountWithdrawable;
// A map from an account to a token to the forced withdrawal (always full balance)
mapping (uint32 => mapping (uint16 => ForcedWithdrawal)) pendingForcedWithdrawals;
// A map from an address to a token to a deposit
mapping (address => mapping (uint16 => Deposit)) pendingDeposits;
// A map from an account owner to an approved transaction hash to if the transaction is approved or not
mapping (address => mapping (bytes32 => bool)) approvedTx;
// A map from an account owner to a destination address to a tokenID to an amount to a storageID to a new recipient address
mapping (address => mapping (address => mapping (uint16 => mapping (uint => mapping (uint32 => address))))) withdrawalRecipient;
// Counter to keep track of how many of forced requests are open so we can limit the work that needs to be done by the owner
uint32 numPendingForcedTransactions;
// Cached data for the protocol fee
ProtocolFeeData protocolFeeData;
// Time when the exchange was shutdown
uint shutdownModeStartTime;
// Time when the exchange has entered withdrawal mode
uint withdrawalModeStartTime;
// Last time the protocol fee was withdrawn for a specific token
mapping (address => uint) protocolFeeLastWithdrawnTime;
}
}
// File: contracts/core/impl/libtransactions/BlockReader.sol
// Copyright 2017 Loopring Technology Limited.
/// @title BlockReader
/// @author Brecht Devos - <brecht@loopring.org>
/// @dev Utility library to read block data.
library BlockReader {
using BlockReader for ExchangeData.Block;
using BytesUtil for bytes;
uint public constant OFFSET_TO_TRANSACTIONS = 20 + 32 + 32 + 4 + 1 + 1 + 4 + 4;
struct BlockHeader
{
address exchange;
bytes32 merkleRootBefore;
bytes32 merkleRootAfter;
uint32 timestamp;
uint8 protocolTakerFeeBips;
uint8 protocolMakerFeeBips;
uint32 numConditionalTransactions;
uint32 operatorAccountID;
}
function readHeader(
bytes memory _blockData
)
internal
pure
returns (BlockHeader memory header)
{
uint offset = 0;
header.exchange = _blockData.toAddress(offset);
offset += 20;
header.merkleRootBefore = _blockData.toBytes32(offset);
offset += 32;
header.merkleRootAfter = _blockData.toBytes32(offset);
offset += 32;
header.timestamp = _blockData.toUint32(offset);
offset += 4;
header.protocolTakerFeeBips = _blockData.toUint8(offset);
offset += 1;
header.protocolMakerFeeBips = _blockData.toUint8(offset);
offset += 1;
header.numConditionalTransactions = _blockData.toUint32(offset);
offset += 4;
header.operatorAccountID = _blockData.toUint32(offset);
offset += 4;
assert(offset == OFFSET_TO_TRANSACTIONS);
}
function readTransactionData(
bytes memory data,
uint txIdx,
uint blockSize,
bytes memory txData
)
internal
pure
{
require(txIdx < blockSize, "INVALID_TX_IDX");
// The transaction was transformed to make it easier to compress.
// Transform it back here.
// Part 1
uint txDataOffset = OFFSET_TO_TRANSACTIONS +
txIdx * ExchangeData.TX_DATA_AVAILABILITY_SIZE_PART_1;
assembly {
mstore(add(txData, 32), mload(add(data, add(txDataOffset, 32))))
}
// Part 2
txDataOffset = OFFSET_TO_TRANSACTIONS +
blockSize * ExchangeData.TX_DATA_AVAILABILITY_SIZE_PART_1 +
txIdx * ExchangeData.TX_DATA_AVAILABILITY_SIZE_PART_2;
assembly {
mstore(add(txData, 61 /*32 + 29*/), mload(add(data, add(txDataOffset, 32))))
mstore(add(txData, 68 ), mload(add(data, add(txDataOffset, 39))))
}
}
}
// File: contracts/lib/EIP712.sol
// Copyright 2017 Loopring Technology Limited.
library EIP712
{
struct Domain {
string name;
string version;
address verifyingContract;
}
bytes32 constant internal EIP712_DOMAIN_TYPEHASH = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
string constant internal EIP191_HEADER = "\x19\x01";
function hash(Domain memory domain)
internal
pure
returns (bytes32)
{
uint _chainid;
assembly { _chainid := chainid() }
return keccak256(
abi.encode(
EIP712_DOMAIN_TYPEHASH,
keccak256(bytes(domain.name)),
keccak256(bytes(domain.version)),
_chainid,
domain.verifyingContract
)
);
}
function hashPacked(
bytes32 domainHash,
bytes32 dataHash
)
internal
pure
returns (bytes32)
{
return keccak256(
abi.encodePacked(
EIP191_HEADER,
domainHash,
dataHash
)
);
}
}
// File: contracts/thirdparty/SafeCast.sol
// Taken from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/SafeCast.sol
/**
* @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 uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value < 2**96, "SafeCast: value doesn\'t fit in 96 bits");
return uint96(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 uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
require(value < 2**40, "SafeCast: value doesn\'t fit in 40 bits");
return uint40(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);
}
}
// File: contracts/lib/FloatUtil.sol
// Copyright 2017 Loopring Technology Limited.
/// @title Utility Functions for floats
/// @author Brecht Devos - <brecht@loopring.org>
library FloatUtil
{
using MathUint for uint;
using SafeCast for uint;
// Decodes a decimal float value that is encoded like `exponent | mantissa`.
// Both exponent and mantissa are in base 10.
// Decoding to an integer is as simple as `mantissa * (10 ** exponent)`
// Will throw when the decoded value overflows an uint96
/// @param f The float value with 5 bits for the exponent
/// @param numBits The total number of bits (numBitsMantissa := numBits - numBitsExponent)
/// @return value The decoded integer value.
function decodeFloat(
uint f,
uint numBits
)
internal
pure
returns (uint96 value)
{
if (f == 0) {
return 0;
}
uint numBitsMantissa = numBits.sub(5);
uint exponent = f >> numBitsMantissa;
// log2(10**77) = 255.79 < 256
require(exponent <= 77, "EXPONENT_TOO_LARGE");
uint mantissa = f & ((1 << numBitsMantissa) - 1);
value = mantissa.mul(10 ** exponent).toUint96();
}
// Decodes a decimal float value that is encoded like `exponent | mantissa`.
// Both exponent and mantissa are in base 10.
// Decoding to an integer is as simple as `mantissa * (10 ** exponent)`
// Will throw when the decoded value overflows an uint96
/// @param f The float value with 5 bits exponent, 11 bits mantissa
/// @return value The decoded integer value.
function decodeFloat16(
uint16 f
)
internal
pure
returns (uint96)
{
uint value = ((uint(f) & 2047) * (10 ** (uint(f) >> 11)));
require(value < 2**96, "SafeCast: value doesn\'t fit in 96 bits");
return uint96(value);
}
// Decodes a decimal float value that is encoded like `exponent | mantissa`.
// Both exponent and mantissa are in base 10.
// Decoding to an integer is as simple as `mantissa * (10 ** exponent)`
// Will throw when the decoded value overflows an uint96
/// @param f The float value with 5 bits exponent, 19 bits mantissa
/// @return value The decoded integer value.
function decodeFloat24(
uint24 f
)
internal
pure
returns (uint96)
{
uint value = ((uint(f) & 524287) * (10 ** (uint(f) >> 19)));
require(value < 2**96, "SafeCast: value doesn\'t fit in 96 bits");
return uint96(value);
}
}
// File: contracts/lib/ERC1271.sol
// Copyright 2017 Loopring Technology Limited.
abstract contract ERC1271 {
// bytes4(keccak256("isValidSignature(bytes32,bytes)")
bytes4 constant internal ERC1271_MAGICVALUE = 0x1626ba7e;
function isValidSignature(
bytes32 _hash,
bytes memory _signature)
public
view
virtual
returns (bytes4 magicValueB32);
}
// File: contracts/lib/SignatureUtil.sol
// Copyright 2017 Loopring Technology Limited.
/// @title SignatureUtil
/// @author Daniel Wang - <daniel@loopring.org>
/// @dev This method supports multihash standard. Each signature's last byte indicates
/// the signature's type.
library SignatureUtil
{
using BytesUtil for bytes;
using MathUint for uint;
using AddressUtil for address;
enum SignatureType {
ILLEGAL,
INVALID,
EIP_712,
ETH_SIGN,
WALLET // deprecated
}
bytes4 constant internal ERC1271_MAGICVALUE = 0x1626ba7e;
function verifySignatures(
bytes32 signHash,
address[] memory signers,
bytes[] memory signatures
)
internal
view
returns (bool)
{
require(signers.length == signatures.length, "BAD_SIGNATURE_DATA");
address lastSigner;
for (uint i = 0; i < signers.length; i++) {
require(signers[i] > lastSigner, "INVALID_SIGNERS_ORDER");
lastSigner = signers[i];
if (!verifySignature(signHash, signers[i], signatures[i])) {
return false;
}
}
return true;
}
function verifySignature(
bytes32 signHash,
address signer,
bytes memory signature
)
internal
view
returns (bool)
{
if (signer == address(0)) {
return false;
}
return signer.isContract()?
verifyERC1271Signature(signHash, signer, signature):
verifyEOASignature(signHash, signer, signature);
}
function recoverECDSASigner(
bytes32 signHash,
bytes memory signature
)
internal
pure
returns (address)
{
if (signature.length != 65) {
return address(0);
}
bytes32 r;
bytes32 s;
uint8 v;
// we jump 32 (0x20) as the first slot of bytes contains the length
// we jump 65 (0x41) per signature
// for v we load 32 bytes ending with v (the first 31 come from s) then apply a mask
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := and(mload(add(signature, 0x41)), 0xff)
}
// See https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/cryptography/ECDSA.sol
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return address(0);
}
if (v == 27 || v == 28) {
return ecrecover(signHash, v, r, s);
} else {
return address(0);
}
}
function verifyEOASignature(
bytes32 signHash,
address signer,
bytes memory signature
)
private
pure
returns (bool success)
{
if (signer == address(0)) {
return false;
}
uint signatureTypeOffset = signature.length.sub(1);
SignatureType signatureType = SignatureType(signature.toUint8(signatureTypeOffset));
// Strip off the last byte of the signature by updating the length
assembly {
mstore(signature, signatureTypeOffset)
}
if (signatureType == SignatureType.EIP_712) {
success = (signer == recoverECDSASigner(signHash, signature));
} else if (signatureType == SignatureType.ETH_SIGN) {
bytes32 hash = keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", signHash)
);
success = (signer == recoverECDSASigner(hash, signature));
} else {
success = false;
}
// Restore the signature length
assembly {
mstore(signature, add(signatureTypeOffset, 1))
}
return success;
}
function verifyERC1271Signature(
bytes32 signHash,
address signer,
bytes memory signature
)
private
view
returns (bool)
{
bytes memory callData = abi.encodeWithSelector(
ERC1271.isValidSignature.selector,
signHash,
signature
);
(bool success, bytes memory result) = signer.staticcall(callData);
return (
success &&
result.length == 32 &&
result.toBytes4(0) == ERC1271_MAGICVALUE
);
}
}
// File: contracts/core/impl/libexchange/ExchangeSignatures.sol
// Copyright 2017 Loopring Technology Limited.
/// @title ExchangeSignatures.
/// @dev All methods in this lib are internal, therefore, there is no need
/// to deploy this library independently.
/// @author Brecht Devos - <brecht@loopring.org>
/// @author Daniel Wang - <daniel@loopring.org>
library ExchangeSignatures
{
using SignatureUtil for bytes32;
function requireAuthorizedTx(
ExchangeData.State storage S,
address signer,
bytes memory signature,
bytes32 txHash
)
internal // inline call
{
require(signer != address(0), "INVALID_SIGNER");
// Verify the signature if one is provided, otherwise fall back to an approved tx
if (signature.length > 0) {
require(txHash.verifySignature(signer, signature), "INVALID_SIGNATURE");
} else {
require(S.approvedTx[signer][txHash], "TX_NOT_APPROVED");
delete S.approvedTx[signer][txHash];
}
}
}
// File: contracts/core/impl/libtransactions/AccountUpdateTransaction.sol
// Copyright 2017 Loopring Technology Limited.
/// @title AccountUpdateTransaction
/// @author Brecht Devos - <brecht@loopring.org>
library AccountUpdateTransaction
{
using BytesUtil for bytes;
using FloatUtil for uint16;
using ExchangeSignatures for ExchangeData.State;
bytes32 constant public ACCOUNTUPDATE_TYPEHASH = keccak256(
"AccountUpdate(address owner,uint32 accountID,uint16 feeTokenID,uint96 maxFee,uint256 publicKey,uint32 validUntil,uint32 nonce)"
);
struct AccountUpdate
{
address owner;
uint32 accountID;
uint16 feeTokenID;
uint96 maxFee;
uint96 fee;
uint publicKey;
uint32 validUntil;
uint32 nonce;
}
// Auxiliary data for each account update
struct AccountUpdateAuxiliaryData
{
bytes signature;
uint96 maxFee;
uint32 validUntil;
}
function process(
ExchangeData.State storage S,
ExchangeData.BlockContext memory ctx,
bytes memory data,
uint offset,
bytes memory auxiliaryData
)
internal
{
// Read the account update
AccountUpdate memory accountUpdate;
readTx(data, offset, accountUpdate);
AccountUpdateAuxiliaryData memory auxData = abi.decode(auxiliaryData, (AccountUpdateAuxiliaryData));
// Fill in withdrawal data missing from DA
accountUpdate.validUntil = auxData.validUntil;
accountUpdate.maxFee = auxData.maxFee == 0 ? accountUpdate.fee : auxData.maxFee;
// Validate
require(ctx.timestamp < accountUpdate.validUntil, "ACCOUNT_UPDATE_EXPIRED");
require(accountUpdate.fee <= accountUpdate.maxFee, "ACCOUNT_UPDATE_FEE_TOO_HIGH");
// Calculate the tx hash
bytes32 txHash = hashTx(ctx.DOMAIN_SEPARATOR, accountUpdate);
// Check onchain authorization
S.requireAuthorizedTx(accountUpdate.owner, auxData.signature, txHash);
}
function readTx(
bytes memory data,
uint offset,
AccountUpdate memory accountUpdate
)
internal
pure
{
uint _offset = offset;
require(data.toUint8Unsafe(_offset) == uint8(ExchangeData.TransactionType.ACCOUNT_UPDATE), "INVALID_TX_TYPE");
_offset += 1;
// Check that this is a conditional offset
require(data.toUint8Unsafe(_offset) == 1, "INVALID_AUXILIARYDATA_DATA");
_offset += 1;
// Extract the data from the tx data
// We don't use abi.decode for this because of the large amount of zero-padding
// bytes the circuit would also have to hash.
accountUpdate.owner = data.toAddressUnsafe(_offset);
_offset += 20;
accountUpdate.accountID = data.toUint32Unsafe(_offset);
_offset += 4;
accountUpdate.feeTokenID = data.toUint16Unsafe(_offset);
_offset += 2;
accountUpdate.fee = data.toUint16Unsafe(_offset).decodeFloat16();
_offset += 2;
accountUpdate.publicKey = data.toUintUnsafe(_offset);
_offset += 32;
accountUpdate.nonce = data.toUint32Unsafe(_offset);
_offset += 4;
}
function hashTx(
bytes32 DOMAIN_SEPARATOR,
AccountUpdate memory accountUpdate
)
internal
pure
returns (bytes32)
{
return EIP712.hashPacked(
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
ACCOUNTUPDATE_TYPEHASH,
accountUpdate.owner,
accountUpdate.accountID,
accountUpdate.feeTokenID,
accountUpdate.maxFee,
accountUpdate.publicKey,
accountUpdate.validUntil,
accountUpdate.nonce
)
)
);
}
}
// File: contracts/core/impl/libtransactions/AmmUpdateTransaction.sol
// Copyright 2017 Loopring Technology Limited.
/// @title AmmUpdateTransaction
/// @author Brecht Devos - <brecht@loopring.org>
library AmmUpdateTransaction
{
using BytesUtil for bytes;
using MathUint for uint;
using ExchangeSignatures for ExchangeData.State;
bytes32 constant public AMMUPDATE_TYPEHASH = keccak256(
"AmmUpdate(address owner,uint32 accountID,uint16 tokenID,uint8 feeBips,uint96 tokenWeight,uint32 validUntil,uint32 nonce)"
);
struct AmmUpdate
{
address owner;
uint32 accountID;
uint16 tokenID;
uint8 feeBips;
uint96 tokenWeight;
uint32 validUntil;
uint32 nonce;
uint96 balance;
}
// Auxiliary data for each AMM update
struct AmmUpdateAuxiliaryData
{
bytes signature;
uint32 validUntil;
}
function process(
ExchangeData.State storage S,
ExchangeData.BlockContext memory ctx,
bytes memory data,
uint offset,
bytes memory auxiliaryData
)
internal
{
// Read in the AMM update
AmmUpdate memory update;
readTx(data, offset, update);
AmmUpdateAuxiliaryData memory auxData = abi.decode(auxiliaryData, (AmmUpdateAuxiliaryData));
// Check validUntil
require(ctx.timestamp < auxData.validUntil, "AMM_UPDATE_EXPIRED");
update.validUntil = auxData.validUntil;
// Calculate the tx hash
bytes32 txHash = hashTx(ctx.DOMAIN_SEPARATOR, update);
// Check the on-chain authorization
S.requireAuthorizedTx(update.owner, auxData.signature, txHash);
}
function readTx(
bytes memory data,
uint offset,
AmmUpdate memory update
)
internal
pure
{
uint _offset = offset;
require(data.toUint8Unsafe(_offset) == uint8(ExchangeData.TransactionType.AMM_UPDATE), "INVALID_TX_TYPE");
_offset += 1;
// We don't use abi.decode for this because of the large amount of zero-padding
// bytes the circuit would also have to hash.
update.owner = data.toAddressUnsafe(_offset);
_offset += 20;
update.accountID = data.toUint32Unsafe(_offset);
_offset += 4;
update.tokenID = data.toUint16Unsafe(_offset);
_offset += 2;
update.feeBips = data.toUint8Unsafe(_offset);
_offset += 1;
update.tokenWeight = data.toUint96Unsafe(_offset);
_offset += 12;
update.nonce = data.toUint32Unsafe(_offset);
_offset += 4;
update.balance = data.toUint96Unsafe(_offset);
_offset += 12;
}
function hashTx(
bytes32 DOMAIN_SEPARATOR,
AmmUpdate memory update
)
internal
pure
returns (bytes32)
{
return EIP712.hashPacked(
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
AMMUPDATE_TYPEHASH,
update.owner,
update.accountID,
update.tokenID,
update.feeBips,
update.tokenWeight,
update.validUntil,
update.nonce
)
)
);
}
}
// File: contracts/lib/MathUint96.sol
// Copyright 2017 Loopring Technology Limited.
/// @title Utility Functions for uint
/// @author Daniel Wang - <daniel@loopring.org>
library MathUint96
{
function add(
uint96 a,
uint96 b
)
internal
pure
returns (uint96 c)
{
c = a + b;
require(c >= a, "ADD_OVERFLOW");
}
function sub(
uint96 a,
uint96 b
)
internal
pure
returns (uint96 c)
{
require(b <= a, "SUB_UNDERFLOW");
return a - b;
}
}
// File: contracts/core/impl/libtransactions/DepositTransaction.sol
// Copyright 2017 Loopring Technology Limited.
/// @title DepositTransaction
/// @author Brecht Devos - <brecht@loopring.org>
library DepositTransaction
{
using BytesUtil for bytes;
using MathUint96 for uint96;
struct Deposit
{
address to;
uint32 toAccountID;
uint16 tokenID;
uint96 amount;
}
function process(
ExchangeData.State storage S,
ExchangeData.BlockContext memory /*ctx*/,
bytes memory data,
uint offset,
bytes memory /*auxiliaryData*/
)
internal
{
// Read in the deposit
Deposit memory deposit;
readTx(data, offset, deposit);
if (deposit.amount == 0) {
return;
}
// Process the deposit
ExchangeData.Deposit memory pendingDeposit = S.pendingDeposits[deposit.to][deposit.tokenID];
// Make sure the deposit was actually done
require(pendingDeposit.timestamp > 0, "DEPOSIT_DOESNT_EXIST");
// Processing partial amounts of the deposited amount is allowed.
// This is done to ensure the user can do multiple deposits after each other
// without invalidating work done by the exchange owner for previous deposit amounts.
require(pendingDeposit.amount >= deposit.amount, "INVALID_AMOUNT");
pendingDeposit.amount = pendingDeposit.amount.sub(deposit.amount);
// If the deposit was fully consumed, reset it so the storage is freed up
// and the owner receives a gas refund.
if (pendingDeposit.amount == 0) {
delete S.pendingDeposits[deposit.to][deposit.tokenID];
} else {
S.pendingDeposits[deposit.to][deposit.tokenID] = pendingDeposit;
}
}
function readTx(
bytes memory data,
uint offset,
Deposit memory deposit
)
internal
pure
{
uint _offset = offset;
require(data.toUint8Unsafe(_offset) == uint8(ExchangeData.TransactionType.DEPOSIT), "INVALID_TX_TYPE");
_offset += 1;
// We don't use abi.decode for this because of the large amount of zero-padding
// bytes the circuit would also have to hash.
deposit.to = data.toAddressUnsafe(_offset);
_offset += 20;
deposit.toAccountID = data.toUint32Unsafe(_offset);
_offset += 4;
deposit.tokenID = data.toUint16Unsafe(_offset);
_offset += 2;
deposit.amount = data.toUint96Unsafe(_offset);
_offset += 12;
}
}
// File: contracts/core/impl/libtransactions/TransferTransaction.sol
// Copyright 2017 Loopring Technology Limited.
/// @title TransferTransaction
/// @author Brecht Devos - <brecht@loopring.org>
library TransferTransaction
{
using BytesUtil for bytes;
using FloatUtil for uint24;
using FloatUtil for uint16;
using MathUint for uint;
using ExchangeSignatures for ExchangeData.State;
bytes32 constant public TRANSFER_TYPEHASH = keccak256(
"Transfer(address from,address to,uint16 tokenID,uint96 amount,uint16 feeTokenID,uint96 maxFee,uint32 validUntil,uint32 storageID)"
);
struct Transfer
{
uint32 fromAccountID;
uint32 toAccountID;
address from;
address to;
uint16 tokenID;
uint96 amount;
uint16 feeTokenID;
uint96 maxFee;
uint96 fee;
uint32 validUntil;
uint32 storageID;
}
// Auxiliary data for each transfer
struct TransferAuxiliaryData
{
bytes signature;
uint96 maxFee;
uint32 validUntil;
}
function process(
ExchangeData.State storage S,
ExchangeData.BlockContext memory ctx,
bytes memory data,
uint offset,
bytes memory auxiliaryData
)
internal
{
// Read the transfer
Transfer memory transfer;
readTx(data, offset, transfer);
TransferAuxiliaryData memory auxData = abi.decode(auxiliaryData, (TransferAuxiliaryData));
// Fill in withdrawal data missing from DA
transfer.validUntil = auxData.validUntil;
transfer.maxFee = auxData.maxFee == 0 ? transfer.fee : auxData.maxFee;
// Validate
require(ctx.timestamp < transfer.validUntil, "TRANSFER_EXPIRED");
require(transfer.fee <= transfer.maxFee, "TRANSFER_FEE_TOO_HIGH");
// Calculate the tx hash
bytes32 txHash = hashTx(ctx.DOMAIN_SEPARATOR, transfer);
// Check the on-chain authorization
S.requireAuthorizedTx(transfer.from, auxData.signature, txHash);
}
function readTx(
bytes memory data,
uint offset,
Transfer memory transfer
)
internal
pure
{
uint _offset = offset;
require(data.toUint8Unsafe(_offset) == uint8(ExchangeData.TransactionType.TRANSFER), "INVALID_TX_TYPE");
_offset += 1;
// Check that this is a conditional transfer
require(data.toUint8Unsafe(_offset) == 1, "INVALID_AUXILIARYDATA_DATA");
_offset += 1;
// Extract the transfer data
// We don't use abi.decode for this because of the large amount of zero-padding
// bytes the circuit would also have to hash.
transfer.fromAccountID = data.toUint32Unsafe(_offset);
_offset += 4;
transfer.toAccountID = data.toUint32Unsafe(_offset);
_offset += 4;
transfer.tokenID = data.toUint16Unsafe(_offset);
_offset += 2;
transfer.amount = data.toUint24Unsafe(_offset).decodeFloat24();
_offset += 3;
transfer.feeTokenID = data.toUint16Unsafe(_offset);
_offset += 2;
transfer.fee = data.toUint16Unsafe(_offset).decodeFloat16();
_offset += 2;
transfer.storageID = data.toUint32Unsafe(_offset);
_offset += 4;
transfer.to = data.toAddressUnsafe(_offset);
_offset += 20;
transfer.from = data.toAddressUnsafe(_offset);
_offset += 20;
}
function hashTx(
bytes32 DOMAIN_SEPARATOR,
Transfer memory transfer
)
internal
pure
returns (bytes32)
{
return EIP712.hashPacked(
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
TRANSFER_TYPEHASH,
transfer.from,
transfer.to,
transfer.tokenID,
transfer.amount,
transfer.feeTokenID,
transfer.maxFee,
transfer.validUntil,
transfer.storageID
)
)
);
}
}
// File: contracts/core/impl/libexchange/ExchangeMode.sol
// Copyright 2017 Loopring Technology Limited.
/// @title ExchangeMode.
/// @dev All methods in this lib are internal, therefore, there is no need
/// to deploy this library independently.
/// @author Brecht Devos - <brecht@loopring.org>
/// @author Daniel Wang - <daniel@loopring.org>
library ExchangeMode
{
using MathUint for uint;
function isInWithdrawalMode(
ExchangeData.State storage S
)
internal // inline call
view
returns (bool result)
{
result = S.withdrawalModeStartTime > 0;
}
function isShutdown(
ExchangeData.State storage S
)
internal // inline call
view
returns (bool)
{
return S.shutdownModeStartTime > 0;
}
function getNumAvailableForcedSlots(
ExchangeData.State storage S
)
internal
view
returns (uint)
{
return ExchangeData.MAX_OPEN_FORCED_REQUESTS - S.numPendingForcedTransactions;
}
}
// File: contracts/lib/Poseidon.sol
// Copyright 2017 Loopring Technology Limited.
/// @title Poseidon hash function
/// See: https://eprint.iacr.org/2019/458.pdf
/// Code auto-generated by generate_poseidon_EVM_code.py
/// @author Brecht Devos - <brecht@loopring.org>
library Poseidon
{
//
// hash_t5f6p52
//
struct HashInputs5
{
uint t0;
uint t1;
uint t2;
uint t3;
uint t4;
}
function hash_t5f6p52_internal(
uint t0,
uint t1,
uint t2,
uint t3,
uint t4,
uint q
)
internal
pure
returns (uint)
{
assembly {
function mix(_t0, _t1, _t2, _t3, _t4, _q) -> nt0, nt1, nt2, nt3, nt4 {
nt0 := mulmod(_t0, 4977258759536702998522229302103997878600602264560359702680165243908162277980, _q)
nt0 := addmod(nt0, mulmod(_t1, 19167410339349846567561662441069598364702008768579734801591448511131028229281, _q), _q)
nt0 := addmod(nt0, mulmod(_t2, 14183033936038168803360723133013092560869148726790180682363054735190196956789, _q), _q)
nt0 := addmod(nt0, mulmod(_t3, 9067734253445064890734144122526450279189023719890032859456830213166173619761, _q), _q)
nt0 := addmod(nt0, mulmod(_t4, 16378664841697311562845443097199265623838619398287411428110917414833007677155, _q), _q)
nt1 := mulmod(_t0, 107933704346764130067829474107909495889716688591997879426350582457782826785, _q)
nt1 := addmod(nt1, mulmod(_t1, 17034139127218860091985397764514160131253018178110701196935786874261236172431, _q), _q)
nt1 := addmod(nt1, mulmod(_t2, 2799255644797227968811798608332314218966179365168250111693473252876996230317, _q), _q)
nt1 := addmod(nt1, mulmod(_t3, 2482058150180648511543788012634934806465808146786082148795902594096349483974, _q), _q)
nt1 := addmod(nt1, mulmod(_t4, 16563522740626180338295201738437974404892092704059676533096069531044355099628, _q), _q)
nt2 := mulmod(_t0, 13596762909635538739079656925495736900379091964739248298531655823337482778123, _q)
nt2 := addmod(nt2, mulmod(_t1, 18985203040268814769637347880759846911264240088034262814847924884273017355969, _q), _q)
nt2 := addmod(nt2, mulmod(_t2, 8652975463545710606098548415650457376967119951977109072274595329619335974180, _q), _q)
nt2 := addmod(nt2, mulmod(_t3, 970943815872417895015626519859542525373809485973005165410533315057253476903, _q), _q)
nt2 := addmod(nt2, mulmod(_t4, 19406667490568134101658669326517700199745817783746545889094238643063688871948, _q), _q)
nt3 := mulmod(_t0, 2953507793609469112222895633455544691298656192015062835263784675891831794974, _q)
nt3 := addmod(nt3, mulmod(_t1, 19025623051770008118343718096455821045904242602531062247152770448380880817517, _q), _q)
nt3 := addmod(nt3, mulmod(_t2, 9077319817220936628089890431129759976815127354480867310384708941479362824016, _q), _q)
nt3 := addmod(nt3, mulmod(_t3, 4770370314098695913091200576539533727214143013236894216582648993741910829490, _q), _q)
nt3 := addmod(nt3, mulmod(_t4, 4298564056297802123194408918029088169104276109138370115401819933600955259473, _q), _q)
nt4 := mulmod(_t0, 8336710468787894148066071988103915091676109272951895469087957569358494947747, _q)
nt4 := addmod(nt4, mulmod(_t1, 16205238342129310687768799056463408647672389183328001070715567975181364448609, _q), _q)
nt4 := addmod(nt4, mulmod(_t2, 8303849270045876854140023508764676765932043944545416856530551331270859502246, _q), _q)
nt4 := addmod(nt4, mulmod(_t3, 20218246699596954048529384569730026273241102596326201163062133863539137060414, _q), _q)
nt4 := addmod(nt4, mulmod(_t4, 1712845821388089905746651754894206522004527237615042226559791118162382909269, _q), _q)
}
function ark(_t0, _t1, _t2, _t3, _t4, _q, c) -> nt0, nt1, nt2, nt3, nt4 {
nt0 := addmod(_t0, c, _q)
nt1 := addmod(_t1, c, _q)
nt2 := addmod(_t2, c, _q)
nt3 := addmod(_t3, c, _q)
nt4 := addmod(_t4, c, _q)
}
function sbox_full(_t0, _t1, _t2, _t3, _t4, _q) -> nt0, nt1, nt2, nt3, nt4 {
nt0 := mulmod(_t0, _t0, _q)
nt0 := mulmod(nt0, nt0, _q)
nt0 := mulmod(_t0, nt0, _q)
nt1 := mulmod(_t1, _t1, _q)
nt1 := mulmod(nt1, nt1, _q)
nt1 := mulmod(_t1, nt1, _q)
nt2 := mulmod(_t2, _t2, _q)
nt2 := mulmod(nt2, nt2, _q)
nt2 := mulmod(_t2, nt2, _q)
nt3 := mulmod(_t3, _t3, _q)
nt3 := mulmod(nt3, nt3, _q)
nt3 := mulmod(_t3, nt3, _q)
nt4 := mulmod(_t4, _t4, _q)
nt4 := mulmod(nt4, nt4, _q)
nt4 := mulmod(_t4, nt4, _q)
}
function sbox_partial(_t, _q) -> nt {
nt := mulmod(_t, _t, _q)
nt := mulmod(nt, nt, _q)
nt := mulmod(_t, nt, _q)
}
// round 0
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 14397397413755236225575615486459253198602422701513067526754101844196324375522)
t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 1
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 10405129301473404666785234951972711717481302463898292859783056520670200613128)
t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 2
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 5179144822360023508491245509308555580251733042407187134628755730783052214509)
t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 3
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 9132640374240188374542843306219594180154739721841249568925550236430986592615)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 4
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20360807315276763881209958738450444293273549928693737723235350358403012458514)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 5
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 17933600965499023212689924809448543050840131883187652471064418452962948061619)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 6
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 3636213416533737411392076250708419981662897009810345015164671602334517041153)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 7
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2008540005368330234524962342006691994500273283000229509835662097352946198608)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 8
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 16018407964853379535338740313053768402596521780991140819786560130595652651567)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 9
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20653139667070586705378398435856186172195806027708437373983929336015162186471)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 10
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 17887713874711369695406927657694993484804203950786446055999405564652412116765)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 11
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 4852706232225925756777361208698488277369799648067343227630786518486608711772)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 12
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 8969172011633935669771678412400911310465619639756845342775631896478908389850)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 13
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20570199545627577691240476121888846460936245025392381957866134167601058684375)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 14
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 16442329894745639881165035015179028112772410105963688121820543219662832524136)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 15
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20060625627350485876280451423010593928172611031611836167979515653463693899374)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 16
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 16637282689940520290130302519163090147511023430395200895953984829546679599107)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 17
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15599196921909732993082127725908821049411366914683565306060493533569088698214)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 18
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 16894591341213863947423904025624185991098788054337051624251730868231322135455)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 19
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 1197934381747032348421303489683932612752526046745577259575778515005162320212)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 20
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 6172482022646932735745595886795230725225293469762393889050804649558459236626)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 21
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 21004037394166516054140386756510609698837211370585899203851827276330669555417)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 22
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15262034989144652068456967541137853724140836132717012646544737680069032573006)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 23
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15017690682054366744270630371095785995296470601172793770224691982518041139766)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 24
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15159744167842240513848638419303545693472533086570469712794583342699782519832)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 25
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 11178069035565459212220861899558526502477231302924961773582350246646450941231)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 26
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 21154888769130549957415912997229564077486639529994598560737238811887296922114)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 27
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20162517328110570500010831422938033120419484532231241180224283481905744633719)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 28
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2777362604871784250419758188173029886707024739806641263170345377816177052018)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 29
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15732290486829619144634131656503993123618032247178179298922551820261215487562)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 30
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 6024433414579583476444635447152826813568595303270846875177844482142230009826)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 31
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 17677827682004946431939402157761289497221048154630238117709539216286149983245)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 32
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 10716307389353583413755237303156291454109852751296156900963208377067748518748)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 33
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 14925386988604173087143546225719076187055229908444910452781922028996524347508)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 34
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 8940878636401797005293482068100797531020505636124892198091491586778667442523)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 35
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 18911747154199663060505302806894425160044925686870165583944475880789706164410)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 36
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 8821532432394939099312235292271438180996556457308429936910969094255825456935)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 37
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20632576502437623790366878538516326728436616723089049415538037018093616927643)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 38
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 71447649211767888770311304010816315780740050029903404046389165015534756512)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 39
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2781996465394730190470582631099299305677291329609718650018200531245670229393)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 40
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 12441376330954323535872906380510501637773629931719508864016287320488688345525)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 41
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2558302139544901035700544058046419714227464650146159803703499681139469546006)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 42
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 10087036781939179132584550273563255199577525914374285705149349445480649057058)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 43
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 4267692623754666261749551533667592242661271409704769363166965280715887854739)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 44
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 4945579503584457514844595640661884835097077318604083061152997449742124905548)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 45
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 17742335354489274412669987990603079185096280484072783973732137326144230832311)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 46
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 6266270088302506215402996795500854910256503071464802875821837403486057988208)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 47
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2716062168542520412498610856550519519760063668165561277991771577403400784706)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 48
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 19118392018538203167410421493487769944462015419023083813301166096764262134232)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 49
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 9386595745626044000666050847309903206827901310677406022353307960932745699524)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 50
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 9121640807890366356465620448383131419933298563527245687958865317869840082266)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 51
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 3078975275808111706229899605611544294904276390490742680006005661017864583210)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 52
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 7157404299437167354719786626667769956233708887934477609633504801472827442743)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 53
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 14056248655941725362944552761799461694550787028230120190862133165195793034373)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 54
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 14124396743304355958915937804966111851843703158171757752158388556919187839849)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 55
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 11851254356749068692552943732920045260402277343008629727465773766468466181076)
t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 56
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 9799099446406796696742256539758943483211846559715874347178722060519817626047)
t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 57
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 10156146186214948683880719664738535455146137901666656566575307300522957959544)
t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
}
return t0;
}
function hash_t5f6p52(HashInputs5 memory i, uint q) internal pure returns (uint)
{
// validate inputs
require(i.t0 < q, "INVALID_INPUT");
require(i.t1 < q, "INVALID_INPUT");
require(i.t2 < q, "INVALID_INPUT");
require(i.t3 < q, "INVALID_INPUT");
require(i.t4 < q, "INVALID_INPUT");
return hash_t5f6p52_internal(i.t0, i.t1, i.t2, i.t3, i.t4, q);
}
//
// hash_t7f6p52
//
struct HashInputs7
{
uint t0;
uint t1;
uint t2;
uint t3;
uint t4;
uint t5;
uint t6;
}
function mix(HashInputs7 memory i, uint q) internal pure
{
HashInputs7 memory o;
o.t0 = mulmod(i.t0, 14183033936038168803360723133013092560869148726790180682363054735190196956789, q);
o.t0 = addmod(o.t0, mulmod(i.t1, 9067734253445064890734144122526450279189023719890032859456830213166173619761, q), q);
o.t0 = addmod(o.t0, mulmod(i.t2, 16378664841697311562845443097199265623838619398287411428110917414833007677155, q), q);
o.t0 = addmod(o.t0, mulmod(i.t3, 12968540216479938138647596899147650021419273189336843725176422194136033835172, q), q);
o.t0 = addmod(o.t0, mulmod(i.t4, 3636162562566338420490575570584278737093584021456168183289112789616069756675, q), q);
o.t0 = addmod(o.t0, mulmod(i.t5, 8949952361235797771659501126471156178804092479420606597426318793013844305422, q), q);
o.t0 = addmod(o.t0, mulmod(i.t6, 13586657904816433080148729258697725609063090799921401830545410130405357110367, q), q);
o.t1 = mulmod(i.t0, 2799255644797227968811798608332314218966179365168250111693473252876996230317, q);
o.t1 = addmod(o.t1, mulmod(i.t1, 2482058150180648511543788012634934806465808146786082148795902594096349483974, q), q);
o.t1 = addmod(o.t1, mulmod(i.t2, 16563522740626180338295201738437974404892092704059676533096069531044355099628, q), q);
o.t1 = addmod(o.t1, mulmod(i.t3, 10468644849657689537028565510142839489302836569811003546969773105463051947124, q), q);
o.t1 = addmod(o.t1, mulmod(i.t4, 3328913364598498171733622353010907641674136720305714432354138807013088636408, q), q);
o.t1 = addmod(o.t1, mulmod(i.t5, 8642889650254799419576843603477253661899356105675006557919250564400804756641, q), q);
o.t1 = addmod(o.t1, mulmod(i.t6, 14300697791556510113764686242794463641010174685800128469053974698256194076125, q), q);
o.t2 = mulmod(i.t0, 8652975463545710606098548415650457376967119951977109072274595329619335974180, q);
o.t2 = addmod(o.t2, mulmod(i.t1, 970943815872417895015626519859542525373809485973005165410533315057253476903, q), q);
o.t2 = addmod(o.t2, mulmod(i.t2, 19406667490568134101658669326517700199745817783746545889094238643063688871948, q), q);
o.t2 = addmod(o.t2, mulmod(i.t3, 17049854690034965250221386317058877242629221002521630573756355118745574274967, q), q);
o.t2 = addmod(o.t2, mulmod(i.t4, 4964394613021008685803675656098849539153699842663541444414978877928878266244, q), q);
o.t2 = addmod(o.t2, mulmod(i.t5, 15474947305445649466370538888925567099067120578851553103424183520405650587995, q), q);
o.t2 = addmod(o.t2, mulmod(i.t6, 1016119095639665978105768933448186152078842964810837543326777554729232767846, q), q);
o.t3 = mulmod(i.t0, 9077319817220936628089890431129759976815127354480867310384708941479362824016, q);
o.t3 = addmod(o.t3, mulmod(i.t1, 4770370314098695913091200576539533727214143013236894216582648993741910829490, q), q);
o.t3 = addmod(o.t3, mulmod(i.t2, 4298564056297802123194408918029088169104276109138370115401819933600955259473, q), q);
o.t3 = addmod(o.t3, mulmod(i.t3, 6905514380186323693285869145872115273350947784558995755916362330070690839131, q), q);
o.t3 = addmod(o.t3, mulmod(i.t4, 4783343257810358393326889022942241108539824540285247795235499223017138301952, q), q);
o.t3 = addmod(o.t3, mulmod(i.t5, 1420772902128122367335354247676760257656541121773854204774788519230732373317, q), q);
o.t3 = addmod(o.t3, mulmod(i.t6, 14172871439045259377975734198064051992755748777535789572469924335100006948373, q), q);
o.t4 = mulmod(i.t0, 8303849270045876854140023508764676765932043944545416856530551331270859502246, q);
o.t4 = addmod(o.t4, mulmod(i.t1, 20218246699596954048529384569730026273241102596326201163062133863539137060414, q), q);
o.t4 = addmod(o.t4, mulmod(i.t2, 1712845821388089905746651754894206522004527237615042226559791118162382909269, q), q);
o.t4 = addmod(o.t4, mulmod(i.t3, 13001155522144542028910638547179410124467185319212645031214919884423841839406, q), q);
o.t4 = addmod(o.t4, mulmod(i.t4, 16037892369576300958623292723740289861626299352695838577330319504984091062115, q), q);
o.t4 = addmod(o.t4, mulmod(i.t5, 19189494548480259335554606182055502469831573298885662881571444557262020106898, q), q);
o.t4 = addmod(o.t4, mulmod(i.t6, 19032687447778391106390582750185144485341165205399984747451318330476859342654, q), q);
o.t5 = mulmod(i.t0, 13272957914179340594010910867091459756043436017766464331915862093201960540910, q);
o.t5 = addmod(o.t5, mulmod(i.t1, 9416416589114508529880440146952102328470363729880726115521103179442988482948, q), q);
o.t5 = addmod(o.t5, mulmod(i.t2, 8035240799672199706102747147502951589635001418759394863664434079699838251138, q), q);
o.t5 = addmod(o.t5, mulmod(i.t3, 21642389080762222565487157652540372010968704000567605990102641816691459811717, q), q);
o.t5 = addmod(o.t5, mulmod(i.t4, 20261355950827657195644012399234591122288573679402601053407151083849785332516, q), q);
o.t5 = addmod(o.t5, mulmod(i.t5, 14514189384576734449268559374569145463190040567900950075547616936149781403109, q), q);
o.t5 = addmod(o.t5, mulmod(i.t6, 19038036134886073991945204537416211699632292792787812530208911676638479944765, q), q);
o.t6 = mulmod(i.t0, 15627836782263662543041758927100784213807648787083018234961118439434298020664, q);
o.t6 = addmod(o.t6, mulmod(i.t1, 5655785191024506056588710805596292231240948371113351452712848652644610823632, q), q);
o.t6 = addmod(o.t6, mulmod(i.t2, 8265264721707292643644260517162050867559314081394556886644673791575065394002, q), q);
o.t6 = addmod(o.t6, mulmod(i.t3, 17151144681903609082202835646026478898625761142991787335302962548605510241586, q), q);
o.t6 = addmod(o.t6, mulmod(i.t4, 18731644709777529787185361516475509623264209648904603914668024590231177708831, q), q);
o.t6 = addmod(o.t6, mulmod(i.t5, 20697789991623248954020701081488146717484139720322034504511115160686216223641, q), q);
o.t6 = addmod(o.t6, mulmod(i.t6, 6200020095464686209289974437830528853749866001482481427982839122465470640886, q), q);
i.t0 = o.t0;
i.t1 = o.t1;
i.t2 = o.t2;
i.t3 = o.t3;
i.t4 = o.t4;
i.t5 = o.t5;
i.t6 = o.t6;
}
function ark(HashInputs7 memory i, uint q, uint c) internal pure
{
HashInputs7 memory o;
o.t0 = addmod(i.t0, c, q);
o.t1 = addmod(i.t1, c, q);
o.t2 = addmod(i.t2, c, q);
o.t3 = addmod(i.t3, c, q);
o.t4 = addmod(i.t4, c, q);
o.t5 = addmod(i.t5, c, q);
o.t6 = addmod(i.t6, c, q);
i.t0 = o.t0;
i.t1 = o.t1;
i.t2 = o.t2;
i.t3 = o.t3;
i.t4 = o.t4;
i.t5 = o.t5;
i.t6 = o.t6;
}
function sbox_full(HashInputs7 memory i, uint q) internal pure
{
HashInputs7 memory o;
o.t0 = mulmod(i.t0, i.t0, q);
o.t0 = mulmod(o.t0, o.t0, q);
o.t0 = mulmod(i.t0, o.t0, q);
o.t1 = mulmod(i.t1, i.t1, q);
o.t1 = mulmod(o.t1, o.t1, q);
o.t1 = mulmod(i.t1, o.t1, q);
o.t2 = mulmod(i.t2, i.t2, q);
o.t2 = mulmod(o.t2, o.t2, q);
o.t2 = mulmod(i.t2, o.t2, q);
o.t3 = mulmod(i.t3, i.t3, q);
o.t3 = mulmod(o.t3, o.t3, q);
o.t3 = mulmod(i.t3, o.t3, q);
o.t4 = mulmod(i.t4, i.t4, q);
o.t4 = mulmod(o.t4, o.t4, q);
o.t4 = mulmod(i.t4, o.t4, q);
o.t5 = mulmod(i.t5, i.t5, q);
o.t5 = mulmod(o.t5, o.t5, q);
o.t5 = mulmod(i.t5, o.t5, q);
o.t6 = mulmod(i.t6, i.t6, q);
o.t6 = mulmod(o.t6, o.t6, q);
o.t6 = mulmod(i.t6, o.t6, q);
i.t0 = o.t0;
i.t1 = o.t1;
i.t2 = o.t2;
i.t3 = o.t3;
i.t4 = o.t4;
i.t5 = o.t5;
i.t6 = o.t6;
}
function sbox_partial(HashInputs7 memory i, uint q) internal pure
{
HashInputs7 memory o;
o.t0 = mulmod(i.t0, i.t0, q);
o.t0 = mulmod(o.t0, o.t0, q);
o.t0 = mulmod(i.t0, o.t0, q);
i.t0 = o.t0;
}
function hash_t7f6p52(HashInputs7 memory i, uint q) internal pure returns (uint)
{
// validate inputs
require(i.t0 < q, "INVALID_INPUT");
require(i.t1 < q, "INVALID_INPUT");
require(i.t2 < q, "INVALID_INPUT");
require(i.t3 < q, "INVALID_INPUT");
require(i.t4 < q, "INVALID_INPUT");
require(i.t5 < q, "INVALID_INPUT");
require(i.t6 < q, "INVALID_INPUT");
// round 0
ark(i, q, 14397397413755236225575615486459253198602422701513067526754101844196324375522);
sbox_full(i, q);
mix(i, q);
// round 1
ark(i, q, 10405129301473404666785234951972711717481302463898292859783056520670200613128);
sbox_full(i, q);
mix(i, q);
// round 2
ark(i, q, 5179144822360023508491245509308555580251733042407187134628755730783052214509);
sbox_full(i, q);
mix(i, q);
// round 3
ark(i, q, 9132640374240188374542843306219594180154739721841249568925550236430986592615);
sbox_partial(i, q);
mix(i, q);
// round 4
ark(i, q, 20360807315276763881209958738450444293273549928693737723235350358403012458514);
sbox_partial(i, q);
mix(i, q);
// round 5
ark(i, q, 17933600965499023212689924809448543050840131883187652471064418452962948061619);
sbox_partial(i, q);
mix(i, q);
// round 6
ark(i, q, 3636213416533737411392076250708419981662897009810345015164671602334517041153);
sbox_partial(i, q);
mix(i, q);
// round 7
ark(i, q, 2008540005368330234524962342006691994500273283000229509835662097352946198608);
sbox_partial(i, q);
mix(i, q);
// round 8
ark(i, q, 16018407964853379535338740313053768402596521780991140819786560130595652651567);
sbox_partial(i, q);
mix(i, q);
// round 9
ark(i, q, 20653139667070586705378398435856186172195806027708437373983929336015162186471);
sbox_partial(i, q);
mix(i, q);
// round 10
ark(i, q, 17887713874711369695406927657694993484804203950786446055999405564652412116765);
sbox_partial(i, q);
mix(i, q);
// round 11
ark(i, q, 4852706232225925756777361208698488277369799648067343227630786518486608711772);
sbox_partial(i, q);
mix(i, q);
// round 12
ark(i, q, 8969172011633935669771678412400911310465619639756845342775631896478908389850);
sbox_partial(i, q);
mix(i, q);
// round 13
ark(i, q, 20570199545627577691240476121888846460936245025392381957866134167601058684375);
sbox_partial(i, q);
mix(i, q);
// round 14
ark(i, q, 16442329894745639881165035015179028112772410105963688121820543219662832524136);
sbox_partial(i, q);
mix(i, q);
// round 15
ark(i, q, 20060625627350485876280451423010593928172611031611836167979515653463693899374);
sbox_partial(i, q);
mix(i, q);
// round 16
ark(i, q, 16637282689940520290130302519163090147511023430395200895953984829546679599107);
sbox_partial(i, q);
mix(i, q);
// round 17
ark(i, q, 15599196921909732993082127725908821049411366914683565306060493533569088698214);
sbox_partial(i, q);
mix(i, q);
// round 18
ark(i, q, 16894591341213863947423904025624185991098788054337051624251730868231322135455);
sbox_partial(i, q);
mix(i, q);
// round 19
ark(i, q, 1197934381747032348421303489683932612752526046745577259575778515005162320212);
sbox_partial(i, q);
mix(i, q);
// round 20
ark(i, q, 6172482022646932735745595886795230725225293469762393889050804649558459236626);
sbox_partial(i, q);
mix(i, q);
// round 21
ark(i, q, 21004037394166516054140386756510609698837211370585899203851827276330669555417);
sbox_partial(i, q);
mix(i, q);
// round 22
ark(i, q, 15262034989144652068456967541137853724140836132717012646544737680069032573006);
sbox_partial(i, q);
mix(i, q);
// round 23
ark(i, q, 15017690682054366744270630371095785995296470601172793770224691982518041139766);
sbox_partial(i, q);
mix(i, q);
// round 24
ark(i, q, 15159744167842240513848638419303545693472533086570469712794583342699782519832);
sbox_partial(i, q);
mix(i, q);
// round 25
ark(i, q, 11178069035565459212220861899558526502477231302924961773582350246646450941231);
sbox_partial(i, q);
mix(i, q);
// round 26
ark(i, q, 21154888769130549957415912997229564077486639529994598560737238811887296922114);
sbox_partial(i, q);
mix(i, q);
// round 27
ark(i, q, 20162517328110570500010831422938033120419484532231241180224283481905744633719);
sbox_partial(i, q);
mix(i, q);
// round 28
ark(i, q, 2777362604871784250419758188173029886707024739806641263170345377816177052018);
sbox_partial(i, q);
mix(i, q);
// round 29
ark(i, q, 15732290486829619144634131656503993123618032247178179298922551820261215487562);
sbox_partial(i, q);
mix(i, q);
// round 30
ark(i, q, 6024433414579583476444635447152826813568595303270846875177844482142230009826);
sbox_partial(i, q);
mix(i, q);
// round 31
ark(i, q, 17677827682004946431939402157761289497221048154630238117709539216286149983245);
sbox_partial(i, q);
mix(i, q);
// round 32
ark(i, q, 10716307389353583413755237303156291454109852751296156900963208377067748518748);
sbox_partial(i, q);
mix(i, q);
// round 33
ark(i, q, 14925386988604173087143546225719076187055229908444910452781922028996524347508);
sbox_partial(i, q);
mix(i, q);
// round 34
ark(i, q, 8940878636401797005293482068100797531020505636124892198091491586778667442523);
sbox_partial(i, q);
mix(i, q);
// round 35
ark(i, q, 18911747154199663060505302806894425160044925686870165583944475880789706164410);
sbox_partial(i, q);
mix(i, q);
// round 36
ark(i, q, 8821532432394939099312235292271438180996556457308429936910969094255825456935);
sbox_partial(i, q);
mix(i, q);
// round 37
ark(i, q, 20632576502437623790366878538516326728436616723089049415538037018093616927643);
sbox_partial(i, q);
mix(i, q);
// round 38
ark(i, q, 71447649211767888770311304010816315780740050029903404046389165015534756512);
sbox_partial(i, q);
mix(i, q);
// round 39
ark(i, q, 2781996465394730190470582631099299305677291329609718650018200531245670229393);
sbox_partial(i, q);
mix(i, q);
// round 40
ark(i, q, 12441376330954323535872906380510501637773629931719508864016287320488688345525);
sbox_partial(i, q);
mix(i, q);
// round 41
ark(i, q, 2558302139544901035700544058046419714227464650146159803703499681139469546006);
sbox_partial(i, q);
mix(i, q);
// round 42
ark(i, q, 10087036781939179132584550273563255199577525914374285705149349445480649057058);
sbox_partial(i, q);
mix(i, q);
// round 43
ark(i, q, 4267692623754666261749551533667592242661271409704769363166965280715887854739);
sbox_partial(i, q);
mix(i, q);
// round 44
ark(i, q, 4945579503584457514844595640661884835097077318604083061152997449742124905548);
sbox_partial(i, q);
mix(i, q);
// round 45
ark(i, q, 17742335354489274412669987990603079185096280484072783973732137326144230832311);
sbox_partial(i, q);
mix(i, q);
// round 46
ark(i, q, 6266270088302506215402996795500854910256503071464802875821837403486057988208);
sbox_partial(i, q);
mix(i, q);
// round 47
ark(i, q, 2716062168542520412498610856550519519760063668165561277991771577403400784706);
sbox_partial(i, q);
mix(i, q);
// round 48
ark(i, q, 19118392018538203167410421493487769944462015419023083813301166096764262134232);
sbox_partial(i, q);
mix(i, q);
// round 49
ark(i, q, 9386595745626044000666050847309903206827901310677406022353307960932745699524);
sbox_partial(i, q);
mix(i, q);
// round 50
ark(i, q, 9121640807890366356465620448383131419933298563527245687958865317869840082266);
sbox_partial(i, q);
mix(i, q);
// round 51
ark(i, q, 3078975275808111706229899605611544294904276390490742680006005661017864583210);
sbox_partial(i, q);
mix(i, q);
// round 52
ark(i, q, 7157404299437167354719786626667769956233708887934477609633504801472827442743);
sbox_partial(i, q);
mix(i, q);
// round 53
ark(i, q, 14056248655941725362944552761799461694550787028230120190862133165195793034373);
sbox_partial(i, q);
mix(i, q);
// round 54
ark(i, q, 14124396743304355958915937804966111851843703158171757752158388556919187839849);
sbox_partial(i, q);
mix(i, q);
// round 55
ark(i, q, 11851254356749068692552943732920045260402277343008629727465773766468466181076);
sbox_full(i, q);
mix(i, q);
// round 56
ark(i, q, 9799099446406796696742256539758943483211846559715874347178722060519817626047);
sbox_full(i, q);
mix(i, q);
// round 57
ark(i, q, 10156146186214948683880719664738535455146137901666656566575307300522957959544);
sbox_full(i, q);
mix(i, q);
return i.t0;
}
}
// File: contracts/core/impl/libexchange/ExchangeBalances.sol
// Copyright 2017 Loopring Technology Limited.
/// @title ExchangeBalances.
/// @author Daniel Wang - <daniel@loopring.org>
/// @author Brecht Devos - <brecht@loopring.org>
library ExchangeBalances
{
using MathUint for uint;
function verifyAccountBalance(
uint merkleRoot,
ExchangeData.MerkleProof calldata merkleProof
)
public
pure
{
require(
isAccountBalanceCorrect(merkleRoot, merkleProof),
"INVALID_MERKLE_TREE_DATA"
);
}
function isAccountBalanceCorrect(
uint merkleRoot,
ExchangeData.MerkleProof memory merkleProof
)
public
pure
returns (bool)
{
// Calculate the Merkle root using the Merkle paths provided
uint calculatedRoot = getBalancesRoot(
merkleProof.balanceLeaf.tokenID,
merkleProof.balanceLeaf.balance,
merkleProof.balanceLeaf.weightAMM,
merkleProof.balanceLeaf.storageRoot,
merkleProof.balanceMerkleProof
);
calculatedRoot = getAccountInternalsRoot(
merkleProof.accountLeaf.accountID,
merkleProof.accountLeaf.owner,
merkleProof.accountLeaf.pubKeyX,
merkleProof.accountLeaf.pubKeyY,
merkleProof.accountLeaf.nonce,
merkleProof.accountLeaf.feeBipsAMM,
calculatedRoot,
merkleProof.accountMerkleProof
);
// Check against the expected Merkle root
return (calculatedRoot == merkleRoot);
}
function getBalancesRoot(
uint16 tokenID,
uint balance,
uint weightAMM,
uint storageRoot,
uint[24] memory balanceMerkleProof
)
private
pure
returns (uint)
{
// Hash the balance leaf
uint balanceItem = hashImpl(balance, weightAMM, storageRoot, 0);
// Calculate the Merkle root of the balance quad Merkle tree
uint _id = tokenID;
for (uint depth = 0; depth < 8; depth++) {
uint base = depth * 3;
if (_id & 3 == 0) {
balanceItem = hashImpl(
balanceItem,
balanceMerkleProof[base],
balanceMerkleProof[base + 1],
balanceMerkleProof[base + 2]
);
} else if (_id & 3 == 1) {
balanceItem = hashImpl(
balanceMerkleProof[base],
balanceItem,
balanceMerkleProof[base + 1],
balanceMerkleProof[base + 2]
);
} else if (_id & 3 == 2) {
balanceItem = hashImpl(
balanceMerkleProof[base],
balanceMerkleProof[base + 1],
balanceItem,
balanceMerkleProof[base + 2]
);
} else if (_id & 3 == 3) {
balanceItem = hashImpl(
balanceMerkleProof[base],
balanceMerkleProof[base + 1],
balanceMerkleProof[base + 2],
balanceItem
);
}
_id = _id >> 2;
}
return balanceItem;
}
function getAccountInternalsRoot(
uint32 accountID,
address owner,
uint pubKeyX,
uint pubKeyY,
uint nonce,
uint feeBipsAMM,
uint balancesRoot,
uint[48] memory accountMerkleProof
)
private
pure
returns (uint)
{
// Hash the account leaf
uint accountItem = hashAccountLeaf(uint(owner), pubKeyX, pubKeyY, nonce, feeBipsAMM, balancesRoot);
// Calculate the Merkle root of the account quad Merkle tree
uint _id = accountID;
for (uint depth = 0; depth < 16; depth++) {
uint base = depth * 3;
if (_id & 3 == 0) {
accountItem = hashImpl(
accountItem,
accountMerkleProof[base],
accountMerkleProof[base + 1],
accountMerkleProof[base + 2]
);
} else if (_id & 3 == 1) {
accountItem = hashImpl(
accountMerkleProof[base],
accountItem,
accountMerkleProof[base + 1],
accountMerkleProof[base + 2]
);
} else if (_id & 3 == 2) {
accountItem = hashImpl(
accountMerkleProof[base],
accountMerkleProof[base + 1],
accountItem,
accountMerkleProof[base + 2]
);
} else if (_id & 3 == 3) {
accountItem = hashImpl(
accountMerkleProof[base],
accountMerkleProof[base + 1],
accountMerkleProof[base + 2],
accountItem
);
}
_id = _id >> 2;
}
return accountItem;
}
function hashAccountLeaf(
uint t0,
uint t1,
uint t2,
uint t3,
uint t4,
uint t5
)
public
pure
returns (uint)
{
Poseidon.HashInputs7 memory inputs = Poseidon.HashInputs7(t0, t1, t2, t3, t4, t5, 0);
return Poseidon.hash_t7f6p52(inputs, ExchangeData.SNARK_SCALAR_FIELD);
}
function hashImpl(
uint t0,
uint t1,
uint t2,
uint t3
)
private
pure
returns (uint)
{
Poseidon.HashInputs5 memory inputs = Poseidon.HashInputs5(t0, t1, t2, t3, 0);
return Poseidon.hash_t5f6p52(inputs, ExchangeData.SNARK_SCALAR_FIELD);
}
}
// File: contracts/lib/ERC20SafeTransfer.sol
// Copyright 2017 Loopring Technology Limited.
/// @title ERC20 safe transfer
/// @dev see https://github.com/sec-bit/badERC20Fix
/// @author Brecht Devos - <brecht@loopring.org>
library ERC20SafeTransfer
{
function safeTransferAndVerify(
address token,
address to,
uint value
)
internal
{
safeTransferWithGasLimitAndVerify(
token,
to,
value,
gasleft()
);
}
function safeTransfer(
address token,
address to,
uint value
)
internal
returns (bool)
{
return safeTransferWithGasLimit(
token,
to,
value,
gasleft()
);
}
function safeTransferWithGasLimitAndVerify(
address token,
address to,
uint value,
uint gasLimit
)
internal
{
require(
safeTransferWithGasLimit(token, to, value, gasLimit),
"TRANSFER_FAILURE"
);
}
function safeTransferWithGasLimit(
address token,
address to,
uint value,
uint gasLimit
)
internal
returns (bool)
{
// A transfer is successful when 'call' is successful and depending on the token:
// - No value is returned: we assume a revert when the transfer failed (i.e. 'call' returns false)
// - A single boolean is returned: this boolean needs to be true (non-zero)
// bytes4(keccak256("transfer(address,uint256)")) = 0xa9059cbb
bytes memory callData = abi.encodeWithSelector(
bytes4(0xa9059cbb),
to,
value
);
(bool success, ) = token.call{gas: gasLimit}(callData);
return checkReturnValue(success);
}
function safeTransferFromAndVerify(
address token,
address from,
address to,
uint value
)
internal
{
safeTransferFromWithGasLimitAndVerify(
token,
from,
to,
value,
gasleft()
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint value
)
internal
returns (bool)
{
return safeTransferFromWithGasLimit(
token,
from,
to,
value,
gasleft()
);
}
function safeTransferFromWithGasLimitAndVerify(
address token,
address from,
address to,
uint value,
uint gasLimit
)
internal
{
bool result = safeTransferFromWithGasLimit(
token,
from,
to,
value,
gasLimit
);
require(result, "TRANSFER_FAILURE");
}
function safeTransferFromWithGasLimit(
address token,
address from,
address to,
uint value,
uint gasLimit
)
internal
returns (bool)
{
// A transferFrom is successful when 'call' is successful and depending on the token:
// - No value is returned: we assume a revert when the transfer failed (i.e. 'call' returns false)
// - A single boolean is returned: this boolean needs to be true (non-zero)
// bytes4(keccak256("transferFrom(address,address,uint256)")) = 0x23b872dd
bytes memory callData = abi.encodeWithSelector(
bytes4(0x23b872dd),
from,
to,
value
);
(bool success, ) = token.call{gas: gasLimit}(callData);
return checkReturnValue(success);
}
function checkReturnValue(
bool success
)
internal
pure
returns (bool)
{
// A transfer/transferFrom is successful when 'call' is successful and depending on the token:
// - No value is returned: we assume a revert when the transfer failed (i.e. 'call' returns false)
// - A single boolean is returned: this boolean needs to be true (non-zero)
if (success) {
assembly {
switch returndatasize()
// Non-standard ERC20: nothing is returned so if 'call' was successful we assume the transfer succeeded
case 0 {
success := 1
}
// Standard ERC20: a single boolean value is returned which needs to be true
case 32 {
returndatacopy(0, 0, 32)
success := mload(0)
}
// None of the above: not successful
default {
success := 0
}
}
}
return success;
}
}
// File: contracts/core/impl/libexchange/ExchangeTokens.sol
// Copyright 2017 Loopring Technology Limited.
/// @title ExchangeTokens.
/// @author Daniel Wang - <daniel@loopring.org>
/// @author Brecht Devos - <brecht@loopring.org>
library ExchangeTokens
{
using MathUint for uint;
using ERC20SafeTransfer for address;
using ExchangeMode for ExchangeData.State;
event TokenRegistered(
address token,
uint16 tokenId
);
function getTokenAddress(
ExchangeData.State storage S,
uint16 tokenID
)
public
view
returns (address)
{
require(tokenID < S.tokens.length, "INVALID_TOKEN_ID");
return S.tokens[tokenID].token;
}
function registerToken(
ExchangeData.State storage S,
address tokenAddress
)
public
returns (uint16 tokenID)
{
require(!S.isInWithdrawalMode(), "INVALID_MODE");
require(S.tokenToTokenId[tokenAddress] == 0, "TOKEN_ALREADY_EXIST");
require(S.tokens.length < ExchangeData.MAX_NUM_TOKENS, "TOKEN_REGISTRY_FULL");
// Check if the deposit contract supports the new token
if (S.depositContract != IDepositContract(0)) {
require(
S.depositContract.isTokenSupported(tokenAddress),
"UNSUPPORTED_TOKEN"
);
}
// Assign a tokenID and store the token
ExchangeData.Token memory token = ExchangeData.Token(
tokenAddress
);
tokenID = uint16(S.tokens.length);
S.tokens.push(token);
S.tokenToTokenId[tokenAddress] = tokenID + 1;
emit TokenRegistered(tokenAddress, tokenID);
}
function getTokenID(
ExchangeData.State storage S,
address tokenAddress
)
internal // inline call
view
returns (uint16 tokenID)
{
tokenID = S.tokenToTokenId[tokenAddress];
require(tokenID != 0, "TOKEN_NOT_FOUND");
tokenID = tokenID - 1;
}
}
// File: contracts/core/impl/libexchange/ExchangeWithdrawals.sol
// Copyright 2017 Loopring Technology Limited.
/// @title ExchangeWithdrawals.
/// @author Brecht Devos - <brecht@loopring.org>
/// @author Daniel Wang - <daniel@loopring.org>
library ExchangeWithdrawals
{
enum WithdrawalCategory
{
DISTRIBUTION,
FROM_MERKLE_TREE,
FROM_DEPOSIT_REQUEST,
FROM_APPROVED_WITHDRAWAL
}
using AddressUtil for address;
using AddressUtil for address payable;
using BytesUtil for bytes;
using MathUint for uint;
using ExchangeBalances for ExchangeData.State;
using ExchangeMode for ExchangeData.State;
using ExchangeTokens for ExchangeData.State;
event ForcedWithdrawalRequested(
address owner,
address token,
uint32 accountID
);
event WithdrawalCompleted(
uint8 category,
address from,
address to,
address token,
uint amount
);
event WithdrawalFailed(
uint8 category,
address from,
address to,
address token,
uint amount
);
function forceWithdraw(
ExchangeData.State storage S,
address owner,
address token,
uint32 accountID
)
public
{
require(!S.isInWithdrawalMode(), "INVALID_MODE");
// Limit the amount of pending forced withdrawals so that the owner cannot be overwhelmed.
require(S.getNumAvailableForcedSlots() > 0, "TOO_MANY_REQUESTS_OPEN");
require(accountID < ExchangeData.MAX_NUM_ACCOUNTS, "INVALID_ACCOUNTID");
uint16 tokenID = S.getTokenID(token);
// A user needs to pay a fixed ETH withdrawal fee, set by the protocol.
uint withdrawalFeeETH = S.loopring.forcedWithdrawalFee();
// Check ETH value sent, can be larger than the expected withdraw fee
require(msg.value >= withdrawalFeeETH, "INSUFFICIENT_FEE");
// Send surplus of ETH back to the sender
uint feeSurplus = msg.value.sub(withdrawalFeeETH);
if (feeSurplus > 0) {
msg.sender.sendETHAndVerify(feeSurplus, gasleft());
}
// There can only be a single forced withdrawal per (account, token) pair.
require(
S.pendingForcedWithdrawals[accountID][tokenID].timestamp == 0,
"WITHDRAWAL_ALREADY_PENDING"
);
// Store the forced withdrawal request data
S.pendingForcedWithdrawals[accountID][tokenID] = ExchangeData.ForcedWithdrawal({
owner: owner,
timestamp: uint64(block.timestamp)
});
// Increment the number of pending forced transactions so we can keep count.
S.numPendingForcedTransactions++;
emit ForcedWithdrawalRequested(
owner,
token,
accountID
);
}
// We alow anyone to withdraw these funds for the account owner
function withdrawFromMerkleTree(
ExchangeData.State storage S,
ExchangeData.MerkleProof calldata merkleProof
)
public
{
require(S.isInWithdrawalMode(), "NOT_IN_WITHDRAW_MODE");
address owner = merkleProof.accountLeaf.owner;
uint32 accountID = merkleProof.accountLeaf.accountID;
uint16 tokenID = merkleProof.balanceLeaf.tokenID;
uint96 balance = merkleProof.balanceLeaf.balance;
// Make sure the funds aren't withdrawn already.
require(S.withdrawnInWithdrawMode[accountID][tokenID] == false, "WITHDRAWN_ALREADY");
// Verify that the provided Merkle tree data is valid by using the Merkle proof.
ExchangeBalances.verifyAccountBalance(
uint(S.merkleRoot),
merkleProof
);
// Make sure the balance can only be withdrawn once
S.withdrawnInWithdrawMode[accountID][tokenID] = true;
// Transfer the tokens to the account owner
transferTokens(
S,
uint8(WithdrawalCategory.FROM_MERKLE_TREE),
owner,
owner,
tokenID,
balance,
new bytes(0),
gasleft(),
false
);
}
function withdrawFromDepositRequest(
ExchangeData.State storage S,
address owner,
address token
)
public
{
uint16 tokenID = S.getTokenID(token);
ExchangeData.Deposit storage deposit = S.pendingDeposits[owner][tokenID];
require(deposit.timestamp != 0, "DEPOSIT_NOT_WITHDRAWABLE_YET");
// Check if the deposit has indeed exceeded the time limit of if the exchange is in withdrawal mode
require(
block.timestamp >= deposit.timestamp + S.maxAgeDepositUntilWithdrawable ||
S.isInWithdrawalMode(),
"DEPOSIT_NOT_WITHDRAWABLE_YET"
);
uint amount = deposit.amount;
// Reset the deposit request
delete S.pendingDeposits[owner][tokenID];
// Transfer the tokens
transferTokens(
S,
uint8(WithdrawalCategory.FROM_DEPOSIT_REQUEST),
owner,
owner,
tokenID,
amount,
new bytes(0),
gasleft(),
false
);
}
function withdrawFromApprovedWithdrawals(
ExchangeData.State storage S,
address[] memory owners,
address[] memory tokens
)
public
{
require(owners.length == tokens.length, "INVALID_INPUT_DATA");
for (uint i = 0; i < owners.length; i++) {
address owner = owners[i];
uint16 tokenID = S.getTokenID(tokens[i]);
uint amount = S.amountWithdrawable[owner][tokenID];
// Make sure this amount can't be withdrawn again
delete S.amountWithdrawable[owner][tokenID];
// Transfer the tokens to the owner
transferTokens(
S,
uint8(WithdrawalCategory.FROM_APPROVED_WITHDRAWAL),
owner,
owner,
tokenID,
amount,
new bytes(0),
gasleft(),
false
);
}
}
function distributeWithdrawal(
ExchangeData.State storage S,
address from,
address to,
uint16 tokenID,
uint amount,
bytes memory extraData,
uint gasLimit
)
public
{
// Try to transfer the tokens
bool success = transferTokens(
S,
uint8(WithdrawalCategory.DISTRIBUTION),
from,
to,
tokenID,
amount,
extraData,
gasLimit,
true
);
// If the transfer was successful there's nothing left to do.
// However, if the transfer failed the tokens are still in the contract and can be
// withdrawn later to `to` by anyone by using `withdrawFromApprovedWithdrawal.
if (!success) {
S.amountWithdrawable[to][tokenID] = S.amountWithdrawable[to][tokenID].add(amount);
}
}
// == Internal and Private Functions ==
// If allowFailure is true the transfer can fail because of a transfer error or
// because the transfer uses more than `gasLimit` gas. The function
// will return true when successful, false otherwise.
// If allowFailure is false the transfer is guaranteed to succeed using
// as much gas as needed, otherwise it throws. The function always returns true.
function transferTokens(
ExchangeData.State storage S,
uint8 category,
address from,
address to,
uint16 tokenID,
uint amount,
bytes memory extraData,
uint gasLimit,
bool allowFailure
)
private
returns (bool success)
{
// Redirect withdrawals to address(0) to the protocol fee vault
if (to == address(0)) {
to = S.loopring.protocolFeeVault();
}
address token = S.getTokenAddress(tokenID);
// Transfer the tokens from the deposit contract to the owner
if (gasLimit > 0) {
try S.depositContract.withdraw{gas: gasLimit}(from, to, token, amount, extraData) {
success = true;
} catch {
success = false;
}
} else {
success = false;
}
require(allowFailure || success, "TRANSFER_FAILURE");
if (success) {
emit WithdrawalCompleted(category, from, to, token, amount);
// Keep track of when the protocol fees were last withdrawn
// (only done to make this data easier available).
if (from == address(0)) {
S.protocolFeeLastWithdrawnTime[token] = block.timestamp;
}
} else {
emit WithdrawalFailed(category, from, to, token, amount);
}
}
}
// File: contracts/core/impl/libtransactions/WithdrawTransaction.sol
// Copyright 2017 Loopring Technology Limited.
/// @title WithdrawTransaction
/// @author Brecht Devos - <brecht@loopring.org>
/// @dev The following 4 types of withdrawals are supported:
/// - withdrawType = 0: offchain withdrawals with EdDSA signatures
/// - withdrawType = 1: offchain withdrawals with ECDSA signatures or onchain appprovals
/// - withdrawType = 2: onchain valid forced withdrawals (owner and accountID match), or
/// offchain operator-initiated withdrawals for protocol fees or for
/// users in shutdown mode
/// - withdrawType = 3: onchain invalid forced withdrawals (owner and accountID mismatch)
library WithdrawTransaction
{
using BytesUtil for bytes;
using FloatUtil for uint16;
using MathUint for uint;
using ExchangeMode for ExchangeData.State;
using ExchangeSignatures for ExchangeData.State;
using ExchangeWithdrawals for ExchangeData.State;
bytes32 constant public WITHDRAWAL_TYPEHASH = keccak256(
"Withdrawal(address owner,uint32 accountID,uint16 tokenID,uint96 amount,uint16 feeTokenID,uint96 maxFee,address to,bytes extraData,uint256 minGas,uint32 validUntil,uint32 storageID)"
);
struct Withdrawal
{
uint withdrawalType;
address from;
uint32 fromAccountID;
uint16 tokenID;
uint96 amount;
uint16 feeTokenID;
uint96 maxFee;
uint96 fee;
address to;
bytes extraData;
uint minGas;
uint32 validUntil;
uint32 storageID;
bytes20 onchainDataHash;
}
// Auxiliary data for each withdrawal
struct WithdrawalAuxiliaryData
{
bool storeRecipient;
uint gasLimit;
bytes signature;
uint minGas;
address to;
bytes extraData;
uint96 maxFee;
uint32 validUntil;
}
function process(
ExchangeData.State storage S,
ExchangeData.BlockContext memory ctx,
bytes memory data,
uint offset,
bytes memory auxiliaryData
)
internal
{
Withdrawal memory withdrawal;
readTx(data, offset, withdrawal);
WithdrawalAuxiliaryData memory auxData = abi.decode(auxiliaryData, (WithdrawalAuxiliaryData));
// Validate the withdrawal data not directly part of the DA
bytes20 onchainDataHash = hashOnchainData(
auxData.minGas,
auxData.to,
auxData.extraData
);
// Only the 20 MSB are used, which is still 80-bit of security, which is more
// than enough, especially when combined with validUntil.
require(withdrawal.onchainDataHash == onchainDataHash, "INVALID_WITHDRAWAL_DATA");
// Fill in withdrawal data missing from DA
withdrawal.to = auxData.to;
withdrawal.minGas = auxData.minGas;
withdrawal.extraData = auxData.extraData;
withdrawal.maxFee = auxData.maxFee == 0 ? withdrawal.fee : auxData.maxFee;
withdrawal.validUntil = auxData.validUntil;
// If the account has an owner, don't allow withdrawing to the zero address
// (which will be the protocol fee vault contract).
require(withdrawal.from == address(0) || withdrawal.to != address(0), "INVALID_WITHDRAWAL_RECIPIENT");
if (withdrawal.withdrawalType == 0) {
// Signature checked offchain, nothing to do
} else if (withdrawal.withdrawalType == 1) {
// Validate
require(ctx.timestamp < withdrawal.validUntil, "WITHDRAWAL_EXPIRED");
require(withdrawal.fee <= withdrawal.maxFee, "WITHDRAWAL_FEE_TOO_HIGH");
// Check appproval onchain
// Calculate the tx hash
bytes32 txHash = hashTx(ctx.DOMAIN_SEPARATOR, withdrawal);
// Check onchain authorization
S.requireAuthorizedTx(withdrawal.from, auxData.signature, txHash);
} else if (withdrawal.withdrawalType == 2 || withdrawal.withdrawalType == 3) {
// Forced withdrawals cannot make use of certain features because the
// necessary data is not authorized by the account owner.
// For protocol fee withdrawals, `owner` and `to` are both address(0).
require(withdrawal.from == withdrawal.to, "INVALID_WITHDRAWAL_ADDRESS");
// Forced withdrawal fees are charged when the request is submitted.
require(withdrawal.fee == 0, "FEE_NOT_ZERO");
require(withdrawal.extraData.length == 0, "AUXILIARY_DATA_NOT_ALLOWED");
ExchangeData.ForcedWithdrawal memory forcedWithdrawal =
S.pendingForcedWithdrawals[withdrawal.fromAccountID][withdrawal.tokenID];
if (forcedWithdrawal.timestamp != 0) {
if (withdrawal.withdrawalType == 2) {
require(withdrawal.from == forcedWithdrawal.owner, "INCONSISENT_OWNER");
} else { //withdrawal.withdrawalType == 3
require(withdrawal.from != forcedWithdrawal.owner, "INCONSISENT_OWNER");
require(withdrawal.amount == 0, "UNAUTHORIZED_WITHDRAWAL");
}
// delete the withdrawal request and free a slot
delete S.pendingForcedWithdrawals[withdrawal.fromAccountID][withdrawal.tokenID];
S.numPendingForcedTransactions--;
} else {
// Allow the owner to submit full withdrawals without authorization
// - when in shutdown mode
// - to withdraw protocol fees
require(
withdrawal.fromAccountID == ExchangeData.ACCOUNTID_PROTOCOLFEE ||
S.isShutdown(),
"FULL_WITHDRAWAL_UNAUTHORIZED"
);
}
} else {
revert("INVALID_WITHDRAWAL_TYPE");
}
// Check if there is a withdrawal recipient
address recipient = S.withdrawalRecipient[withdrawal.from][withdrawal.to][withdrawal.tokenID][withdrawal.amount][withdrawal.storageID];
if (recipient != address(0)) {
// Auxiliary data is not supported
require (withdrawal.extraData.length == 0, "AUXILIARY_DATA_NOT_ALLOWED");
// Set the new recipient address
withdrawal.to = recipient;
// Allow any amount of gas to be used on this withdrawal (which allows the transfer to be skipped)
withdrawal.minGas = 0;
// Do NOT delete the recipient to prevent replay attack
// delete S.withdrawalRecipient[withdrawal.owner][withdrawal.to][withdrawal.tokenID][withdrawal.amount][withdrawal.storageID];
} else if (auxData.storeRecipient) {
// Store the destination address to mark the withdrawal as done
require(withdrawal.to != address(0), "INVALID_DESTINATION_ADDRESS");
S.withdrawalRecipient[withdrawal.from][withdrawal.to][withdrawal.tokenID][withdrawal.amount][withdrawal.storageID] = withdrawal.to;
}
// Validate gas provided
require(auxData.gasLimit >= withdrawal.minGas, "OUT_OF_GAS_FOR_WITHDRAWAL");
// Try to transfer the tokens with the provided gas limit
S.distributeWithdrawal(
withdrawal.from,
withdrawal.to,
withdrawal.tokenID,
withdrawal.amount,
withdrawal.extraData,
auxData.gasLimit
);
}
function readTx(
bytes memory data,
uint offset,
Withdrawal memory withdrawal
)
internal
pure
{
uint _offset = offset;
require(data.toUint8Unsafe(_offset) == uint8(ExchangeData.TransactionType.WITHDRAWAL), "INVALID_TX_TYPE");
_offset += 1;
// Extract the transfer data
// We don't use abi.decode for this because of the large amount of zero-padding
// bytes the circuit would also have to hash.
withdrawal.withdrawalType = data.toUint8Unsafe(_offset);
_offset += 1;
withdrawal.from = data.toAddressUnsafe(_offset);
_offset += 20;
withdrawal.fromAccountID = data.toUint32Unsafe(_offset);
_offset += 4;
withdrawal.tokenID = data.toUint16Unsafe(_offset);
_offset += 2;
withdrawal.amount = data.toUint96Unsafe(_offset);
_offset += 12;
withdrawal.feeTokenID = data.toUint16Unsafe(_offset);
_offset += 2;
withdrawal.fee = data.toUint16Unsafe(_offset).decodeFloat16();
_offset += 2;
withdrawal.storageID = data.toUint32Unsafe(_offset);
_offset += 4;
withdrawal.onchainDataHash = data.toBytes20Unsafe(_offset);
_offset += 20;
}
function hashTx(
bytes32 DOMAIN_SEPARATOR,
Withdrawal memory withdrawal
)
internal
pure
returns (bytes32)
{
return EIP712.hashPacked(
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
WITHDRAWAL_TYPEHASH,
withdrawal.from,
withdrawal.fromAccountID,
withdrawal.tokenID,
withdrawal.amount,
withdrawal.feeTokenID,
withdrawal.maxFee,
withdrawal.to,
keccak256(withdrawal.extraData),
withdrawal.minGas,
withdrawal.validUntil,
withdrawal.storageID
)
)
);
}
function hashOnchainData(
uint minGas,
address to,
bytes memory extraData
)
internal
pure
returns (bytes20)
{
// Only the 20 MSB are used, which is still 80-bit of security, which is more
// than enough, especially when combined with validUntil.
return bytes20(keccak256(
abi.encodePacked(
minGas,
to,
extraData
)
));
}
}
// File: contracts/core/impl/libexchange/ExchangeBlocks.sol
// Copyright 2017 Loopring Technology Limited.
/// @title ExchangeBlocks.
/// @author Brecht Devos - <brecht@loopring.org>
/// @author Daniel Wang - <daniel@loopring.org>
library ExchangeBlocks
{
using AddressUtil for address;
using AddressUtil for address payable;
using BlockReader for bytes;
using BytesUtil for bytes;
using MathUint for uint;
using ExchangeMode for ExchangeData.State;
using ExchangeWithdrawals for ExchangeData.State;
using SignatureUtil for bytes32;
event BlockSubmitted(
uint indexed blockIdx,
bytes32 merkleRoot,
bytes32 publicDataHash
);
event ProtocolFeesUpdated(
uint8 takerFeeBips,
uint8 makerFeeBips,
uint8 previousTakerFeeBips,
uint8 previousMakerFeeBips
);
function submitBlocks(
ExchangeData.State storage S,
ExchangeData.Block[] memory blocks
)
public
{
// Exchange cannot be in withdrawal mode
require(!S.isInWithdrawalMode(), "INVALID_MODE");
// Commit the blocks
bytes32[] memory publicDataHashes = new bytes32[](blocks.length);
for (uint i = 0; i < blocks.length; i++) {
// Hash all the public data to a single value which is used as the input for the circuit
publicDataHashes[i] = blocks[i].data.fastSHA256();
// Commit the block
commitBlock(S, blocks[i], publicDataHashes[i]);
}
// Verify the blocks - blocks are verified in a batch to save gas.
verifyBlocks(S, blocks, publicDataHashes);
}
// == Internal Functions ==
function commitBlock(
ExchangeData.State storage S,
ExchangeData.Block memory _block,
bytes32 _publicDataHash
)
private
{
// Read the block header
BlockReader.BlockHeader memory header = _block.data.readHeader();
// Validate the exchange
require(header.exchange == address(this), "INVALID_EXCHANGE");
// Validate the Merkle roots
require(header.merkleRootBefore == S.merkleRoot, "INVALID_MERKLE_ROOT");
require(header.merkleRootAfter != header.merkleRootBefore, "EMPTY_BLOCK_DISABLED");
require(uint(header.merkleRootAfter) < ExchangeData.SNARK_SCALAR_FIELD, "INVALID_MERKLE_ROOT");
// Validate the timestamp
require(
header.timestamp > block.timestamp - ExchangeData.TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS &&
header.timestamp < block.timestamp + ExchangeData.TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS,
"INVALID_TIMESTAMP"
);
// Validate the protocol fee values
require(
validateAndSyncProtocolFees(S, header.protocolTakerFeeBips, header.protocolMakerFeeBips),
"INVALID_PROTOCOL_FEES"
);
// Process conditional transactions
processConditionalTransactions(
S,
_block,
header
);
// Emit an event
uint numBlocks = S.numBlocks;
emit BlockSubmitted(numBlocks, header.merkleRootAfter, _publicDataHash);
S.merkleRoot = header.merkleRootAfter;
if (_block.storeBlockInfoOnchain) {
S.blocks[numBlocks] = ExchangeData.BlockInfo(
uint32(block.timestamp),
bytes28(_publicDataHash)
);
}
S.numBlocks = numBlocks + 1;
}
function verifyBlocks(
ExchangeData.State storage S,
ExchangeData.Block[] memory blocks,
bytes32[] memory publicDataHashes
)
private
view
{
IBlockVerifier blockVerifier = S.blockVerifier;
uint numBlocksVerified = 0;
bool[] memory blockVerified = new bool[](blocks.length);
ExchangeData.Block memory firstBlock;
uint[] memory batch = new uint[](blocks.length);
while (numBlocksVerified < blocks.length) {
// Find all blocks of the same type
uint batchLength = 0;
for (uint i = 0; i < blocks.length; i++) {
if (blockVerified[i] == false) {
if (batchLength == 0) {
firstBlock = blocks[i];
batch[batchLength++] = i;
} else {
ExchangeData.Block memory _block = blocks[i];
if (_block.blockType == firstBlock.blockType &&
_block.blockSize == firstBlock.blockSize &&
_block.blockVersion == firstBlock.blockVersion) {
batch[batchLength++] = i;
}
}
}
}
// Prepare the data for batch verification
uint[] memory publicInputs = new uint[](batchLength);
uint[] memory proofs = new uint[](batchLength * 8);
for (uint i = 0; i < batchLength; i++) {
uint blockIdx = batch[i];
// Mark the block as verified
blockVerified[blockIdx] = true;
// Strip the 3 least significant bits of the public data hash
// so we don't have any overflow in the snark field
publicInputs[i] = uint(publicDataHashes[blockIdx]) >> 3;
// Copy proof
ExchangeData.Block memory _block = blocks[blockIdx];
for (uint j = 0; j < 8; j++) {
proofs[i*8 + j] = _block.proof[j];
}
}
// Verify the proofs
require(
blockVerifier.verifyProofs(
uint8(firstBlock.blockType),
firstBlock.blockSize,
firstBlock.blockVersion,
publicInputs,
proofs
),
"INVALID_PROOF"
);
numBlocksVerified += batchLength;
}
}
function processConditionalTransactions(
ExchangeData.State storage S,
ExchangeData.Block memory _block,
BlockReader.BlockHeader memory header
)
private
{
if (header.numConditionalTransactions > 0) {
// Cache the domain seperator to save on SLOADs each time it is accessed.
ExchangeData.BlockContext memory ctx = ExchangeData.BlockContext({
DOMAIN_SEPARATOR: S.DOMAIN_SEPARATOR,
timestamp: header.timestamp
});
ExchangeData.AuxiliaryData[] memory block_auxiliaryData;
bytes memory blockAuxData = _block.auxiliaryData;
assembly {
block_auxiliaryData := add(blockAuxData, 64)
}
require(
block_auxiliaryData.length == header.numConditionalTransactions,
"AUXILIARYDATA_INVALID_LENGTH"
);
// Run over all conditional transactions
uint minTxIndex = 0;
bytes memory txData = new bytes(ExchangeData.TX_DATA_AVAILABILITY_SIZE);
for (uint i = 0; i < block_auxiliaryData.length; i++) {
// Load the data from auxiliaryData, which is still encoded as calldata
uint txIndex;
bool approved;
bytes memory auxData;
assembly {
// Offset to block_auxiliaryData[i]
let auxOffset := mload(add(block_auxiliaryData, add(32, mul(32, i))))
// Load `txIndex` (pos 0) and `approved` (pos 1) in block_auxiliaryData[i]
txIndex := mload(add(add(32, block_auxiliaryData), auxOffset))
approved := mload(add(add(64, block_auxiliaryData), auxOffset))
// Load `data` (pos 2)
let auxDataOffset := mload(add(add(96, block_auxiliaryData), auxOffset))
auxData := add(add(32, block_auxiliaryData), add(auxOffset, auxDataOffset))
}
// Each conditional transaction needs to be processed from left to right
require(txIndex >= minTxIndex, "AUXILIARYDATA_INVALID_ORDER");
minTxIndex = txIndex + 1;
if (approved) {
continue;
}
// Get the transaction data
_block.data.readTransactionData(txIndex, _block.blockSize, txData);
// Process the transaction
ExchangeData.TransactionType txType = ExchangeData.TransactionType(
txData.toUint8(0)
);
uint txDataOffset = 0;
if (txType == ExchangeData.TransactionType.DEPOSIT) {
DepositTransaction.process(
S,
ctx,
txData,
txDataOffset,
auxData
);
} else if (txType == ExchangeData.TransactionType.WITHDRAWAL) {
WithdrawTransaction.process(
S,
ctx,
txData,
txDataOffset,
auxData
);
} else if (txType == ExchangeData.TransactionType.TRANSFER) {
TransferTransaction.process(
S,
ctx,
txData,
txDataOffset,
auxData
);
} else if (txType == ExchangeData.TransactionType.ACCOUNT_UPDATE) {
AccountUpdateTransaction.process(
S,
ctx,
txData,
txDataOffset,
auxData
);
} else if (txType == ExchangeData.TransactionType.AMM_UPDATE) {
AmmUpdateTransaction.process(
S,
ctx,
txData,
txDataOffset,
auxData
);
} else {
// ExchangeData.TransactionType.NOOP,
// ExchangeData.TransactionType.SPOT_TRADE and
// ExchangeData.TransactionType.SIGNATURE_VERIFICATION
// are not supported
revert("UNSUPPORTED_TX_TYPE");
}
}
}
}
function validateAndSyncProtocolFees(
ExchangeData.State storage S,
uint8 takerFeeBips,
uint8 makerFeeBips
)
private
returns (bool)
{
ExchangeData.ProtocolFeeData memory data = S.protocolFeeData;
if (block.timestamp > data.syncedAt + ExchangeData.MIN_AGE_PROTOCOL_FEES_UNTIL_UPDATED) {
// Store the current protocol fees in the previous protocol fees
data.previousTakerFeeBips = data.takerFeeBips;
data.previousMakerFeeBips = data.makerFeeBips;
// Get the latest protocol fees for this exchange
(data.takerFeeBips, data.makerFeeBips) = S.loopring.getProtocolFeeValues();
data.syncedAt = uint32(block.timestamp);
if (data.takerFeeBips != data.previousTakerFeeBips ||
data.makerFeeBips != data.previousMakerFeeBips) {
emit ProtocolFeesUpdated(
data.takerFeeBips,
data.makerFeeBips,
data.previousTakerFeeBips,
data.previousMakerFeeBips
);
}
// Update the data in storage
S.protocolFeeData = data;
}
// The given fee values are valid if they are the current or previous protocol fee values
return (takerFeeBips == data.takerFeeBips && makerFeeBips == data.makerFeeBips) ||
(takerFeeBips == data.previousTakerFeeBips && makerFeeBips == data.previousMakerFeeBips);
}
}
|
Limit the amount of pending forced withdrawals so that the owner cannot be overwhelmed. A user needs to pay a fixed ETH withdrawal fee, set by the protocol. Check ETH value sent, can be larger than the expected withdraw fee Send surplus of ETH back to the sender Store the forced withdrawal request data
|
function forceWithdraw(
ExchangeData.State storage S,
address owner,
address token,
uint32 accountID
)
public
{
require(!S.isInWithdrawalMode(), "INVALID_MODE");
require(S.getNumAvailableForcedSlots() > 0, "TOO_MANY_REQUESTS_OPEN");
require(accountID < ExchangeData.MAX_NUM_ACCOUNTS, "INVALID_ACCOUNTID");
uint16 tokenID = S.getTokenID(token);
uint withdrawalFeeETH = S.loopring.forcedWithdrawalFee();
require(msg.value >= withdrawalFeeETH, "INSUFFICIENT_FEE");
uint feeSurplus = msg.value.sub(withdrawalFeeETH);
if (feeSurplus > 0) {
msg.sender.sendETHAndVerify(feeSurplus, gasleft());
}
S.pendingForcedWithdrawals[accountID][tokenID].timestamp == 0,
"WITHDRAWAL_ALREADY_PENDING"
);
S.pendingForcedWithdrawals[accountID][tokenID] = ExchangeData.ForcedWithdrawal({
owner: owner,
timestamp: uint64(block.timestamp)
});
emit ForcedWithdrawalRequested(
owner,
token,
accountID
);
}
| 334,423
|
//SPDX-License-Identifier: MIT
pragma solidity 0.7.3;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title bloXmove Cliffing and Vesting Contract.
*/
contract BloXmoveVesting is Ownable {
using SafeMath for uint256;
using SafeMath for uint16;
// The ERC20 bloXmove token
IERC20 public immutable bloXmoveToken;
// The allowed total amount of all grants (currently estimated 49000000 tokens).
uint256 public immutable totalAmountOfGrants;
// The current total amount of added grants.
uint256 public storedAddedAmount = 0;
struct Grant {
address beneficiary;
uint16 vestingDuration; // in days
uint16 daysClaimed;
uint256 vestingStartTime;
uint256 amount;
uint256 totalClaimed;
}
// The start time of all Grants.
// starttime + cliffing time of Grant = starttime of vesting
uint256 public immutable startTime;
mapping(address => Grant) private tokenGrants;
event GrantAdded(address indexed beneficiary);
event GrantTokensClaimed(
address indexed beneficiary,
uint256 amountClaimed
);
/**
* @dev Constructor to set the address of the token contract
* and the start time (timestamp in seconds).
*/
constructor(
address _bloXmoveToken,
address _grantManagerAddr,
uint256 _totalAmountOfGrants,
uint256 _startTime
) {
transferOwnership(_grantManagerAddr);
bloXmoveToken = IERC20(_bloXmoveToken);
totalAmountOfGrants = _totalAmountOfGrants;
startTime = _startTime;
}
/**
* @dev Not supported receive function.
*/
receive() external payable {
revert("Not supported receive function");
}
/**
* @dev Not supported fallback function.
*/
fallback() external payable {
revert("Not supported fallback function");
}
/**
* @dev Add Token Grant for the beneficiary.
* @param _beneficiary the address of the account receiving the grant
* @param _amount the amount (in 1/18 token) of the grant
* @param _vestingDurationInDays the vesting period of the grant in days
* @param _vestingCliffInDays the cliff period of the grant in days
*
* Emits a {GrantAdded} event indicating the beneficiary address.
*
* Requirements:
*
* - The msg.sender is the owner of the contract.
* - The beneficiary has no other Grants.
* - The given grant amount + other added grants is smaller or equal to the totalAmountOfGrants
* - The amount vested per day (amount/vestingDurationInDays) is bigger than 0.
* - The requirement described in function {calculateGrantClaim} for msg.sender.
* - The contract can transfer token on behalf of the owner of the contract.
*/
function addTokenGrant(
address _beneficiary,
uint256 _amount,
uint16 _vestingDurationInDays,
uint16 _vestingCliffInDays
) external onlyOwner {
require(tokenGrants[_beneficiary].amount == 0, "Grant already exists!");
storedAddedAmount = storedAddedAmount.add(_amount);
require(
storedAddedAmount <= totalAmountOfGrants,
"Amount exceeds grants balance!"
);
uint256 amountVestedPerDay = _amount.div(_vestingDurationInDays);
require(amountVestedPerDay > 0, "amountVestedPerDay is 0");
require(
bloXmoveToken.transferFrom(owner(), address(this), _amount),
"transferFrom Error"
);
Grant memory grant = Grant({
vestingStartTime: startTime + _vestingCliffInDays * 1 days,
amount: _amount,
vestingDuration: _vestingDurationInDays,
daysClaimed: 0,
totalClaimed: 0,
beneficiary: _beneficiary
});
tokenGrants[_beneficiary] = grant;
emit GrantAdded(_beneficiary);
}
/**
* @dev Claim the available vested tokens.
*
* This function is called by the beneficiaries to claim their vested tokens.
*
* Emits a {GrantTokensClaimed} event indicating the beneficiary address and
* the claimed amount.
*
* Requirements:
*
* - The vested amount to claim is bigger than 0
* - The requirement described in function {calculateGrantClaim} for msg.sender
* - The contract can transfer tokens to the beneficiary
*/
function claimVestedTokens() external {
uint16 daysVested;
uint256 amountVested;
(daysVested, amountVested) = calculateGrantClaim(_msgSender());
require(amountVested > 0, "Vested is 0");
Grant storage tokenGrant = tokenGrants[_msgSender()];
tokenGrant.daysClaimed = uint16(tokenGrant.daysClaimed.add(daysVested));
tokenGrant.totalClaimed = uint256(
tokenGrant.totalClaimed.add(amountVested)
);
require(
bloXmoveToken.transfer(tokenGrant.beneficiary, amountVested),
"no tokens"
);
emit GrantTokensClaimed(tokenGrant.beneficiary, amountVested);
}
/**
* @dev calculate the days and the amount vested for a particular claim.
*
* Requirements:
*
* - The Grant ist not fully claimed
* - The current time is bigger than the starttime.
*
* @return a tuple of days vested and amount of vested tokens.
*/
function calculateGrantClaim(address _beneficiary)
private
view
returns (uint16, uint256)
{
Grant storage tokenGrant = tokenGrants[_beneficiary];
require(tokenGrant.amount > 0, "no Grant");
require(
tokenGrant.totalClaimed < tokenGrant.amount,
"Grant fully claimed"
);
// Check cliffing duration
if (currentTime() < tokenGrant.vestingStartTime) {
return (0, 0);
}
uint256 elapsedDays = currentTime()
.sub(tokenGrant.vestingStartTime - 1 days)
.div(1 days);
// If over vesting duration, all tokens vested
if (elapsedDays >= tokenGrant.vestingDuration) {
// solve the uneven vest issue that could accure
uint256 remainingGrant = tokenGrant.amount.sub(
tokenGrant.totalClaimed
);
return (tokenGrant.vestingDuration, remainingGrant);
} else {
uint16 daysVested = uint16(elapsedDays.sub(tokenGrant.daysClaimed));
uint256 amountVestedPerDay = tokenGrant.amount.div(
uint256(tokenGrant.vestingDuration)
);
uint256 amountVested = uint256(daysVested.mul(amountVestedPerDay));
return (daysVested, amountVested);
}
}
/**
* @dev Get the amount of tokens that are currently available to claim for a given beneficiary.
* Reverts if there is no grant for the beneficiary.
*
* @return the amount of tokens that are currently available to claim, 0 if fully claimed.
*/
function getCurrentAmountToClaim(address _beneficiary)
public
view
returns (uint256)
{
Grant storage tokenGrant = tokenGrants[_beneficiary];
require(tokenGrant.amount > 0, "no Grant");
if (tokenGrant.totalClaimed == tokenGrant.amount) {
return 0;
}
uint256 amountVested;
(, amountVested) = calculateGrantClaim(_beneficiary);
return amountVested;
}
/**
* @dev Get the remaining grant amount for a given beneficiary.
* @return the remaining grant amount.
*/
function getRemainingGrant(address _beneficiary)
public
view
returns (uint256)
{
Grant storage tokenGrant = tokenGrants[_beneficiary];
return tokenGrant.amount.sub(tokenGrant.totalClaimed);
}
/**
* @dev Get the vesting start time for a given beneficiary.
* @return the start time.
*/
function getVestingStartTime(address _beneficiary)
public
view
returns (uint256)
{
Grant storage tokenGrant = tokenGrants[_beneficiary];
return tokenGrant.vestingStartTime;
}
/**
* @dev Get the grant amount for a given beneficiary.
* @return the grant amount.
*/
function getGrantAmount(address _beneficiary)
public
view
returns (uint256)
{
Grant storage tokenGrant = tokenGrants[_beneficiary];
return tokenGrant.amount;
}
/**
* @dev Get the timestamp from the block set by the miners.
* @return the current timestamp of the block.
*/
function currentTime() private view returns (uint256) {
return block.timestamp; // solhint-disable-line
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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 () {
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
pragma solidity ^0.7.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: 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: 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;
}
}
|
Get the timestamp from the block set by the miners. return the current timestamp of the block./
|
function currentTime() private view returns (uint256) {
}
| 322,003
|
./full_match/56/0x5B99e0893225178dBf4Ffe9FfD2142a21E8d1087/sources/src/strategies/CTokenBaseStrategy.sol
|
Returns the current banana balance of the strategy contract.
|
function _currentBananaBalance() internal view returns (uint256) {
return compToken.balanceOf(address(this));
}
| 3,226,470
|
./partial_match/1/0xf6C8Ee885dAB34025cA275e269f8EC4BD85aD7FB/sources/contracts/interfaces/IPromissoryNote.sol
|
Getter for mapping: mapping(uint256 => uint256) public loanIdByNoteId;
|
interface IPromissoryNote is IERC721 {
function loanIdByNoteId(uint256 noteId) external view returns (uint256);
function mint(address to, uint256 loanId) external returns (uint256);
function burn(uint256 tokenId) external;
}
| 4,366,384
|
./partial_match/3/0xAAa655f350eF27981dcDfC2B82d3DA52D8D1cf45/sources/Governance.sol
|
get the current status for the proposal./
|
function getStatus(bytes32 proposeId)
external
view
override
returns (
uint128 appliedMinimumVote,
uint128 currentApprovalVoteSum,
uint128 currentDenialVoteSum,
uint32 prevoteDeadline,
uint32 mainvoteDeadline,
uint32 expiration,
bool lockin,
bool applied
)
{
prevoteDeadline = _proposeStatus[proposeId].prevoteDeadline;
mainvoteDeadline = _proposeStatus[proposeId].mainvoteDeadline;
expiration = _proposeStatus[proposeId].expiration;
appliedMinimumVote = _proposeStatus[proposeId].appliedMinimumVote;
currentApprovalVoteSum = _proposeStatus[proposeId].currentApprovalVoteSum;
currentDenialVoteSum = _proposeStatus[proposeId].currentDenialVoteSum;
lockin = _proposeStatus[proposeId].lockin;
applied = _proposeStatus[proposeId].applied;
}
| 5,230,205
|
pragma solidity ^0.4.22;
import './mortal.sol';
import './SafeMath.sol';
import './CNV.sol';
import './OraculoPrecio.sol';
contract ContratoSAS is mortal {
using SafeMath for uint;
CNV cnv;
OraculoPrecio oraculo_precio;
/* Events */
event contributionFiled(address indexed from, uint indexed uid, uint amount);
event receivedFunds(address _from, uint _amount);
event fundReturned(address _to, uint _amount);
event beneficiarioSet(address beneficiario);
event cantAccionesSet(uint cant_acciones);
event Transfer(address indexed from, address indexed to, uint tokens);
event symbolSet(string symbol);
event urlSet(string url);
event nombreSet(string nombre);
event montoSet(uint monto);
event montoMaxSet(uint monto_max);
event fechaSet(uint fecha_fin);
event descripcionSet(string descripcion);
event cuitSet(uint cuit);
/* event uidSet(uint uid); */
struct Contribution {
address _from;
uint _uid;
uint _amount;
}
uint public m_total_supply; // ERC 20
uint public m_decimals; // ERC 20
string public m_symbol; // ERC 20
uint public contribution_counter;
address public m_beneficiario;
string public m_url;
string public m_nombre; // ERC 20
uint public m_monto; // Monto en centavos
uint public m_monto_max; // Monto en centavos
uint public m_fecha_fin;
uint public m_fecha_cierre;
string public m_descripcion;
uint public m_cuit;
bool public m_project_valid;
bool public m_beneficiary_valid;
bool public m_closed_round;
/* uint public m_uid; */
mapping(uint => Contribution) m_contributions;
mapping(address => uint) balances;
/* constructor() public {
m_decimals = 18;
contribution_counter = 0;
m_project_valid = false;
m_beneficiary_valid = false;
m_closed_round = false;
} */
constructor(address cnv_addr, address oraculo_precio_addr, address beneficiario, uint cant_acciones, string symbol, uint monto, uint monto_max, uint fecha_fin) payable public {
m_decimals = 18;
contribution_counter = 0;
m_project_valid = false;
m_beneficiary_valid = false;
m_closed_round = false;
///
cnv = CNV(cnv_addr);
oraculo_precio = OraculoPrecio(oraculo_precio_addr);
///
m_beneficiario = beneficiario;
emit beneficiarioSet(m_beneficiario);
m_total_supply = cant_acciones * 10**uint(m_decimals);
balances[owner] = m_total_supply; // Sets all the tokens in the owners balance
emit cantAccionesSet(m_total_supply);
m_symbol = symbol;
emit symbolSet(symbol);
m_monto = monto;
emit montoSet(m_monto);
m_monto_max = monto_max;
emit montoMaxSet(m_monto_max);
m_fecha_fin = fecha_fin;
emit fechaSet(m_fecha_fin);
}
/* constructor(address beneficiario, string url, string nombre, uint monto, uint monto_max, string fecha, string descripcion, uint cuit) public {
contribution_counter = 0;
m_beneficiario = beneficiario;
m_url = url;
m_nombre = nombre;
m_monto = monto;
m_monto_max = monto_max;
m_fecha_fin = fecha;
m_descripcion = descripcion;
m_cuit = cuit;
m_project_valid = false;
m_beneficiary_valid = false;
} */
function appendUintToString(string inStr, uint v) private pure returns (string str) {
uint maxlength = 100;
bytes memory reversed = new bytes(maxlength);
uint i = 0;
while (v != 0) {
uint remainder = v % 10;
v = v / 10;
reversed[i++] = byte(48 + remainder);
}
bytes memory inStrb = bytes(inStr);
bytes memory s = new bytes(inStrb.length + i);
uint j;
for (j = 0; j < inStrb.length; j++) {
s[j] = inStrb[j];
}
for (j = 0; j < i; j++) {
s[j + inStrb.length] = reversed[i - 1 - j];
}
str = string(s);
}
function append(string a, string b) private pure returns (string str) {
return string(abi.encodePacked(a, b));
}
function appendFive(string a, string b, string c, string d, string e) private pure returns (string str) {
return string(abi.encodePacked(a, b, c, d, e));
}
function noSuperaMontoMax () private view returns (bool supera) {
uint balanceActual = address(this).balance;
uint precioOraculo = oraculo_precio.getPrecio();
uint weiMultiplier = 10**uint(m_decimals);
/* uint sumaBalanceMonto = uint(balanceActual + val); */ // Omitimos este paso pues solidity suma al balance el value del mensaje previo a la carga del cuerpo del método
/* uint divisionMontoPrecio = m_monto_max / precioOraculo; */
uint montoPrecioWei = m_monto_max * weiMultiplier / precioOraculo;
bool comparacion = balanceActual <= montoPrecioWei;
/* append(
appendUintToString("divisionMontoPrecio: ", divisionMontoPrecio),
" "
), */
/* if(comparacion){
require(false, append("Comparación VERDADERA --- ", appendFive(
append(appendUintToString("balanceActual: ", balanceActual), " "),
append(appendUintToString("precioOraculo: ", precioOraculo), " "),
append(appendUintToString("weiMultiplier: ", weiMultiplier), " "),
append(appendUintToString("m_monto_max: ", m_monto_max), " "),
append(appendUintToString("montoPrecioWei: ", montoPrecioWei), " ")
)
)
);
}
else{
require(false, append("Comparación FALSA --- ", appendFive(
append(appendUintToString("balanceActual: ", balanceActual), " "),
append(appendUintToString("precioOraculo: ", precioOraculo), " "),
append(appendUintToString("weiMultiplier: ", weiMultiplier), " "),
append(appendUintToString("m_monto_max: ", m_monto_max), " "),
append(appendUintToString("montoPrecioWei: ", montoPrecioWei), " ")
)
)
);
} */
/* if(comparacion){
require(false, append("Comparación VERDADERA --- ", append(appendUintToString("Balance actual: ", balanceActual), appendUintToString("Monto precio wei: ", montoPrecioWei))));
}
else{
require(false, append("Comparación FALSA --- ", append(appendUintToString("Balance actual: ", balanceActual), appendUintToString("Monto precio wei: ", montoPrecioWei))));
} */
return comparacion;
}
function receiveFunds(uint uid) payable public {
require(m_project_valid, "El proyecto debe ser validado por la CNV");
require(m_beneficiary_valid, "El beneficiario del proyecto debe ser validado por la CNV");
require(!m_closed_round, "La ronda debe estar abierta para poder contribuir.");
bool noSupera = bool(noSuperaMontoMax());
require(noSupera, "El monto del proyecto más el monto a tranferir supera el monto por supersuscripción.");
/* Receive amount */
if(msg.value > 0) {
emit receivedFunds(msg.sender, msg.value);
}
/* File contribution*/
contribution_counter++;
m_contributions[contribution_counter] = Contribution(msg.sender, uid, msg.value);
emit contributionFiled(msg.sender, uid, msg.value);
}
/*function getNombre() public returns (string) {
return m_nombre;
}*/
/* Setea el totalSupply de la SAS/proyecto */
function setSymbol(string symbol) onlyowner public {
m_symbol = symbol;
emit symbolSet(symbol);
}
/* Setea el totalSupply de la SAS/proyecto */
function setCantAcciones(uint cant) onlyowner public {
m_total_supply = cant * 10**uint(m_decimals);
balances[owner] = m_total_supply; // Sets all the tokens in the owners balance
emit cantAccionesSet(cant);
}
/* Setea el beneficiario de la SAS/proyecto */
function setBeneficiario(address beneficiario) onlyowner public {
m_beneficiario = beneficiario;
emit beneficiarioSet(m_beneficiario);
}
/* Setea el url de la SAS/proyecto */
function setUrl(string url) onlyowner public {
m_url = url;
emit urlSet(m_url);
}
/* Setea el nombre de la SAS/proyecto */
function setNombre(string nombre) onlyowner public {
m_nombre = nombre;
emit nombreSet(m_nombre);
}
/* Setea el monto de la SAS/proyecto */
function setMonto(uint monto) onlyowner public {
m_monto = monto;
emit montoSet(m_monto);
}
/* Setea el monto max de la SAS/proyecto */
function setMontoMax(uint monto_max) onlyowner public {
m_monto_max = monto_max;
emit montoMaxSet(m_monto_max);
}
/* Setea la fecha de la SAS/proyecto */
function setFecha(uint fecha_fin) onlyowner public {
m_fecha_fin = fecha_fin;
emit fechaSet(m_fecha_fin);
}
/* Setea la descripcion de la SAS/proyecto */
function setDescripcion(string descripcion) onlyowner public {
m_descripcion = descripcion;
emit descripcionSet(m_descripcion);
}
/* Setea el CUIT de la SAS/proyecto */
function setCuit(uint cuit) onlyowner public {
m_cuit = cuit;
emit cuitSet(m_cuit);
}
function setCNVAddress(address cnv_addr) onlyowner public {
cnv = CNV(cnv_addr);
}
function setProjectValidity() onlyowner public {
m_project_valid = cnv.isProjectValid(address(this));
/* m_project_valid = true; */
}
function setBeneficiaryValidity() onlyowner public {
m_beneficiary_valid = cnv.isBeneficiaryValid(m_beneficiario);
/* return m_beneficiary_valid; */
/* m_beneficiary_valid = true; */
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
require(m_closed_round, "No se pueden transferir tokens de un proyecto abierto.");
require(from == msg.sender, "Un usuario solo puede transferir sus propios tokens");
balances[from] = balances[from].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(owner, to, tokens);
return true;
}
function transfer(address to, uint tokens) public returns (bool success) {
require(m_closed_round, "No se pueden transferir tokens de un proyecto abierto.");
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function transferCloseRound(address to, uint tokens) private returns (bool success) {
balances[owner] = balances[owner].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(owner, to, tokens);
return true;
}
function balanceOf(address who) public view returns (uint balance) {
return balances[who];
}
function calculateTokens(uint _wei) private view returns (uint tokens) {
return _wei * m_total_supply / address(this).balance;
}
function closeRound() public returns (bool success) {
require(!m_closed_round, "La ronda debe seguir abierta para poder realizar el cierre.");
if(oraculo_precio.getPrecio() * address(this).balance / 10**uint(m_decimals) >= m_monto) { // Se alcanzó el monto esperado para el proyecto
for (uint i = 1; i <= contribution_counter; i++) { // Repartimos tokens a los holders
transferCloseRound(m_contributions[i]._from, calculateTokens(m_contributions[i]._amount)); // Los tokens los mandamos como el amount sin multiplicar por los decimales porque ya los estamos almacenando en wei al crear la contribución.
}
m_closed_round = true;
m_fecha_cierre = now;
} else if(now >= m_fecha_fin) { // Se alcanzó la fecha de cierre del proyecto y no se alcanzó el monto esperado
for (uint j = 1; j <= contribution_counter; j++) { // Devolvemos la plata a los holders y cerramos la ronda
m_contributions[j]._from.transfer(m_contributions[j]._amount); // En este caso, address.transfer es una llamada a transfer de solidity https://solidity.readthedocs.io/en/develop/units-and-global-variables.html#members-of-address-types
emit fundReturned(m_contributions[j]._from, m_contributions[j]._amount);
}
m_closed_round = true;
m_fecha_cierre = now;
}
return m_closed_round;
}
/* Setea el uid de la SAS/proyecto */
/* function setUid(uint uid) onlyowner public {
m_uid = uid;
emit uidSet(m_uid);
} */
/* TODO: Fill in function or get from frontend */
/*function getUserId() private returns (uint) {
return 1;
}*/
/* m_project_valid = cnv_addr.call(bytes4(keccak256("isProjectValid(address)")), address(this)); */
}
|
Setea el url de la SAS/proyecto /
|
function setUrl(string url) onlyowner public {
m_url = url;
emit urlSet(m_url);
}
| 12,782,692
|
./full_match/42161/0x2b99224DAD73d7D84b7C74E9161BbD0D01a2A15b/sources/contracts/multiinvoker/MultiInvoker.sol
|
Helper function to unwrap `amount` DSU into USDC and send to `receiver` receiver Address to receive the USDC amount Amount of DSU to unwrap/ If the batcher is 0 or doesn't have enough for this unwrap, go directly to the reserve Unwrap the DSU into USDC and return to the receiver
|
function _unwrap(address receiver, UFixed18 amount) private {
if (address(batcher) == address(0) || amount.gt(USDC.balanceOf(address(batcher)))) {
reserve.redeem(amount);
if (receiver != address(this)) USDC.push(receiver, amount);
batcher.unwrap(amount, receiver);
}
}
| 16,305,862
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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 () {
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
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.7.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));
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This is a modified implementation of OpenZeppelin's Ownable.sol.
* The modifications allow the contract to be inherited by a proxy's logic contract.
* Any owner-only functions on the base implementation will be unusable.
*
* By default, the owner account will be a null address which can be set by invoking
* a function with the `initializer` modifier. The owner 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. It also makes available the `initializer` modifier, which will set
* the owner to `msg.sender` the first time the function is invoked, and will
* revert if the owner has already been set.
*
* Note: This contract should only be inherited by proxy implementation contracts
* where the implementation will only ever be used as the logic address for proxies.
* The constructor permanently locks the owner of the implementation contract, but the
* owner of the proxies can be configured by the first caller.
*/
contract OwnableProxyImplementation {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() {
_owner = address(1);
emit OwnershipTransferred(address(0), address(1));
}
/**
* @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 == msg.sender, "!owner");
_;
}
/**
* @dev Initializes the contract setting `initialOwner` as the initial owner.
* Reverts if owner has already been set.
*/
modifier initializer(address initialOwner) {
require(_owner == address(0), "already initialized");
_owner = initialOwner;
emit OwnershipTransferred(address(0), initialOwner);
_;
}
/**
* @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 {
// Modified from OZ contract - sets owner to address(1) to prevent
// the initializer from being invoked after ownership is revoked.
emit OwnershipTransferred(_owner, address(1));
_owner = address(1);
}
/**
* @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.7.6;
interface IAdapterRegistry {
/* ========== Events ========== */
event ProtocolAdapterAdded(uint256 protocolId, address protocolAdapter);
event ProtocolAdapterRemoved(uint256 protocolId);
event TokenAdapterAdded(address adapter, uint256 protocolId, address underlying, address wrapper);
event TokenAdapterRemoved(address adapter, uint256 protocolId, address underlying, address wrapper);
event TokenSupportAdded(address underlying);
event TokenSupportRemoved(address underlying);
event VaultFactoryAdded(address factory);
event VaultFactoryRemoved(address factory);
event VaultAdded(address underlying, address vault);
event VaultRemoved(address underlying, address vault);
/* ========== Structs ========== */
struct TokenAdapter {
address adapter;
uint96 protocolId;
}
/* ========== Storage ========== */
function protocolsCount() external view returns (uint256);
function protocolAdapters(uint256 id) external view returns (address protocolAdapter);
function protocolAdapterIds(address protocolAdapter) external view returns (uint256 id);
function vaultsByUnderlying(address underlying) external view returns (address vault);
function approvedVaultFactories(address factory) external view returns (bool approved);
/* ========== Vault Factory Management ========== */
function addVaultFactory(address _factory) external;
function removeVaultFactory(address _factory) external;
/* ========== Vault Management ========== */
function addVault(address vault) external;
function removeVault(address vault) external;
/* ========== Protocol Adapter Management ========== */
function addProtocolAdapter(address protocolAdapter) external returns (uint256 id);
function removeProtocolAdapter(address protocolAdapter) external;
/* ========== Token Adapter Management ========== */
function addTokenAdapter(address adapter) external;
function addTokenAdapters(address[] calldata adapters) external;
function removeTokenAdapter(address adapter) external;
/* ========== Vault Queries ========== */
function getVaultsList() external view returns (address[] memory);
function haveVaultFor(address underlying) external view returns (bool);
/* ========== Protocol Queries ========== */
function getProtocolAdaptersAndIds() external view returns (address[] memory adapters, uint256[] memory ids);
function getProtocolMetadata(uint256 id) external view returns (address protocolAdapter, string memory name);
function getProtocolForTokenAdapter(address adapter) external view returns (address protocolAdapter);
/* ========== Supported Token Queries ========== */
function isSupported(address underlying) external view returns (bool);
function getSupportedTokens() external view returns (address[] memory list);
/* ========== Token Adapter Queries ========== */
function isApprovedAdapter(address adapter) external view returns (bool);
function getAdaptersList(address underlying) external view returns (address[] memory list);
function getAdapterForWrapperToken(address wrapperToken) external view returns (address);
function getAdaptersCount(address underlying) external view returns (uint256);
function getAdaptersSortedByAPR(address underlying)
external
view
returns (address[] memory adapters, uint256[] memory aprs);
function getAdaptersSortedByAPRWithDeposit(
address underlying,
uint256 deposit,
address excludingAdapter
)
external
view
returns (address[] memory adapters, uint256[] memory aprs);
function getAdapterWithHighestAPR(address underlying) external view returns (address adapter, uint256 apr);
function getAdapterWithHighestAPRForDeposit(
address underlying,
uint256 deposit,
address excludingAdapter
) external view returns (address adapter, uint256 apr);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
interface IERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
interface IERC20Metadata {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
interface IERC20MetadataBytes32 {
function name() external view returns (bytes32);
function symbol() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
pragma abicoder v2;
import "./IAdapterRegistry.sol";
import "./ITokenAdapter.sol";
import "./IRewardsSeller.sol";
interface INirnVault {
/* ========== Events ========== */
/** @dev Emitted when an adapter is removed and its balance fully withdrawn. */
event AdapterRemoved(IErc20Adapter adapter);
/** @dev Emitted when weights or adapters are updated. */
event AllocationsUpdated(IErc20Adapter[] adapters, uint256[] weights);
/** @dev Emitted when performance fees are claimed. */
event FeesClaimed(uint256 underlyingAmount, uint256 sharesMinted);
/** @dev Emitted when a rebalance happens without allocation changes. */
event Rebalanced();
/** @dev Emitted when max underlying is updated. */
event SetMaximumUnderlying(uint256 maxBalance);
/** @dev Emitted when fee recipient address is set. */
event SetFeeRecipient(address feeRecipient);
/** @dev Emitted when performance fee is set. */
event SetPerformanceFee(uint256 performanceFee);
/** @dev Emitted when reserve ratio is set. */
event SetReserveRatio(uint256 reserveRatio);
/** @dev Emitted when rewards seller contract is set. */
event SetRewardsSeller(address rewardsSeller);
/** @dev Emitted when a deposit is made. */
event Deposit(uint256 shares, uint256 underlying);
/** @dev Emitted when a deposit is made. */
event Withdrawal(uint256 shares, uint256 underlying);
/* ========== Structs ========== */
struct DistributionParameters {
IErc20Adapter[] adapters;
uint256[] weights;
uint256[] balances;
int256[] liquidityDeltas;
uint256 netAPR;
}
/* ========== Initializer ========== */
function initialize(
address _underlying,
address _rewardsSeller,
address _feeRecipient,
address _owner
) external;
/* ========== Config Queries ========== */
function minimumAPRImprovement() external view returns (uint256);
function registry() external view returns (IAdapterRegistry);
function eoaSafeCaller() external view returns (address);
function underlying() external view returns (address);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function feeRecipient() external view returns (address);
function rewardsSeller() external view returns (IRewardsSeller);
function lockedTokens(address) external view returns (bool);
function maximumUnderlying() external view returns (uint256);
function performanceFee() external view returns (uint64);
function reserveRatio() external view returns (uint64);
function priceAtLastFee() external view returns (uint128);
function minimumCompositionChangeDelay() external view returns (uint256);
function canChangeCompositionAfter() external view returns (uint96);
/* ========== Admin Actions ========== */
function setMaximumUnderlying(uint256 _maximumUnderlying) external;
function setPerformanceFee(uint64 _performanceFee) external;
function setFeeRecipient(address _feeRecipient) external;
function setRewardsSeller(IRewardsSeller _rewardsSeller) external;
function setReserveRatio(uint64 _reserveRatio) external;
/* ========== Balance Queries ========== */
function balance() external view returns (uint256 sum);
function reserveBalance() external view returns (uint256);
/* ========== Fee Queries ========== */
function getPendingFees() external view returns (uint256);
/* ========== Price Queries ========== */
function getPricePerFullShare() external view returns (uint256);
function getPricePerFullShareWithFee() external view returns (uint256);
/* ========== Reward Token Sales ========== */
function sellRewards(address rewardsToken, bytes calldata params) external;
/* ========== Adapter Queries ========== */
function getBalances() external view returns (uint256[] memory balances);
function getAdaptersAndWeights() external view returns (
IErc20Adapter[] memory adapters,
uint256[] memory weights
);
/* ========== Status Queries ========== */
function getCurrentLiquidityDeltas() external view returns (int256[] memory liquidityDeltas);
function getAPR() external view returns (uint256);
function currentDistribution() external view returns (
DistributionParameters memory params,
uint256 totalProductiveBalance,
uint256 _reserveBalance
);
/* ========== Deposit/Withdraw ========== */
function deposit(uint256 amount) external returns (uint256 shares);
function depositTo(uint256 amount, address to) external returns (uint256 shares);
function withdraw(uint256 shares) external returns (uint256 owed);
function withdrawUnderlying(uint256 amount) external returns (uint256 shares);
/* ========== Rebalance Actions ========== */
function rebalance() external;
function rebalanceWithNewWeights(uint256[] calldata proposedWeights) external;
function rebalanceWithNewAdapters(
IErc20Adapter[] calldata proposedAdapters,
uint256[] calldata proposedWeights
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
interface IRewardsSeller {
/**
* @dev Sell `rewardsToken` for `underlyingToken`.
* Should only be called after `rewardsToken` is transferred.
* @param sender - Address of account that initially triggered the call. Can be used to restrict who can trigger a sale.
* @param rewardsToken - Address of the token to sell.
* @param underlyingToken - Address of the token to buy.
* @param params - Any additional data that the caller provided.
*/
function sellRewards(
address sender,
address rewardsToken,
address underlyingToken,
bytes calldata params
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
interface IErc20Adapter {
/* ========== Metadata ========== */
function underlying() external view returns (address);
function token() external view returns (address);
function name() external view returns (string memory);
function availableLiquidity() external view returns (uint256);
/* ========== Conversion ========== */
function toUnderlyingAmount(uint256 tokenAmount) external view returns (uint256);
function toWrappedAmount(uint256 underlyingAmount) external view returns (uint256);
/* ========== Performance Queries ========== */
function getAPR() external view returns (uint256);
function getHypotheticalAPR(int256 liquidityDelta) external view returns (uint256);
function getRevenueBreakdown()
external
view
returns (
address[] memory assets,
uint256[] memory aprs
);
/* ========== Caller Balance Queries ========== */
function balanceWrapped() external view returns (uint256);
function balanceUnderlying() external view returns (uint256);
/* ========== Interactions ========== */
function deposit(uint256 amountUnderlying) external returns (uint256 amountMinted);
function withdraw(uint256 amountToken) external returns (uint256 amountReceived);
function withdrawAll() external returns (uint256 amountReceived);
function withdrawUnderlying(uint256 amountUnderlying) external returns (uint256 amountBurned);
function withdrawUnderlyingUpTo(uint256 amountUnderlying) external returns (uint256 amountReceived);
}
interface IEtherAdapter is IErc20Adapter {
function depositETH() external payable returns (uint256 amountMinted);
function withdrawAsETH(uint256 amountToken) external returns (uint256 amountReceived);
function withdrawAllAsETH() external returns (uint256 amountReceived);
function withdrawUnderlyingAsETH(uint256 amountUnderlying) external returns (uint256 amountBurned);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "../interfaces/IAdapterRegistry.sol";
import "../interfaces/ITokenAdapter.sol";
import "../interfaces/IERC20.sol";
import "../libraries/LowGasSafeMath.sol";
import "../libraries/MinimalSignedMath.sol";
import "../libraries/ArrayHelper.sol";
import "../libraries/DynamicArrays.sol";
import "../libraries/Fraction.sol";
import "../libraries/SafeCast.sol";
library AdapterHelper {
using Fraction for uint256;
using LowGasSafeMath for uint256;
using MinimalSignedMath for int256;
using SafeCast for uint256;
using SafeCast for int256;
using ArrayHelper for address[];
using ArrayHelper for uint256[];
using DynamicArrays for uint256[];
function packAdapterAndWeight(
IErc20Adapter adapter,
uint256 weight
)
internal
pure
returns (bytes32 encoded)
{
assembly {
encoded := or(shl(96, adapter), weight)
}
}
function packAdaptersAndWeights(
IErc20Adapter[] memory adapters,
uint256[] memory weights
)
internal
pure
returns (bytes32[] memory encodedArray)
{
uint256 len = adapters.length;
encodedArray = new bytes32[](len);
for (uint256 i; i < len; i++) {
IErc20Adapter adapter = adapters[i];
uint256 weight = weights[i];
bytes32 encoded;
assembly {
encoded := or(shl(96, adapter), weight)
}
encodedArray[i] = encoded;
}
}
function unpackAdapterAndWeight(bytes32 encoded)
internal
pure
returns (
IErc20Adapter adapter,
uint256 weight
)
{
assembly {
adapter := shr(96, encoded)
weight := and(
encoded,
0x0000000000000000000000000000000000000000ffffffffffffffffffffffff
)
}
}
function unpackAdaptersAndWeights(bytes32[] memory encodedArray)
internal
pure
returns (
IErc20Adapter[] memory adapters,
uint256[] memory weights
)
{
uint256 len = encodedArray.length;
adapters = new IErc20Adapter[](len);
weights = new uint256[](len);
for (uint256 i; i < len; i++) {
bytes32 encoded = encodedArray[i];
IErc20Adapter adapter;
uint256 weight;
assembly {
adapter := shr(96, encoded)
weight := and(
encoded,
0x0000000000000000000000000000000000000000ffffffffffffffffffffffff
)
}
adapters[i] = adapter;
weights[i] = weight;
}
}
function getNetAPR(
IErc20Adapter[] memory adapters,
uint256[] memory weights,
int256[] memory liquidityDeltas
) internal view returns (uint256 netAPR) {
uint256 len = adapters.length;
for (uint256 i; i < len; i++) {
uint256 weight = weights[i];
if (weight > 0) {
netAPR = netAPR.add(
adapters[i].getHypotheticalAPR(liquidityDeltas[i]).mulFractionE18(weight)
);
}
}
}
function getLiquidityDeltas(
uint256 totalProductiveBalance,
uint256[] memory balances,
uint256[] memory weights
) internal pure returns (int256[] memory deltas) {
uint256 len = balances.length;
deltas = new int256[](len);
for (uint256 i; i < len; i++) {
uint256 targetBalance = totalProductiveBalance.mulFractionE18(weights[i]);
deltas[i] = targetBalance.toInt256().sub(balances[i].toInt256());
}
}
function getBalances(IErc20Adapter[] memory adapters) internal view returns (uint256[] memory balances) {
uint256 len = adapters.length;
balances = new uint256[](len);
for (uint256 i; i < len; i++) balances[i] = adapters[i].balanceUnderlying();
}
function getExcludedAdapterIndices(
IErc20Adapter[] memory oldAdapters,
IErc20Adapter[] memory newAdapters
) internal pure returns (uint256[] memory excludedAdapterIndices) {
uint256 selfLen = oldAdapters.length;
uint256 otherLen = newAdapters.length;
excludedAdapterIndices = DynamicArrays.dynamicUint256Array(selfLen);
for (uint256 i; i < selfLen; i++) {
IErc20Adapter element = oldAdapters[i];
for (uint256 j; j < otherLen; j++) {
if (element == newAdapters[j]) {
element = IErc20Adapter(0);
break;
}
}
if (element != IErc20Adapter(0)) {
excludedAdapterIndices.dynamicPush(i);
}
}
}
/**
* @dev Rebalances the vault by withdrawing tokens from adapters with negative liquidity deltas
* and depositing to adapters with positive liquidity deltas.
*
* Note: This does not necessarily result in a vault composition that matches the assigned weights,
* as some of the lending markets for adapters with negative deltas may have insufficient liquidity
* to process withdrawals of the desired amounts. In this case, the vault will withdraw what it can
* and deposit up to the amount withdrawn to the other markets.
*
* Returns an array with indices of the adapters that both have a weight of zero and were able to
* process a withdrawal of the vault's full balance. This array is used to remove those adapters.
*/
function rebalance(
IErc20Adapter[] memory adapters,
uint256[] memory weights,
int256[] memory liquidityDeltas,
uint256 reserveBalance
) internal returns (uint256[] memory removedIndices) {
uint256 len = liquidityDeltas.length;
removedIndices = DynamicArrays.dynamicUint256Array(len);
uint256 totalAvailableBalance = reserveBalance;
// Execute withdrawals first
for (uint256 i; i < len; i++) {
int256 delta = liquidityDeltas[i];
if (delta < 0) {
uint256 amountToWithdraw = (-delta).toUint256();
uint256 amountWithdrawn = adapters[i].withdrawUnderlyingUpTo(amountToWithdraw);
// If the weight is 0, `amountToWithdraw` is the balance of the vault in the adapter
// and the vault intends to remove the adapter. If the rebalance is able to withdraw
// the full balance, it will mark the index of the adapter as able to be removed
// so that it can be deleted by the rebalance function.
if (weights[i] == 0 && amountWithdrawn == amountToWithdraw) {
removedIndices.dynamicPush(i);
}
totalAvailableBalance = totalAvailableBalance.add(amountWithdrawn);
}
}
// Execute deposits after
for (uint256 i; i < len; i++) {
int256 delta = liquidityDeltas[i];
if (delta > 0) {
if (totalAvailableBalance == 0) break;
uint256 amountToDeposit = delta.toUint256();
if (amountToDeposit >= totalAvailableBalance) {
IErc20Adapter(adapters[i]).deposit(totalAvailableBalance);
break;
}
IErc20Adapter(adapters[i]).deposit(amountToDeposit);
totalAvailableBalance = totalAvailableBalance.sub(amountToDeposit);
}
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "../libraries/LowGasSafeMath.sol";
import "../interfaces/ITokenAdapter.sol";
library ArrayHelper {
using EnumerableSet for EnumerableSet.AddressSet;
using LowGasSafeMath for uint256;
/* ========== Type Cast ========== */
/**
* @dev Cast an enumerable address set as an address array.
* The enumerable set library stores the values as a bytes32 array, this function
* casts it as an address array with a pointer assignment.
*/
function toArray(EnumerableSet.AddressSet storage set) internal view returns (address[] memory arr) {
bytes32[] memory bytes32Arr = set._inner._values;
assembly { arr := bytes32Arr }
}
/**
* @dev Cast an array of IErc20Adapter to an array of address using a pointer assignment.
* Note: The resulting array is the same as the original, so all changes to one will be
* reflected in the other.
*/
function toAddressArray(IErc20Adapter[] memory _arr) internal pure returns (address[] memory arr) {
assembly { arr := _arr }
}
/* ========== Math ========== */
/**
* @dev Computes the sum of a uint256 array.
*/
function sum(uint256[] memory arr) internal pure returns (uint256 _sum) {
uint256 len = arr.length;
for (uint256 i; i < len; i++) _sum = _sum.add(arr[i]);
}
/* ========== Removal ========== */
/**
* @dev Remove the element at `index` from an array and decrement its length.
* If `index` is the last index in the array, pops it from the array.
* Otherwise, stores the last element in the array at `index` and then pops the last element.
*/
function mremove(uint256[] memory arr, uint256 index) internal pure {
uint256 len = arr.length;
if (index != len - 1) {
uint256 last = arr[len - 1];
arr[index] = last;
}
assembly { mstore(arr, sub(len, 1)) }
}
/**
* @dev Remove the element at `index` from an array and decrement its length.
* If `index` is the last index in the array, pops it from the array.
* Otherwise, stores the last element in the array at `index` and then pops the last element.
*/
function mremove(address[] memory arr, uint256 index) internal pure {
uint256 len = arr.length;
if (index != len - 1) {
address last = arr[len - 1];
arr[index] = last;
}
assembly { mstore(arr, sub(len, 1)) }
}
/**
* @dev Remove the element at `index` from an array and decrement its length.
* If `index` is the last index in the array, pops it from the array.
* Otherwise, stores the last element in the array at `index` and then pops the last element.
*/
function mremove(IErc20Adapter[] memory arr, uint256 index) internal pure {
uint256 len = arr.length;
if (index != len - 1) {
IErc20Adapter last = arr[len - 1];
arr[index] = last;
}
assembly { mstore(arr, sub(len, 1)) }
}
/**
* @dev Remove the element at `index` from an array and decrement its length.
* If `index` is the last index in the array, pops it from the array.
* Otherwise, stores the last element in the array at `index` and then pops the last element.
*/
function remove(bytes32[] storage arr, uint256 index) internal {
uint256 len = arr.length;
if (index == len - 1) {
arr.pop();
return;
}
bytes32 last = arr[len - 1];
arr[index] = last;
arr.pop();
}
/**
* @dev Remove the element at `index` from an array and decrement its length.
* If `index` is the last index in the array, pops it from the array.
* Otherwise, stores the last element in the array at `index` and then pops the last element.
*/
function remove(address[] storage arr, uint256 index) internal {
uint256 len = arr.length;
if (index == len - 1) {
arr.pop();
return;
}
address last = arr[len - 1];
arr[index] = last;
arr.pop();
}
/* ========== Search ========== */
/**
* @dev Find the index of an address in an array.
* If the address is not found, revert.
*/
function indexOf(address[] memory arr, address find) internal pure returns (uint256) {
uint256 len = arr.length;
for (uint256 i; i < len; i++) if (arr[i] == find) return i;
revert("element not found");
}
/**
* @dev Determine whether an element is included in an array.
*/
function includes(address[] memory arr, address find) internal pure returns (bool) {
uint256 len = arr.length;
for (uint256 i; i < len; i++) if (arr[i] == find) return true;
return false;
}
/* ========== Sorting ========== */
/**
* @dev Given an array of tokens and scores, sort by scores in descending order.
* Maintains the relationship between elements of each array at the same index.
*/
function sortByDescendingScore(
address[] memory addresses,
uint256[] memory scores
) internal pure {
uint256 len = addresses.length;
for (uint256 i = 0; i < len; i++) {
uint256 score = scores[i];
address _address = addresses[i];
uint256 j = i - 1;
while (int(j) >= 0 && scores[j] < score) {
scores[j + 1] = scores[j];
addresses[j + 1] = addresses[j];
j--;
}
scores[j + 1] = score;
addresses[j + 1] = _address;
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
/**
* @dev Library for handling dynamic in-memory arrays.
*
* There is a very good reason for Solidity not supporting this by default -- dynamic
* arrays in memory completely break memory management for Solidity when used improperly;
* however, they can be created manually in a safe way so long as the maximum size is known
* beforehand.
*
* This applies primarily to situations where a subset is taken from an existing array
* by some filtering process.
*
* This library should not be used to bypass Solidity's lack of dynamic memory array
* support in any situation where the code could potentially cause the array to exceed
* the maximum size assigned in the array creation call. Doing so is likely to have
* unintended and unpredictable side effects.
*/
library DynamicArrays {
/**
* @dev Reserves space in memory for an array of length `size`, but sets the length to 0.
* This can be safely used for a dynamic array so long as the maximum possible size is
* known beforehand. If the array can exceed `size`, pushing to it will corrupt memory.
*/
function dynamicAddressArray(uint256 size) internal pure returns (address[] memory arr) {
arr = new address[](size);
assembly { mstore(arr, 0) }
}
/**
* @dev Reserves space in memory for an array of length `size`, but sets the length to 0.
* This can be safely used for a dynamic array so long as the maximum possible size is
* known beforehand. If the array can exceed length `size`, pushing to it will corrupt memory.
*/
function dynamicUint256Array(uint256 size) internal pure returns (uint256[] memory arr) {
arr = new uint256[](size);
assembly { mstore(arr, 0) }
}
/**
* @dev Pushes an address to an in-memory array by reassigning the array length and storing
* the element in the position used by solidity for the current array index.
* Note: This should ONLY be used on an array created with `dynamicAddressArray`. Using it
* on a typical array created with `new address[]()` will almost certainly have unintended
* and unpredictable side effects.
*/
function dynamicPush(address[] memory arr, address element) internal pure {
assembly {
let size := mload(arr)
let ptr := add(
add(arr, 32),
mul(size, 32)
)
mstore(ptr, element)
mstore(arr, add(size, 1))
}
}
/**
* @dev Pushes a uint256 to an in-memory array by reassigning the array length and storing
* the element in the position used by solidity for the current array index.
* Note: This should ONLY be used on an array created with `dynamicUint256Array`. Using it
* on a typical array created with `new uint256[]()` will almost certainly have unintended
* and unpredictable side effects.
*/
function dynamicPush(uint256[] memory arr, uint256 element) internal pure {
assembly {
let size := mload(arr)
let ptr := add(
add(arr, 32),
mul(size, 32)
)
mstore(ptr, element)
mstore(arr, add(size, 1))
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
import "../libraries/LowGasSafeMath.sol";
library Fraction {
using LowGasSafeMath for uint256;
uint256 internal constant ONE_E18 = 1e18;
function mulFractionE18(uint256 a, uint256 fraction) internal pure returns (uint256) {
return a.mul(fraction) / ONE_E18;
}
function mulSubFractionE18(uint256 a, uint256 fraction) internal pure returns (uint256) {
return a.sub(a.mul(fraction) / ONE_E18);
}
function toFractionE18(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mul(ONE_E18) / b;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.0;
/************************************************************************************************
Originally from https://github.com/Uniswap/uniswap-v3-core/blob/main/contracts/libraries/LowGasSafeMath.sol
This source code has been modified from the original, which was copied from the github repository
at commit hash b83fcf497e895ae59b97c9d04e997023f69b5e97.
Subject to the GPL-2.0 license
*************************************************************************************************/
/// @title Optimized overflow and underflow safe math operations
/// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost
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 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, string memory errorMessage) internal pure returns (uint256 z) {
require((z = x + y) >= x, errorMessage);
}
/// @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(y <= x);
z = x - y;
}
/// @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, string memory errorMessage) internal pure returns (uint256 z) {
require(y <= x, errorMessage);
z = x - y;
}
/// @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) {
if (x == 0) return 0;
z = x * y;
require(z / x == y);
}
/// @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, string memory errorMessage) internal pure returns (uint256 z) {
if (x == 0) return 0;
z = x * y;
require(z / x == y, errorMessage);
}
/// @notice Returns ceil(x / y)
/// @param x The numerator
/// @param y The denominator
/// @return z The quotient of x and y
function divCeil(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x % y == 0 ? x / y : (x/y) + 1;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
library MinimalSignedMath {
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
function add(uint256 a, int256 b) internal pure returns (uint256) {
require(a < 2**255);
int256 _a = int256(a);
int256 c = _a + b;
require((b >= 0 && c >= _a) || (b < 0 && c < _a));
if (c < 0) return 0;
return uint256(c);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "../interfaces/IAdapterRegistry.sol";
import "../interfaces/ITokenAdapter.sol";
import "../libraries/LowGasSafeMath.sol";
import "../libraries/Fraction.sol";
library RebalanceValidation {
using LowGasSafeMath for uint256;
using Fraction for uint256;
function validateSufficientImprovement(
uint256 currentAPR,
uint256 newAPR,
uint256 minImprovement
) internal pure {
require(
newAPR.sub(currentAPR, "!increased").toFractionE18(currentAPR) >= minImprovement,
"insufficient improvement"
);
}
function validateProposedWeights(
uint256[] memory currentWeights,
uint256[] memory proposedWeights
) internal pure {
uint256 len = currentWeights.length;
require(proposedWeights.length == len, "bad lengths");
uint256 _sum;
for (uint256 i; i < len; i++) {
uint256 weight = proposedWeights[i];
_sum = _sum.add(weight);
if (weight == 0) {
require(currentWeights[i] == 0, "can not set null weight");
} else {
require(weight >= 5e16, "weight < 5%");
}
}
require(_sum == 1e18, "weights != 100%");
}
function validateAdaptersAndWeights(
IAdapterRegistry registry,
address underlying,
IErc20Adapter[] memory adapters,
uint256[] memory weights
) internal view {
uint256 len = adapters.length;
require(weights.length == len, "bad lengths");
uint256 totalWeight;
for (uint256 i; i < len; i++) {
IErc20Adapter adapter = adapters[i];
require(registry.isApprovedAdapter(address(adapter)), "!approved");
require(adapter.underlying() == underlying, "bad adapter");
for (uint256 j = i + 1; j < len; j++) {
require(address(adapter) != address(adapters[j]), "duplicate adapter");
}
uint256 weight = weights[i];
totalWeight = totalWeight.add(weight);
require(weight >= 5e16, "weight < 5%");
}
require(totalWeight == 1e18, "weights != 100%");
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/************************************************************************************************
Originally from https://github.com/Uniswap/uniswap-v3-core/blob/main/contracts/libraries/SafeCast.sol
This source code has been modified from the original, which was copied from the github repository
at commit hash b83fcf497e895ae59b97c9d04e997023f69b5e97.
Subject to the GPL-2.0 license
*************************************************************************************************/
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
/// @notice Cast a uint256 to a uint160, revert on overflow
/// @param y The uint256 to be downcasted
/// @return z The downcasted integer, now type uint160
function toUint160(uint256 y) internal pure returns (uint160 z) {
require((z = uint160(y)) == y);
}
/// @notice Cast a uint256 to a uint128, revert on overflow
/// @param y The uint256 to be downcasted
/// @return z The downcasted integer, now type uint128
function toUint128(uint256 y) internal pure returns (uint128 z) {
require((z = uint128(y)) == y);
}
/// @notice Cast a uint256 to a uint96, revert on overflow
/// @param y The uint256 to be downcasted
/// @return z The downcasted integer, now type uint96
function toUint96(uint256 y) internal pure returns (uint96 z) {
require((z = uint96(y)) == y);
}
/// @notice Cast a int256 to a int128, revert on overflow or underflow
/// @param y The int256 to be downcasted
/// @return z The downcasted integer, now type int128
function toInt128(int256 y) internal pure returns (int128 z) {
require((z = int128(y)) == y);
}
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param y The uint256 to be casted
/// @return z The casted integer, now type int256
function toInt256(uint256 y) internal pure returns (int256 z) {
require(y < 2**255);
z = int256(y);
}
/// @notice Cast an int256 to a uint256, revert on overflow
/// @param y The uint256 to be downcasted
/// @return z The downcasted integer, now type uint160
function toUint256(int256 y) internal pure returns (uint256 z) {
require(y >= 0);
z = uint256(y);
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
import "../interfaces/IERC20Metadata.sol";
library SymbolHelper {
/**
* @dev Returns the index of the lowest bit set in `self`.
* Note: Requires that `self != 0`
*/
function lowestBitSet(uint256 self) internal pure returns (uint256 _z) {
require (self > 0, "Bits::lowestBitSet: Value 0 has no bits set");
uint256 _magic = 0x00818283848586878898a8b8c8d8e8f929395969799a9b9d9e9faaeb6bedeeff;
uint256 val = (self & -self) * _magic >> 248;
uint256 _y = val >> 5;
_z = (
_y < 4
? _y < 2
? _y == 0
? 0x753a6d1b65325d0c552a4d1345224105391a310b29122104190a110309020100
: 0xc976c13bb96e881cb166a933a55e490d9d56952b8d4e801485467d2362422606
: _y == 2
? 0xe39ed557db96902cd38ed14fad815115c786af479b7e83247363534337271707
: 0xf7cae577eec2a03cf3bad76fb589591debb2dd67e0aa9834bea6925f6a4a2e0e
: _y < 6
? _y == 4
? 0xc8c0b887b0a8a4489c948c7f847c6125746c645c544c444038302820181008ff
: 0xf6e4ed9ff2d6b458eadcdf97bd91692de2d4da8fd2d0ac50c6ae9a8272523616
: _y == 6
? 0xf5ecf1b3e9debc68e1d9cfabc5997135bfb7a7a3938b7b606b5b4b3f2f1f0ffe
: 0xf8f9cbfae6cc78fbefe7cdc3a1793dfcf4f0e8bbd8cec470b6a28a7a5a3e1efd
);
_z >>= (val & 0x1f) << 3;
return _z & 0xff;
}
function getSymbol(address token) internal view returns (string memory) {
(bool success, bytes memory data) = token.staticcall(abi.encodeWithSignature("symbol()"));
if (!success) return "UNKNOWN";
if (data.length != 32) return abi.decode(data, (string));
uint256 symbol = abi.decode(data, (uint256));
if (symbol == 0) return "UNKNOWN";
uint256 emptyBits = 255 - lowestBitSet(symbol);
uint256 size = (emptyBits / 8) + (emptyBits % 8 > 0 ? 1 : 0);
assembly { mstore(data, size) }
return string(data);
}
function getName(address token) internal view returns (string memory) {
(bool success, bytes memory data) = token.staticcall(abi.encodeWithSignature("name()"));
if (!success) return "UNKNOWN";
if (data.length != 32) return abi.decode(data, (string));
uint256 symbol = abi.decode(data, (uint256));
if (symbol == 0) return "UNKNOWN";
uint256 emptyBits = 255 - lowestBitSet(symbol);
uint256 size = (emptyBits / 8) + (emptyBits % 8 > 0 ? 1 : 0);
assembly { mstore(data, size) }
return string(data);
}
function getPrefixedSymbol(string memory prefix, address token) internal view returns (string memory prefixedSymbol) {
prefixedSymbol = string(abi.encodePacked(
prefix,
getSymbol(token)
));
}
function getPrefixedName(string memory prefix, address token) internal view returns (string memory prefixedName) {
prefixedName = string(abi.encodePacked(
prefix,
getName(token)
));
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
/************************************************************************************************
Originally from https://github.com/Uniswap/uniswap-lib/blob/master/contracts/libraries/TransferHelper.sol
This source code has been modified from the original, which was copied from the github repository
at commit hash cfedb1f55864dcf8cc0831fdd8ec18eb045b7fd1.
Subject to the MIT license
*************************************************************************************************/
library TransferHelper {
function safeApproveMax(address token, address to) internal {
safeApprove(token, to, type(uint256).max);
}
function safeUnapprove(address token, address to) internal {
safeApprove(token, to, 0);
}
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))), "TH:SA");
}
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))), "TH:ST");
}
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))), "TH:STF");
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}("");
require(success, "TH:STE");
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
import "../libraries/LowGasSafeMath.sol";
import "../interfaces/IERC20.sol";
contract ERC20 is IERC20 {
using LowGasSafeMath for uint256;
mapping(address => uint256) public override balanceOf;
mapping(address => mapping(address => uint256)) public override allowance;
uint256 public override totalSupply;
function transfer(address recipient, uint256 amount) external override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function approve(address spender, uint256 amount) external override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) external override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
msg.sender,
allowance[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance")
);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) external override returns (bool) {
_approve(msg.sender, spender, allowance[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) external override returns (bool) {
_approve(
msg.sender,
spender,
allowance[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")
);
return true;
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
balanceOf[sender] = balanceOf[sender].sub(amount, "ERC20: transfer amount exceeds balance");
balanceOf[recipient] = balanceOf[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
totalSupply = totalSupply.add(amount);
balanceOf[account] = balanceOf[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
balanceOf[account] = balanceOf[account].sub(amount, "ERC20: burn amount exceeds balance");
totalSupply = totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(
address owner,
address spender,
uint256 amount
) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
allowance[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(
account,
msg.sender,
allowance[account][msg.sender].sub(amount, "ERC20: burn amount exceeds allowance")
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts/access/Ownable.sol";
import "../libraries/RebalanceValidation.sol";
import "../libraries/SafeCast.sol";
import "./NirnVaultBase.sol";
contract NirnVault is NirnVaultBase {
using Fraction for uint256;
using TransferHelper for address;
using LowGasSafeMath for uint256;
using MinimalSignedMath for int256;
using SafeCast for uint256;
using SafeCast for int256;
using ArrayHelper for uint256[];
using ArrayHelper for bytes32[];
using ArrayHelper for IErc20Adapter[];
using DynamicArrays for uint256[];
using AdapterHelper for IErc20Adapter[];
/* ========== Constructor ========== */
constructor(
address _registry,
address _eoaSafeCaller
) NirnVaultBase(_registry, _eoaSafeCaller) {}
/* ========== Status Queries ========== */
function getCurrentLiquidityDeltas() external view override returns (int256[] memory liquidityDeltas) {
(IErc20Adapter[] memory adapters, uint256[] memory weights) = getAdaptersAndWeights();
BalanceSheet memory balanceSheet = getBalanceSheet(adapters);
liquidityDeltas = AdapterHelper.getLiquidityDeltas(
balanceSheet.totalProductiveBalance,
balanceSheet.balances,
weights
);
}
function getAPR() external view override returns (uint256) {
(DistributionParameters memory params,,) = currentDistribution();
return params.netAPR;
}
/* ========== Deposit/Withdraw ========== */
function deposit(uint256 amount) external override returns (uint256 shares) {
shares = depositTo(amount, msg.sender);
}
function depositTo(uint256 amount, address to) public override returns (uint256 shares) {
uint256 bal = balance();
uint256 max = maximumUnderlying;
if (max > 0) {
require(bal.add(amount) <= max, "maximumUnderlying");
}
underlying.safeTransferFrom(msg.sender, address(this), amount);
uint256 supply = claimFees(bal, totalSupply);
shares = supply == 0 ? amount : amount.mul(supply) / bal;
_mint(to, shares);
emit Deposit(shares, amount);
}
function withdraw(uint256 shares) external override returns (uint256 amountOut) {
(IErc20Adapter[] memory adapters, uint256[] memory weights) = getAdaptersAndWeights();
BalanceSheet memory balanceSheet = getBalanceSheet(adapters);
uint256 supply = claimFees(balanceSheet.totalBalance, totalSupply);
amountOut = shares.mul(balanceSheet.totalBalance) / supply;
withdrawInternal(
shares,
amountOut,
adapters,
weights,
balanceSheet
);
}
function withdrawUnderlying(uint256 amount) external override returns (uint256 shares) {
(IErc20Adapter[] memory adapters, uint256[] memory weights) = getAdaptersAndWeights();
BalanceSheet memory balanceSheet = getBalanceSheet(adapters);
uint256 supply = claimFees(balanceSheet.totalBalance, totalSupply);
shares = amount.mul(supply) / balanceSheet.totalBalance;
withdrawInternal(
shares,
amount,
adapters,
weights,
balanceSheet
);
}
function withdrawInternal(
uint256 shares,
uint256 amountOut,
IErc20Adapter[] memory adapters,
uint256[] memory weights,
BalanceSheet memory balanceSheet
) internal {
_burn(msg.sender, shares);
emit Withdrawal(shares, amountOut);
uint256 newReserves = balanceSheet.totalBalance.sub(amountOut).mulFractionE18(reserveRatio);
withdrawToMatchAmount(
adapters,
weights,
balanceSheet.balances,
balanceSheet.reserveBalance,
amountOut,
newReserves
);
_transferOut(msg.sender, amountOut);
}
function withdrawToMatchAmount(
IErc20Adapter[] memory adapters,
uint256[] memory weights,
uint256[] memory balances,
uint256 _reserveBalance,
uint256 amount,
uint256 newReserves
) internal {
if (amount > _reserveBalance) {
uint256 remainder = amount.sub(_reserveBalance);
uint256 len = balances.length;
uint256[] memory removeIndices = DynamicArrays.dynamicUint256Array(len);
for (uint256 i; i < len; i++) {
uint256 bal = balances[i];
if (bal == 0) continue;
// If the balance is sufficient to withdraw both the remainder and the new reserves,
// withdraw the remainder and the new reserves. Otherwise, withdraw the balance.
uint256 optimalWithdrawal = remainder.add(newReserves);
uint256 amountToWithdraw = bal > optimalWithdrawal
? optimalWithdrawal
: bal;
uint256 amountWithdrawn = adapters[i].withdrawUnderlyingUpTo(amountToWithdraw);
remainder = remainder >= amountWithdrawn ? remainder - amountWithdrawn : 0;
if (weights[i] == 0 && amountWithdrawn == bal) {
removeIndices.dynamicPush(i);
}
if (remainder == 0) break;
}
require(remainder == 0, "insufficient available balance");
removeAdapters(removeIndices);
}
}
/* ========== Rebalance Actions ========== */
function rebalance() external override onlyEOA {
(IErc20Adapter[] memory adapters, uint256[] memory weights) = getAdaptersAndWeights();
BalanceSheet memory balanceSheet = getBalanceSheet(adapters);
int256[] memory liquidityDeltas = AdapterHelper.getLiquidityDeltas(balanceSheet.totalProductiveBalance, balanceSheet.balances, weights);
uint256[] memory removedIndices = AdapterHelper.rebalance(
adapters,
weights,
liquidityDeltas,
balanceSheet.reserveBalance
);
removeAdapters(removedIndices);
emit Rebalanced();
}
function rebalanceWithNewWeights(uint256[] memory proposedWeights) external override onlyEOA changesComposition {
(
DistributionParameters memory params,
uint256 totalProductiveBalance,
uint256 _reserveBalance
) = currentDistribution();
RebalanceValidation.validateProposedWeights(params.weights, proposedWeights);
// Get liquidity deltas and APR for new weights
int256[] memory proposedLiquidityDeltas = AdapterHelper.getLiquidityDeltas(totalProductiveBalance, params.balances, proposedWeights);
uint256 proposedAPR = AdapterHelper.getNetAPR(params.adapters, proposedWeights, proposedLiquidityDeltas).mulSubFractionE18(reserveRatio);
// Validate rebalance results in sufficient APR improvement
RebalanceValidation.validateSufficientImprovement(params.netAPR, proposedAPR, minimumAPRImprovement);
// Rebalance and remove adapters with 0 weight which the vault could fully exit.
uint256[] memory removedIndices = AdapterHelper.rebalance(params.adapters, proposedWeights, proposedLiquidityDeltas, _reserveBalance);
uint256 removeLen = removedIndices.length;
if (removeLen > 0) {
for (uint256 i = removeLen; i > 0; i--) {
uint256 rI = removedIndices[i-1];
emit AdapterRemoved(params.adapters[rI]);
params.adapters.mremove(rI);
proposedWeights.mremove(rI);
}
}
setAdaptersAndWeights(params.adapters, proposedWeights);
}
function currentDistribution() public view override returns (
DistributionParameters memory params,
uint256 totalProductiveBalance,
uint256 _reserveBalance
) {
uint256 _reserveRatio = reserveRatio;
(params.adapters, params.weights) = getAdaptersAndWeights();
uint256 len = params.adapters.length;
uint256 netAPR;
params.balances = params.adapters.getBalances();
_reserveBalance = reserveBalance();
totalProductiveBalance = params.balances.sum().add(_reserveBalance).mulSubFractionE18(_reserveRatio);
params.liquidityDeltas = new int256[](len);
for (uint256 i; i < len; i++) {
IErc20Adapter adapter = params.adapters[i];
uint256 weight = params.weights[i];
uint256 targetBalance = totalProductiveBalance.mulFractionE18(weight);
int256 liquidityDelta = targetBalance.toInt256().sub(params.balances[i].toInt256());
netAPR = netAPR.add(
adapter.getHypotheticalAPR(liquidityDelta).mulFractionE18(weight)
);
params.liquidityDeltas[i] = liquidityDelta;
}
params.netAPR = netAPR.mulSubFractionE18(_reserveRatio);
}
function processProposedDistribution(
DistributionParameters memory currentParams,
uint256 totalProductiveBalance,
IErc20Adapter[] calldata proposedAdapters,
uint256[] calldata proposedWeights
) internal view returns (DistributionParameters memory params) {
uint256[] memory excludedAdapterIndices = currentParams.adapters.getExcludedAdapterIndices(proposedAdapters);
uint256 proposedSize = proposedAdapters.length;
uint256 expandedSize = proposedAdapters.length + excludedAdapterIndices.length;
params.adapters = new IErc20Adapter[](expandedSize);
params.weights = new uint256[](expandedSize);
params.balances = new uint256[](expandedSize);
params.liquidityDeltas = new int256[](expandedSize);
uint256 i;
uint256 netAPR;
for (; i < proposedSize; i++) {
IErc20Adapter adapter = proposedAdapters[i];
params.adapters[i] = adapter;
uint256 weight = proposedWeights[i];
params.weights[i] = weight;
uint256 targetBalance = totalProductiveBalance.mulFractionE18(weight);
uint256 _balance = adapter.balanceUnderlying();
params.balances[i] = _balance;
int256 liquidityDelta = targetBalance.toInt256().sub(_balance.toInt256());
netAPR = netAPR.add(
adapter.getHypotheticalAPR(liquidityDelta).mulFractionE18(weight)
);
params.liquidityDeltas[i] = liquidityDelta;
}
netAPR = netAPR.mulSubFractionE18(reserveRatio);
RebalanceValidation.validateSufficientImprovement(currentParams.netAPR, netAPR, minimumAPRImprovement);
for (; i < expandedSize; i++) {
// i - proposedSize = index in excluded adapter indices array
// The value in excludedAdapterIndices is the index in the current adapters array
// for the adapter which is being removed.
// The lending markets for these adapters may or may not have sufficient liquidity to
// process a full withdrawal requested by the vault, so we keep those adapters in the
// adapters list, but set a weight of 0 and a liquidity delta of -balance
uint256 rI = excludedAdapterIndices[i - proposedSize];
params.adapters[i] = currentParams.adapters[rI];
params.weights[i] = 0;
uint256 _balance = currentParams.balances[rI];
params.balances[i] = _balance;
params.liquidityDeltas[i] = -_balance.toInt256();
}
}
function rebalanceWithNewAdapters(
IErc20Adapter[] calldata proposedAdapters,
uint256[] calldata proposedWeights
) external override onlyEOA changesComposition {
RebalanceValidation.validateAdaptersAndWeights(registry, underlying, proposedAdapters, proposedWeights);
(
DistributionParameters memory currentParams,
uint256 totalProductiveBalance,
uint256 _reserveBalance
) = currentDistribution();
DistributionParameters memory proposedParams = processProposedDistribution(
currentParams,
totalProductiveBalance,
proposedAdapters,
proposedWeights
);
beforeAddAdapters(proposedParams.adapters);
uint256[] memory removedIndices = AdapterHelper.rebalance(
proposedParams.adapters,
proposedParams.weights,
proposedParams.liquidityDeltas,
_reserveBalance
);
uint256 removedLen = removedIndices.length;
if (removedLen > 0) {
// The indices to remove are necessarily in ascending order, so as long as we remove
// them in reverse, the removal of elements will not break the other indices.
for (uint256 i = removedLen; i > 0; i--) {
uint256 rI = removedIndices[i-1];
emit AdapterRemoved(proposedParams.adapters[rI]);
proposedParams.adapters.mremove(rI);
proposedParams.weights.mremove(rI);
}
}
setAdaptersAndWeights(proposedParams.adapters, proposedParams.weights);
}
function _transferOut(address to, uint256 amount) internal {
underlying.safeTransfer(to, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
pragma abicoder v2;
import "../OwnableProxyImplementation.sol";
import "../interfaces/IAdapterRegistry.sol";
import "../interfaces/IRewardsSeller.sol";
import "../interfaces/INirnVault.sol";
import "../libraries/LowGasSafeMath.sol";
import "../libraries/SymbolHelper.sol";
import "../libraries/TransferHelper.sol";
import "../libraries/AdapterHelper.sol";
import "./ERC20.sol";
/**
* @dev Base contract defining the constant and storage variables
* for NirnVault, as well as basic state queries and setters.
*/
abstract contract NirnVaultBase is ERC20, OwnableProxyImplementation(), INirnVault {
using SafeCast for uint256;
using TransferHelper for address;
using Fraction for uint256;
using LowGasSafeMath for uint256;
using MinimalSignedMath for uint256;
using MinimalSignedMath for int256;
using ArrayHelper for uint256[];
using ArrayHelper for address[];
using ArrayHelper for bytes32[];
using ArrayHelper for IErc20Adapter[];
using AdapterHelper for bytes32;
using AdapterHelper for bytes32[];
using AdapterHelper for IErc20Adapter[];
/* ========== Constants ========== */
/**
* @dev Fraction of the current APR of the vault that a proposed rebalance must improve
* the net APR by to be accepted, as a fraction of 1e18.
* 5e16 means newAPR-currentAPR must be greater than or equal to currentAPR*1.05
*/
uint256 public constant override minimumAPRImprovement = 5e16;
uint256 public constant override minimumCompositionChangeDelay = 1 hours;
/** @dev Nirn adapter registry */
IAdapterRegistry public immutable override registry;
/** @dev Address of a contract which can only execute specific functions and only allows EOAs to call. */
address public immutable override eoaSafeCaller;
/* ========== Storage ========== */
/** @dev Underlying asset for the vault. */
address public override underlying;
/** @dev Time at which a changing rebalance can be executed. */
uint96 public override canChangeCompositionAfter;
/** @dev ERC20 name */
string public override name;
/** @dev ERC20 symbol */
string public override symbol;
/** @dev Tokens which can not be sold - wrapper tokens used by the adapters. */
mapping(address => bool) public override lockedTokens;
/** @dev Account that receives performance fees. */
address public override feeRecipient;
/** @dev Address of contract used to sell rewards. */
IRewardsSeller public override rewardsSeller;
/**
* @dev Maximum underlying balance that can be deposited.
* If zero, no maximum.
*/
uint256 public override maximumUnderlying;
/** @dev Fee taken on profit as a fraction of 1e18. */
uint64 public override performanceFee;
/** @dev Ratio of underlying token to keep in the vault for cheap withdrawals as a fraction of 1e18. */
uint64 public override reserveRatio;
/** @dev Last price at which fees were taken. */
uint128 public override priceAtLastFee;
/** @dev Tightly packed token adapters encoded as (address,uint96). */
bytes32[] internal packedAdaptersAndWeights;
/** @dev ERC20 decimals */
function decimals() external view override returns (uint8) {
try IERC20Metadata(underlying).decimals() returns (uint8 _decimals) {
return _decimals;
} catch {
return 18;
}
}
function getAdaptersAndWeights() public view override returns (
IErc20Adapter[] memory adapters,
uint256[] memory weights
) {
(adapters, weights) = packedAdaptersAndWeights.unpackAdaptersAndWeights();
}
function setAdaptersAndWeights(IErc20Adapter[] memory adapters, uint256[] memory weights) internal {
emit AllocationsUpdated(adapters, weights);
packedAdaptersAndWeights = AdapterHelper.packAdaptersAndWeights(
adapters,
weights
);
}
function removeAdapters(uint256[] memory removeIndices) internal {
uint256 len = removeIndices.length;
if (len == 0) return;
for (uint256 i = len; i > 0; i--) {
uint256 rI = removeIndices[i - 1];
(IErc20Adapter adapter,) = packedAdaptersAndWeights[rI].unpackAdapterAndWeight();
emit AdapterRemoved(adapter);
packedAdaptersAndWeights.remove(rI);
}
}
/* ========== Modifiers ========== */
/**
* @dev Prevents calls from arbitrary contracts.
* Caller must be an EOA account or a pre-approved "EOA-safe" caller,
* meaning a smart contract which can only be called by an EOA and has
* a limited set of functions it can call.
* This prevents griefing via flash loans that force the vault to use
* adapters with low interest rates.
*/
modifier onlyEOA {
require(msg.sender == tx.origin || msg.sender == eoaSafeCaller, "!EOA");
_;
}
/**
* @dev Prevents composition-changing rebalances from being executed more
* frequently than the configured minimum delay;
*/
modifier changesComposition {
require(block.timestamp >= canChangeCompositionAfter, "too soon");
canChangeCompositionAfter = block.timestamp.add(minimumCompositionChangeDelay).toUint96();
_;
}
/* ========== Constructor ========== */
constructor(address _registry, address _eoaSafeCaller) {
registry = IAdapterRegistry(_registry);
eoaSafeCaller = _eoaSafeCaller;
}
function initialize(
address _underlying,
address _rewardsSeller,
address _feeRecipient,
address _owner
) external override initializer(_owner) {
require(_feeRecipient != address(0), "null address");
underlying = _underlying;
feeRecipient = _feeRecipient;
rewardsSeller = IRewardsSeller(_rewardsSeller);
(address adapter,) = registry.getAdapterWithHighestAPR(_underlying);
packedAdaptersAndWeights.push(AdapterHelper.packAdapterAndWeight(IErc20Adapter(adapter), 1e18));
beforeAddAdapter(IErc20Adapter(adapter));
name = SymbolHelper.getPrefixedName("Indexed ", _underlying);
symbol = SymbolHelper.getPrefixedSymbol("n", _underlying);
performanceFee = 1e17;
reserveRatio = 1e17;
priceAtLastFee = 1e18;
}
/* ========== Configuration Controls ========== */
function setMaximumUnderlying(uint256 _maximumUnderlying) external override onlyOwner {
maximumUnderlying = _maximumUnderlying;
emit SetMaximumUnderlying(_maximumUnderlying);
}
function setPerformanceFee(uint64 _performanceFee) external override onlyOwner {
claimFees(balance(), totalSupply);
require(_performanceFee <= 2e17, "fee > 20%");
performanceFee = _performanceFee;
emit SetPerformanceFee(_performanceFee);
}
function setReserveRatio(uint64 _reserveRatio) external override onlyOwner {
require(_reserveRatio <= 2e17, "reserve > 20%");
reserveRatio = _reserveRatio;
emit SetReserveRatio(_reserveRatio);
}
function setFeeRecipient(address _feeRecipient) external override onlyOwner {
require(_feeRecipient != address(0), "null address");
feeRecipient = _feeRecipient;
emit SetFeeRecipient(_feeRecipient);
}
function setRewardsSeller(IRewardsSeller _rewardsSeller) external override onlyOwner {
rewardsSeller = _rewardsSeller;
emit SetRewardsSeller(address(_rewardsSeller));
}
/* ========== Reward Token Sale ========== */
function sellRewards(address rewardsToken, bytes calldata params) external override onlyEOA {
uint256 _balance = IERC20(rewardsToken).balanceOf(address(this));
require(!lockedTokens[rewardsToken] && rewardsToken != underlying, "token locked");
IRewardsSeller _rewardsSeller = rewardsSeller;
require(address(_rewardsSeller) != address(0), "null seller");
rewardsToken.safeTransfer(address(_rewardsSeller), _balance);
_rewardsSeller.sellRewards(msg.sender, rewardsToken, underlying, params);
}
function withdrawFromUnusedAdapter(IErc20Adapter adapter) external {
(IErc20Adapter[] memory adapters,) = getAdaptersAndWeights();
require(
!adapters.toAddressArray().includes(address(adapter)),
"!unused"
);
require(registry.isApprovedAdapter(address(adapter)), "!approved");
address wrapper = adapter.token();
wrapper.safeApproveMax(address(adapter));
uint256 bal = adapter.balanceUnderlying();
adapter.withdrawUnderlyingUpTo(bal);
wrapper.safeUnapprove(address(adapter));
}
/* ========== Underlying Balance Queries ========== */
struct BalanceSheet {
uint256[] balances;
uint256 reserveBalance;
uint256 totalBalance;
uint256 totalProductiveBalance;
}
function getBalanceSheet(
IErc20Adapter[] memory adapters
) internal view returns (BalanceSheet memory sheet) {
sheet.balances = adapters.getBalances();
sheet.reserveBalance = reserveBalance();
sheet.totalBalance = sheet.balances.sum().add(sheet.reserveBalance);
sheet.totalProductiveBalance = sheet.totalBalance.mulSubFractionE18(reserveRatio);
}
/**
* @dev Returns the value in `underlying` of the vault's deposits
* in each adapter.
*/
function getBalances() public view override returns (uint256[] memory balances) {
(IErc20Adapter[] memory adapters,) = getAdaptersAndWeights();
return adapters.getBalances();
}
/**
* @dev Returns total value of vault in `underlying`
*/
function balance() public view override returns (uint256 sum) {
(IErc20Adapter[] memory adapters,) = getAdaptersAndWeights();
uint256 len = adapters.length;
for (uint256 i; i < len; i++) {
sum = sum.add(adapters[i].balanceUnderlying());
}
sum = sum.add(reserveBalance());
}
/**
* @dev Returns current "reserve" balance, or balance of `underlying` held by the vault
*/
function reserveBalance() public view override returns (uint256) {
return IERC20(underlying).balanceOf(address(this));
}
/* ========== Fees ========== */
function calculateFee(uint256 totalBalance, uint256 supply) internal view returns (uint256) {
uint256 valueAtLastCollectionPrice = supply.mulFractionE18(priceAtLastFee);
if (totalBalance <= valueAtLastCollectionPrice) return 0;
uint256 profit = totalBalance.sub(valueAtLastCollectionPrice);
return profit.mulFractionE18(performanceFee);
}
function getPendingFees() external view override returns (uint256) {
return calculateFee(balance(), totalSupply);
}
function claimFees(uint256 totalBalance, uint256 supply) internal returns (uint256 newSupply) {
uint256 totalFees = calculateFee(totalBalance, supply);
if (totalFees == 0) return supply;
uint256 equivalentShares = totalFees.mul(supply) / totalBalance.sub(totalFees);
emit FeesClaimed(totalFees, equivalentShares);
_mint(feeRecipient, equivalentShares);
newSupply = supply.add(equivalentShares);
priceAtLastFee = totalBalance.toFractionE18(newSupply).toUint128();
}
function claimFees() external {
claimFees(balance(), totalSupply);
}
/* ========== Price Queries ========== */
function getPricePerFullShare() external view override returns (uint256) {
return balance().toFractionE18(totalSupply);
}
function getPricePerFullShareWithFee() public view override returns (uint256) {
uint256 totalBalance = balance();
uint256 supply = totalSupply;
uint256 pendingFees = calculateFee(totalBalance, supply);
if (pendingFees > 0) {
uint256 equivalentShares = pendingFees.mul(supply) / totalBalance.sub(pendingFees);
supply = supply.add(equivalentShares);
}
return totalBalance.toFractionE18(supply);
}
/* ========== Update Hooks ========== */
function beforeAddAdapter(IErc20Adapter adapter) internal {
address wrapper = adapter.token();
if (IERC20(wrapper).allowance(address(this), address(adapter)) > 0) return;
lockedTokens[wrapper] = true;
underlying.safeApproveMax(address(adapter));
wrapper.safeApproveMax(address(adapter));
}
function beforeAddAdapters(IErc20Adapter[] memory adapters) internal {
uint256 len = adapters.length;
for (uint256 i; i < len; i++) beforeAddAdapter(adapters[i]);
}
}
|
========== Constants ========== / Fraction of the current APR of the vault that a proposed rebalance must improve the net APR by to be accepted, as a fraction of 1e18. 5e16 means newAPR-currentAPR must be greater than or equal to currentAPR1.05/ Nirn adapter registry / Address of a contract which can only execute specific functions and only allows EOAs to call. / ========== Storage ========== / Underlying asset for the vault. / Time at which a changing rebalance can be executed. / ERC20 name / ERC20 symbol / Tokens which can not be sold - wrapper tokens used by the adapters. / Account that receives performance fees. / Address of contract used to sell rewards. / Maximum underlying balance that can be deposited. If zero, no maximum./ Fee taken on profit as a fraction of 1e18. / Ratio of underlying token to keep in the vault for cheap withdrawals as a fraction of 1e18. / Last price at which fees were taken. / Tightly packed token adapters encoded as (address,uint96). / ERC20 decimals /
|
function decimals() external view override returns (uint8) {
try IERC20Metadata(underlying).decimals() returns (uint8 _decimals) {
return _decimals;
return 18;
}
}
| 11,951,393
|
pragma solidity >=0.4.1 <=0.4.20;// Incompatible compiler version... please select one stated within pragma solidity or use different oraclizeAPI version
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) payable returns (bytes32 _id);
function getPrice(string _datasource) returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice);
function useCoupon(string _coupon);
function setProofType(byte _proofType);
function setConfig(bytes32 _config);
function setCustomGasPrice(uint _gasPrice);
}
contract OraclizeAddrResolverI {
function getAddress() returns (address _addr);
}
contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto);
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
oraclize.useCoupon(code);
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) {
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_setConfig(bytes32 config) oraclizeAPI internal {
return oraclize.setConfig(config);
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal returns (string) {
return strConcat(_a, _b, "", "", "");
}
// parseInt
function parseInt(string _a) internal returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
function stra2cbor(string[] arr) internal returns (bytes) {
uint arrlen = arr.length;
// get correct cbor output length
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
// if there's a bug with larger strings, this may be the culprit
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
}
/* =========================================================================================================*/
/**
* @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);
}
/*
** OutCloud Contract begins here
**/
contract OutCloud is ERC20, usingOraclize {
using SafeMath for uint256;
uint ETHUSD;
uint _totalsupply = 1200000000; // 1.2 Billion OUT Coins -F
uint currentTokenPriceFactor;
uint256 no_of_tokens;
uint256 total_token;
uint256 public ico_startdate;
uint256 public preico_startdate;
uint256 public preico_enddate;
// uint256 constant public ETH_DECIMALS = 10 ** 18;
uint256 ethreceived;
uint256 TotalICOSupply;
uint256 TotalPREICOSupply;
uint256 ReservedSupplies;
uint256 minContribution = 1; // 1 USD (1 USD = 100 cents)
uint256 rate;
uint256 weiAmount;
bool stopped = false;
// bool public lockstatus;
string public constant name = "OutCloud";
string public constant symbol = "OUT";
uint public constant decimals = 18;
string public ethereum2USDprice;
address sen;
address public owner;
address public wallet; // address to receive ether from smart contract
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
event LogPriceUpdated(string price);
event LogNewOraclizeQuery(string description);
enum Stages {
NOTSTARTED,
PREICO,
ICO,
ENDED
}
Stages public stage;
modifier atStage(Stages _stage) {
require (stage == _stage);
_;
}
modifier onlyOwner(){
require (msg.sender == owner);
_;
}
function OutCloud(address _owner, address _wallet) public {
owner = _owner;
wallet = _wallet;
TotalICOSupply = 400000000; // -F
TotalPREICOSupply = 300000000; // -F
ReservedSupplies = 500000000; // -F
balances[this] = _totalsupply*10**uint(decimals);
_xx();
// lockstatus = true;
Transfer(address(0), this, _totalsupply*10**uint(decimals));
}
function () public payable {
buyTokens();
}
function __callback(bytes32 myid, string result) {
if (msg.sender != oraclize_cbAddress()) revert();
ethereum2USDprice = result;
ETHUSD = parseInt(result,0);
LogPriceUpdated(result);
if(ETHUSD > 0){
_pro(sen, weiAmount);
}
}
function updatePrice() public payable {
if (oraclize_getPrice("json(https://api.kraken.com/0/public/Ticker?pair=ETHUSD).result.XETHZUSD.c.0") > this.balance) {
LogNewOraclizeQuery("Oraclize query was NOT sent, please add some ETH to cover for the query fee");
revert();
}
else {
LogNewOraclizeQuery("Oraclize query was sent, standing by for the answer..");
oraclize_query("URL","json(https://api.kraken.com/0/public/Ticker?pair=ETHUSD).result.XETHZUSD.c.0");
}
}
function buyTokens() public payable {
sen = msg.sender;
weiAmount = msg.value;
_preValidatePurchase(sen, weiAmount);
updatePrice();
}
function _pro (address _beneficiary, uint256 weiAmount) internal {
// calculate token amount to sell
uint256 tokens = _getTokenAmount(weiAmount);
// update state
ethreceived = ethreceived.add(weiAmount);
_processPurchase(_beneficiary, tokens);
TokenPurchase(this, _beneficiary, weiAmount, tokens);
// _forwardFunds();
}
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal view {
// require(_weiAmount >= _calculateMinimumprice());
require(stage != Stages.ENDED);
require(!stopped);
require(_beneficiary != address(0x0));
require(_weiAmount != 0);
require(_weiAmount >= (minContribution*10**uint(decimals)).div(300));
}
function _getTokenAmount(uint256 _weiAmount) internal returns (uint256) {
_setRate();
return _weiAmount.mul(rate);
}
function _setRate() internal{
uint256 ETHUSD = parseInt(ethereum2USDprice,0);
// check which stage is open (pre-ico or ico)
if (stage == Stages.PREICO && now <= preico_enddate){
require(balances[this] != (_totalsupply.sub(TotalPREICOSupply))*10**uint(decimals));
// pre-ico is open
currentTokenPriceFactor = (block.timestamp.sub(preico_startdate)).div(604800); // 1 week time period in seconds
if (currentTokenPriceFactor== 0) // week 1
_setPriceFactor(10, ETHUSD);
else if (currentTokenPriceFactor == 1) // week 2
_setPriceFactor(11, ETHUSD);
else if (currentTokenPriceFactor ==2 ) // week 3
_setPriceFactor(12, ETHUSD);
else if (currentTokenPriceFactor == 3) // week 4
_setPriceFactor(13, ETHUSD);
}
else if (stage == Stages.ICO ){
require(balances[this] != (_totalsupply.sub(TotalICOSupply.add(TotalPREICOSupply)))*10**uint(decimals));
_setPriceFactor(15, ETHUSD); // ICO started
}
else {
revert();
}
}
function _setPriceFactor(uint cents, uint256 ETHUSD) internal {
uint256 ETHUSD2CENTS = ETHUSD.mul(100); // convert USD price per ethers to cents
uint256 tokenRatePerWei = ETHUSD2CENTS.div(cents); // calculates the rate of the tokens to be given per wei, checking the rate in cents
rate = tokenRatePerWei;
}
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
_deliverTokens(_beneficiary, _tokenAmount);
}
function _forwardFunds() internal {
wallet.transfer(address(this).balance);
}
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
_transfer(_beneficiary,_tokenAmount);
}
// called by the owner, pause ICO
function StopICO() external onlyOwner {
stopped = true;
}
// called by the owner , resumes ICO
function releaseICO() external onlyOwner{
stopped = false;
}
function setEthmainAddress(address newEthfundaddress) external onlyOwner{
wallet = newEthfundaddress;
}
function start_PREICO() external onlyOwner atStage(Stages.NOTSTARTED){
stage = Stages.PREICO;
stopped = false;
preico_startdate = now;
preico_enddate = now + 28 days; //time period for preICO = 4 weeks
}
function _xx() internal {
stage = Stages.PREICO;
stopped = false;
preico_startdate = 1534877389;
preico_enddate = 1537296589;
}
function start_ICO() external onlyOwner atStage(Stages.PREICO){
stage = Stages.ICO;
stopped = false;
ico_startdate = now;
}
function end_ICO() external onlyOwner atStage(Stages.ICO){
stage = Stages.ENDED;
// lockstatus = false;
}
/*// This function can be used by owner in emergency to update running status parameter
function removeLocking(bool RunningStatusLock) external onlyOwner{
lockstatus = RunningStatusLock;
}*/
// 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);
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);
// require( !lockstatus);
allowed[msg.sender][_spender] = _amount;
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) {
/*if ( lockstatus && msg.sender == owner) {
require(balances[msg.sender] >= _amount && _amount >= 0);
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] += _amount;
Transfer(msg.sender, _to, _amount);
return true;
}
else if(!lockstatus)
{*/
require(balances[msg.sender] >= _amount && _amount >= 0);
balances[msg.sender] = (balances[msg.sender]).sub(_amount);
balances[_to] = (balances[_to]).add(_amount);
Transfer(msg.sender, _to, _amount);
return true;
/*}
else{
revert();
}*/
}
//In case the ownership needs to be transferred
function transferOwnership(address newOwner)public onlyOwner{
require( newOwner != 0x0);
balances[newOwner] = (balances[newOwner]).add(balances[owner]);
balances[owner] = 0;
owner = newOwner;
Transfer(msg.sender, newOwner, balances[newOwner]);
}
function _transfer(address _to, uint _tokens) internal returns (bool success){
// prevent transfer to 0x0, use burn instead
require(_to != 0x0);
require(balances[this] >= _tokens);
require(balances[_to] + _tokens >= balances[_to]);
balances[this] = balances[this].sub(_tokens);
balances[_to] = balances[_to].add(_tokens);
Transfer(this,_to,_tokens);
return true;
}
function freeTokens(address receiver, uint tokenAmount) external onlyOwner {
require(balances[this] != 0);
_transfer(receiver,tokenAmount*10**uint(decimals));
}
function drainFunds() external onlyOwner {
_forwardFunds();
}
}
|
lockstatus = false;
|
function end_ICO() external onlyOwner atStage(Stages.ICO){
stage = Stages.ENDED;
}
| 12,701,213
|
./partial_match/1/0x203D619D92904CbBa38710A4f2126f353E99E201/sources/contracts/libraries/BokkyPooBahsDateTimeLibrary.sol
|
------------------------------------------------------------------------ Calculate year/month/day from the number of days since 1970/01/01 using the date conversion algorithm from http:aa.usno.navy.mil/faq/docs/JD_Formula.php and adding the offset 2440588 so that 1970/01/01 is day 0 int L = days + 68569 + offset int N = 4 L / 146097 L = L - (146097 N + 3) / 4 year = 4000 (L + 1) / 1461001 L = L - 1461 year / 4 + 31 month = 80 L / 2447 dd = L - 2447 month / 80 L = month / 11 month = month + 2 - 12 L year = 100 (N - 49) + year + L ------------------------------------------------------------------------
|
function _daysToDate(
uint _days
) internal pure returns (uint year, uint month, uint day) {
int __days = int(_days);
int L = __days + 68569 + OFFSET19700101;
int N = (4 * L) / 146097;
L = L - (146097 * N + 3) / 4;
int _year = (4000 * (L + 1)) / 1461001;
L = L - (1461 * _year) / 4 + 31;
int _month = (80 * L) / 2447;
int _day = L - (2447 * _month) / 80;
L = _month / 11;
_month = _month + 2 - 12 * L;
_year = 100 * (N - 49) + _year + L;
year = uint(_year);
month = uint(_month);
day = uint(_day);
}
| 15,921,054
|
./partial_match/97/0xD7dB66AA506bFef7B47266f9CCD801F3C720d43f/sources/stakingPool.sol
|
get total rewards collected by user
|
function getTotalRewardCollectedByUser(address userAddress) view public returns (uint256 _totalRewardCollected)
{
return userRewardInfo[userAddress].totalWithdrawn;
}
| 11,356,194
|
// to test issue with nodes breaking with large clients over WS
// fixed in web3 with fragmentationThreshold: 8192
pragma solidity ^0.4.17;
contract BigFreakingContract {
event Transfer(address indexed from, address indexed to, uint value);
event Approval( address indexed owner, address indexed spender, uint value);
mapping( address => uint ) _balances;
mapping( address => mapping( address => uint ) ) _approvals;
uint public _supply;
constructor( uint initial_balance ) public {
_balances[msg.sender] = initial_balance;
_supply = initial_balance;
}
function totalSupply() public constant returns (uint supply) {
return _supply;
}
function balanceOf( address who ) public constant returns (uint value) {
return _balances[who];
}
function transfer( address to, uint value) public returns (bool ok) {
if( _balances[msg.sender] < value ) {
revert();
}
if( !safeToAdd(_balances[to], value) ) {
revert();
}
_balances[msg.sender] -= value;
_balances[to] += value;
emit Transfer( msg.sender, to, value );
return true;
}
function transferFrom( address from, address to, uint value) public returns (bool ok) {
// if you don't have enough balance, throw
if( _balances[from] < value ) {
revert();
}
// if you don't have approval, throw
if( _approvals[from][msg.sender] < value ) {
revert();
}
if( !safeToAdd(_balances[to], value) ) {
revert();
}
// transfer and return true
_approvals[from][msg.sender] -= value;
_balances[from] -= value;
_balances[to] += value;
emit Transfer( from, to, value );
return true;
}
function approve(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function allowance(address owner, address spender) public constant returns (uint _allowance) {
return _approvals[owner][spender];
}
function safeToAdd(uint a, uint b) internal pure returns (bool) {
return (a + b >= a);
}
function isAvailable() public pure returns (bool) {
return false;
}
function approve_1(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_2(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_3(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_4(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_5(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_6(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_7(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_8(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_9(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_10(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_11(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_12(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_13(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_14(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_15(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_16(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_17(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_18(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_19(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_20(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_21(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_22(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_23(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_24(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_25(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_26(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_27(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_28(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_29(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_30(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_31(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_32(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_33(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_34(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_35(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_36(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_37(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_38(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_39(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_40(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_41(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_42(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_43(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_44(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_45(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_46(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_47(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_48(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_49(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_50(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_51(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_52(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_53(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_54(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_55(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_56(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_57(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_58(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_59(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_60(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_61(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_62(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_63(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_64(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_65(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_66(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_67(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_68(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_69(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_70(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_71(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_72(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_73(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_74(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_75(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_76(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_77(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_78(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_79(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_80(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_81(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_82(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_83(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_84(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_85(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_86(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_87(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_88(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_89(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_90(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_91(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_92(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_93(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_94(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_95(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_96(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_97(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_98(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_99(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_100(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_101(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_102(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_103(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_104(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_105(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_106(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_107(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_108(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_109(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_110(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_111(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_112(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_113(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_114(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_115(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_116(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_117(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_118(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_119(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_120(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_121(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_122(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_123(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_124(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_125(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_126(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_127(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_128(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_129(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_130(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_131(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_132(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_133(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_134(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_135(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_136(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_137(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_138(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_139(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_140(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_141(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_142(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_143(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_144(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_145(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_146(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_147(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_148(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_149(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_150(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_151(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_152(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_153(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_154(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_155(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_156(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_157(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_158(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_159(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_160(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_161(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_162(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_163(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_164(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_165(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_166(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_167(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_168(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_169(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_170(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_171(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_172(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_173(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_174(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_175(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_176(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_177(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_178(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_179(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_180(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_181(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_182(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_183(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_184(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_185(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_186(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_187(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_188(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_189(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_190(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_191(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_192(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_193(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_194(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_195(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_196(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_197(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_198(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_199(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_200(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_201(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_202(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_203(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_204(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_205(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_206(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_207(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_208(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_209(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_210(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_211(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_212(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_213(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_214(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_215(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_216(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_217(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_218(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_219(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_220(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_221(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_222(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_223(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_224(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_225(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_226(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_227(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_228(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_229(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_230(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_231(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_232(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_233(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_234(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_235(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_236(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_237(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_238(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_239(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_240(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_241(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_242(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_243(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_244(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_245(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_246(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_247(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_248(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_249(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_250(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_251(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_252(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_253(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_254(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_255(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_256(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_257(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_258(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_259(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_260(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_261(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_262(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_263(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_264(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_265(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_266(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_267(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_268(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_269(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_270(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_271(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_272(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_273(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_274(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_275(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_276(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_277(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_278(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_279(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_280(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_281(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_282(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_283(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_284(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_285(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_286(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_287(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_288(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_289(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_290(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_291(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_292(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_293(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_294(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_295(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_296(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_297(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_298(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_299(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_300(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_301(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_302(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_303(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_304(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_305(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_306(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_307(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_308(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_309(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_310(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_311(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_312(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_313(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_314(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_315(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_316(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_317(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_318(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_319(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_320(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_321(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_322(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_323(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_324(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_325(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_326(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_327(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_328(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_329(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_330(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_331(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_332(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_333(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_334(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_335(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_336(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_337(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_338(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_339(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_340(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_341(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_342(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_343(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_344(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_345(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_346(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_347(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_348(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_349(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_350(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_351(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_352(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_353(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_354(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_355(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_356(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_357(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_358(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_359(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_360(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_361(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_362(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_363(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_364(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_365(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_366(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_367(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_368(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_369(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_370(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_371(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_372(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_373(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_374(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_375(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_376(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_377(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_378(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_379(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_380(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_381(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_382(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_383(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_384(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_385(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_386(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_387(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_388(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_389(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_390(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_391(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_392(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_393(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_394(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_395(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_396(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_397(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_398(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_399(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_400(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_401(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_402(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_403(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_404(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_405(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_406(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_407(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_408(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_409(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_410(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_411(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_412(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_413(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_414(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_415(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_416(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_417(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_418(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_419(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_420(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_421(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_422(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_423(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_424(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_425(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_426(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_427(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_428(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_429(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_430(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_431(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_432(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_433(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_434(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_435(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_436(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_437(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_438(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_439(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_440(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_441(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_442(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_443(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_444(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_445(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_446(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_447(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_448(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_449(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_450(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_451(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_452(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_453(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_454(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_455(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_456(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_457(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_458(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_459(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_460(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_461(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_462(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_463(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_464(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_465(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_466(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_467(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_468(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_469(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_470(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_471(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_472(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_473(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_474(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_475(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_476(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_477(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_478(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_479(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_480(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_481(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_482(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_483(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_484(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_485(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_486(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_487(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_488(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_489(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_490(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_491(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_492(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_493(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_494(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_495(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_496(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_497(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_498(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_499(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_500(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_501(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_502(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_503(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_504(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_505(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_506(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_507(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_508(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_509(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_510(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_511(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_512(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_513(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_514(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_515(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_516(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_517(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_518(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_519(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_520(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_521(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_522(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_523(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_524(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_525(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_526(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_527(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_528(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_529(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_530(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_531(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_532(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_533(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_534(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_535(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_536(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_537(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_538(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_539(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_540(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_541(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_542(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_543(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_544(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_545(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_546(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_547(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_548(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_549(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_550(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_551(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_552(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_553(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_554(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_555(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_556(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_557(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_558(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_559(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_560(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_561(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_562(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_563(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_564(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_565(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_566(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_567(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_568(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_569(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_570(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_571(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_572(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_573(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_574(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_575(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_576(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_577(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_578(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_579(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_580(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_581(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_582(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_583(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_584(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_585(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_586(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_587(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_588(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_589(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_590(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_591(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_592(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_593(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_594(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_595(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_596(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_597(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_598(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_599(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_600(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_601(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_602(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_603(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_604(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_605(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_606(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_607(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_608(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_609(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_610(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_611(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_612(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_613(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_614(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_615(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_616(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_617(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_618(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_619(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_620(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_621(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_622(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_623(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_624(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_625(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_626(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_627(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_628(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_629(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_630(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_631(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_632(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_633(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_634(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_635(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_636(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_637(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_638(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_639(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_640(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_641(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_642(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_643(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_644(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_645(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_646(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_647(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_648(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_649(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_650(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_651(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_652(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_653(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_654(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_655(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_656(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_657(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_658(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_659(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_660(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_661(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_662(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_663(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_664(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_665(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_666(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_667(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_668(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_669(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_670(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_671(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_672(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_673(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_674(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_675(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_676(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_677(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_678(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_679(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_680(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_681(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_682(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_683(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_684(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_685(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_686(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_687(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_688(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_689(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_690(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_691(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_692(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_693(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_694(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_695(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_696(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_697(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_698(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_699(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_700(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_701(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_702(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_703(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_704(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_705(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_706(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_707(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_708(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_709(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_710(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_711(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_712(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_713(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_714(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_715(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_716(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_717(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_718(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_719(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_720(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_721(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_722(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_723(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_724(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_725(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_726(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_727(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_728(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_729(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_730(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_731(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_732(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_733(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_734(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_735(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_736(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_737(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_738(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_739(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_740(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_741(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_742(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_743(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_744(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_745(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_746(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_747(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_748(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_749(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_750(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_751(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_752(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_753(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_754(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_755(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_756(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_757(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_758(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_759(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_760(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_761(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_762(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_763(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_764(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_765(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_766(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_767(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_768(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_769(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_770(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_771(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_772(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_773(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_774(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_775(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_776(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_777(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_778(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_779(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_780(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_781(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_782(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_783(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_784(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_785(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_786(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_787(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_788(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_789(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_790(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_791(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_792(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_793(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_794(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_795(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_796(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_797(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_798(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_799(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_800(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_801(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_802(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_803(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_804(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_805(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_806(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_807(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_808(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_809(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_810(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_811(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_812(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_813(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_814(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_815(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_816(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_817(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_818(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_819(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_820(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_821(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_822(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_823(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_824(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_825(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_826(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_827(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_828(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_829(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_830(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_831(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_832(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_833(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_834(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_835(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_836(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_837(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_838(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_839(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_840(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_841(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_842(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_843(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_844(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_845(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_846(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_847(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_848(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_849(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_850(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_851(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_852(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_853(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_854(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_855(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_856(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_857(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_858(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_859(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_860(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_861(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_862(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_863(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_864(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_865(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_866(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_867(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_868(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_869(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_870(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_871(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_872(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_873(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_874(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_875(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_876(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_877(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_878(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_879(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_880(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_881(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_882(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_883(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_884(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_885(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_886(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_887(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_888(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_889(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_890(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_891(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_892(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_893(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_894(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_895(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_896(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_897(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_898(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_899(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_900(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_901(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
}
|
TODO: should increase instead
|
function approve_575(address spender, uint value) public returns (bool ok) {
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
| 6,454,288
|
// SPDX-License-Identifier: Apache-2.0
pragma solidity >=0.6.4 <0.8.0;
pragma experimental ABIEncoderV2;
import "https://github.com/vigilance91/solidarity/contracts/accessControl/blacklist/iBlacklist.sol";
//import "https://github.com/vigilance91/solidarity/contracts/accessControl/frameworkAccessControl.sol";
///
/// @title Framework Blacklist Library
/// @author Tyler R. Drury <vigilstudios.td@gmail.com> (www.twitter.com/StudiosVigil) - copyright 12/5/2021, All Rights Reserved
///
library frameworkBlacklist
{
using LogicConstraints for bool;
using AddressConstraints for address;
using frameworkERC165 for address;
using frameworkAccessControl for address;
string private constant _NAME = 'frameworkBlacklist: ';
//bytes private constant _CALLER_ADDRESS_HASH_SIGNATURE = abi.encodeWithSignature(
//'callerAddressHash()'
//);
//bytes private constant _ROLE_ADMIN_SIGNATURE = abi.encodeWithSignature(
//'ROLE_ADMIN()'
//);
bytes private constant _ROLE_BANNED_SIGNATURE = abi.encodeWithSignature(
'ROLE_BANNED()'
);
bytes private constant _GET_BANNED_MEMBER_COUNT_SIGNATURE = abi.encodeWithSignature(
'getBannedMemberCount()'
);
bytes4 private constant _iBLACKLIST_ID = type(iBlacklist).interfaceId;
function _requireSupportsInterface(
address target
)private view
{
target.supportsInterface(_iBLACKLIST_ID).requireTrue(
'contract does not implement iBlacklist'
);
}
function _requireBanned(
address target,
address account
)internal view
{
isBanned(target, account).requireTrue(
//"sender is not banned"
);
}
function _requireBanned(
address target,
address[] memory accounts
)internal view
{
bool[] memory ret = isBanned(target, accounts);
for(uint i; i < accounts.length; i++){
ret[i].requireTrue(
//_NAME.concatenate(
//"account is not banned: ".concatenate(ret[i].hexadecimal())
//)
);
}
}
function _requireNotBanned(
address target,
bytes32 role,
address[] memory accounts
)internal view
{
bool[] memory ret = isBanned(target, accounts);
for(uint i; i < accounts.length; i++){
ret[i].requireFalse(
//_NAME.concatenate(
//"account is banned: ".concatenate(ret[i].hexadecimal())
//)
);
}
}
//function _requireHasAdminRole(
//bytes32 role,
//address account
//)internal view
//{
//hasRole(target, _roleAt(role).adminRole, account).requireTrue(
////"sender must be an admin"
//);
//}
//function _requireNotHasAdminRole(
//address target,
//bytes32 role,
//address account
//)internal view
//{
//hasRole(target, _roleAt(role).adminRole, account).requireFalse(
////"sender must not be an admin"
//);
//}
/**
modifier onlyBanned(
bytes32 role
)internal view
{
_requireHasRole(role, _msgSender());
_;
}
modifier onlyNotBanned(
bytes32 role
){
_requireNotHasRole(role, _msgSender());
}
*/
///
///read-only/staticcall interface
///
///
/// @return ret {bool} true if account is whitelisted, granted access to network
///
function isBanned(
address target,
address account
)internal view returns(
bool ret
){
_requireSupportsInterface(target);
(bool success, bytes memory result) = target.staticcall(
abi.encodeWithSignature(
'isBanned(address)',
account
)
);
success.requireTrue('staticcall failed');
(ret) = abi.decode(result, (bool));
}
///
/// @return ret {bool} true if account is blacklisted, denying network access
///
function isBanned(
address target,
address[] memory accounts
)internal view returns(
bool[] memory ret
){
_requireSupportsInterface(target);
(bool success, bytes memory result) = target.staticcall(
abi.encodeWithSignature(
'isBanned(address[])',
accounts
)
);
success.requireTrue('staticcall failed');
(ret) = abi.decode(result, (bool[]));
}
*/
///
///mutable interface
///
///
/// @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 ban(
address target,
address account
)internal
{
_requireSupportsInterface(target);
(bool success, ) = target.call(
abi.encodeWithSignature(
'ban(address)',
account
)
);
success.requireTrue('call failed');
}
///
/// @dev Grants `role` to each account in `accounts`
/// If `account` had not been already granted `role`, emits multiple {RoleGranted} events
///
/// Requirements:
/// - the caller must have `role`'s admin role
/// - atomic, each account in `accounts` must not have previously been assigned `role`
///
function ban(
address target,
address[] memory accounts
)internal
{
_requireSupportsInterface(target);
(bool success, ) = target.call(
abi.encodeWithSignature(
'ban(address[])',
accounts
)
);
success.requireTrue('call failed');
}
///
/// @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 revokeBan(
address target,
address account
)internal
{
_requireSupportsInterface(target);
(bool success, ) = target.call(
abi.encodeWithSignature(
'revokeBan(address)',
account
)
);
success.requireTrue('call failed');
}
///
/// @dev Revokes `role` from each accoun in `accounts`
/// If `account` had been granted `role`, emits multiple {RoleRevoked} events
///
/// Requirements:
/// - the caller must have `role`'s admin role
/// - atomic, each account in `accounts` must have previously been assigned `role`
///
function revokeBan(
address target,
address[] memory accounts
)internal
{
_requireSupportsInterface(target);
(bool success, ) = target.call(
abi.encodeWithSignature(
'revokeBan(address[])',
accounts
)
);
success.requireTrue('call failed');
}
function roleBanned(
address target
)internal view returns(
bytes32 ret
){
_requireSupportsInterface(target);
(bool success, bytes memory result) = target.staticcall(
_ROLE_BANNED_SIGNATURE
);
success.requireTrue('static call failed');
(ret) = abi.decode(result, (bytes32));
}
function getBannedMemberCount(
address target
)internal view returns(
uint256 ret
){
_requireSupportsInterface(target);
(bool success, bytes memory result) = target.staticcall(
_GET_BANNED_MEMBER_COUNT_SIGNATURE
);
success.requireTrue('static call failed');
(ret) = abi.decode(result, (uint256));
}
}
|
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 ban(
address target,
address account
)internal
{
_requireSupportsInterface(target);
(bool success, ) = target.call(
abi.encodeWithSignature(
'ban(address)',
account
)
);
success.requireTrue('call failed');
}
| 12,728,587
|
pragma solidity ^0.4.21;
/**
* @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'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;
}
}
/**
* @title TokenlessCrowdsale
* @dev Crowdsale based on OpenZeppelin's Crowdsale but without token-related logic
* @author U-Zyn Chua <uzyn@zynesis.com>
*
* Largely similar to OpenZeppelin except the following irrelevant token-related hooks removed:
* - function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal
* - function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal
* - function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256)
* - event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount)
*
* Added hooks:
* - function _processPurchaseInWei(address _beneficiary, uint256 _weiAmount) internal
* - event SaleContribution(address indexed purchaser, address indexed beneficiary, uint256 value)
*/
contract TokenlessCrowdsale {
using SafeMath for uint256;
// Address where funds are collected
address public wallet;
// Amount of wei raised
uint256 public weiRaised;
/**
* Event for token purchase logging
* similar to TokenPurchase without the token amount
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
*/
event SaleContribution(address indexed purchaser, address indexed beneficiary, uint256 value);
/**
* @param _wallet Address where collected funds will be forwarded to
*/
constructor (address _wallet) public {
require(_wallet != address(0));
wallet = _wallet;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param _beneficiary Address performing the token purchase
*/
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
// update state
weiRaised = weiRaised.add(weiAmount);
_processPurchaseInWei(_beneficiary, weiAmount);
emit SaleContribution(
msg.sender,
_beneficiary,
weiAmount
);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
// optional override
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _beneficiary Address receiving the tokens
* @param _weiAmount Number of wei contributed
*/
function _processPurchaseInWei(address _beneficiary, uint256 _weiAmount) internal {
// override with logic on tokens delivery
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param _beneficiary Address receiving the tokens
* @param _weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal {
// optional override
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
}
/**
* @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 WhitelistedAICrowdsale
* @dev Crowdsale in which only whitelisted users can contribute,
* with a defined individual cap in wei,
* and a bool flag on whether a user is an accredited investor (AI)
* Based on OpenZeppelin's WhitelistedCrowdsale and IndividuallyCappedCrowdsale
* @author U-Zyn Chua <uzyn@zynesis.com>
*/
contract WhitelistedAICrowdsale is TokenlessCrowdsale, Ownable {
using SafeMath for uint256;
mapping(address => bool) public accredited;
// Individual cap
mapping(address => uint256) public contributions;
mapping(address => uint256) public caps;
/**
* @dev Returns if a beneficiary is whitelisted
* @return bool
*/
function isWhitelisted(address _beneficiary) public view returns (bool) {
if (caps[_beneficiary] != 0) {
return true;
}
return false;
}
/**
* @dev Adds single address to whitelist.
* Use this also to update
* @param _beneficiary Address to be added to the whitelist
*/
function addToWhitelist(address _beneficiary, uint256 _cap, bool _accredited) external onlyOwner {
caps[_beneficiary] = _cap;
accredited[_beneficiary] = _accredited;
}
/**
* @dev Removes single address from whitelist.
* @param _beneficiary Address to be removed to the whitelist
*/
function removeFromWhitelist(address _beneficiary) external onlyOwner {
caps[_beneficiary] = 0;
accredited[_beneficiary] = false;
}
/**
* @dev Extend parent behavior requiring beneficiary to be in whitelist.
* @param _beneficiary Token beneficiary
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
super._preValidatePurchase(_beneficiary, _weiAmount);
require(contributions[_beneficiary].add(_weiAmount) <= caps[_beneficiary]);
}
/**
* @dev Extend parent behavior to update user contributions
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal {
super._updatePurchasingState(_beneficiary, _weiAmount);
contributions[_beneficiary] = contributions[_beneficiary].add(_weiAmount);
}
}
/**
* @title FiatCappedCrowdsale
* @dev Crowdsale with a limit for total contributions defined in fiat (USD).
* Based on OpenZeppelin's CappedCrowdsale
* Handles fiat rates, but does not handle token awarding.
* @author U-Zyn Chua <uzyn@zynesis.com>
*/
contract FiatCappedCrowdsale is TokenlessCrowdsale, Ownable {
using SafeMath for uint256;
// 1 USD = 1000 mill (1 mill is USD 0.001)
// 1 ETH = 1e18 wei
// 1 SPX = 1e18 leconte
uint256 public millCap; // cap defined in USD mill
uint256 public millRaised; // amount of USD mill raised
// Minimum fiat value purchase per transaction
uint256 public minMillPurchase;
// How many ETH wei per USD 0.001
uint256 public millWeiRate;
// How many SPX leconte per USD 0.001, without bonus
uint256 public millLeconteRate;
// Sanity checks
// 1 ETH is between USD 100 and USD 5,000
uint256 constant minMillWeiRate = (10 ** 18) / (5000 * (10 ** 3)); // USD 5,000
uint256 constant maxMillWeiRate = (10 ** 18) / (100 * (10 ** 3)); // USD 100
// 1 SPX is between USD 0.01 and USD 1
uint256 constant minMillLeconteRate = (10 ** 18) / 1000; // USD 1
uint256 constant maxMillLeconteRate = (10 ** 18) / 10; // USD 0.01
/**
* @dev Throws if mill rate for ETH wei is not sane
*/
modifier isSaneETHRate(uint256 _millWeiRate) {
require(_millWeiRate >= minMillWeiRate);
require(_millWeiRate <= maxMillWeiRate);
_;
}
/**
* @dev Throws if mill rate for SPX wei is not sane
*/
modifier isSaneSPXRate(uint256 _millLeconteRate) {
require(_millLeconteRate >= minMillLeconteRate);
require(_millLeconteRate <= maxMillLeconteRate);
_;
}
/**
* @dev Constructor
* @param _millCap Max amount of mill to be contributed
* @param _millLeconteRate How many SPX leconte per mill
* @param _millWeiRate How many ETH wei per mill, this is updateable with setWeiRate()
*/
constructor (
uint256 _millCap,
uint256 _minMillPurchase,
uint256 _millLeconteRate,
uint256 _millWeiRate
) public isSaneSPXRate(_millLeconteRate) isSaneETHRate(_millWeiRate) {
require(_millCap > 0);
require(_minMillPurchase > 0);
millCap = _millCap;
minMillPurchase = _minMillPurchase;
millLeconteRate = _millLeconteRate;
millWeiRate = _millWeiRate;
}
/**
* @dev Checks whether the cap has been reached.
* @return Whether the cap was reached
*/
function capReached() public view returns (bool) {
return millRaised >= millCap;
}
/**
* @dev Sets the current ETH wei rate - How many ETH wei per mill
*/
function setWeiRate(uint256 _millWeiRate) external onlyOwner isSaneETHRate(_millWeiRate) {
millWeiRate = _millWeiRate;
}
/**
* @dev Extend parent behavior requiring purchase to respect the funding cap,
* and that contribution should be >= minMillPurchase
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
super._preValidatePurchase(_beneficiary, _weiAmount);
// Check for minimum contribution
uint256 _millAmount = _toMill(_weiAmount);
require(_millAmount >= minMillPurchase);
// Check for funding cap
uint256 _millRaised = millRaised.add(_millAmount);
require(_millRaised <= millCap);
millRaised = _millRaised;
}
/**
* @dev Returns the amount in USD mill given ETH wei
* @param _weiAmount Amount in ETH wei
* @return amount in mill
*/
function _toMill(uint256 _weiAmount) internal returns (uint256) {
return _weiAmount.div(millWeiRate);
}
/**
* @dev Returns the amount in SPX leconte given ETH wei
* @param _weiAmount Amount in ETH wei
* @return amount in leconte
*/
function _toLeconte(uint256 _weiAmount) internal returns (uint256) {
return _toMill(_weiAmount).mul(millLeconteRate);
}
}
/**
* @title PausableCrowdsale
* @dev Crowdsale allowing owner to halt sale process
* Based on OpenZeppelin's TimedCrowdsale
* @author U-Zyn Chua <uzyn@zynesis.com>
*/
contract PausableCrowdsale is TokenlessCrowdsale, Ownable {
/**
* Owner controllable switch to open or halt sale
* This is independent from other checks such as cap, no other processes except owner should alter this value. This also means that even if hardCap is reached, this variable does not set to false on its own.
* This variable is revocable, hence behaving more like a pause than close when turned to off.
*/
bool public open = true;
modifier saleIsOpen() {
require(open);
_;
}
function unpauseSale() external onlyOwner {
require(!open);
open = true;
}
function pauseSale() external onlyOwner saleIsOpen {
open = false;
}
/**
* @dev Extend parent behavior requiring sale to be opened
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal saleIsOpen {
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
/**
* @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);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
/**
* @title ERC223 Token Receiver Interface
* based on https://github.com/Dexaran/ERC223-token-standard/blob/Recommended/Receiver_Interface.sol but much simplified
*/
contract BasicERC223Receiver {
function tokenFallback(address _from, uint256 _value, bytes _data) public pure;
}
/**
* @title RestrictedToken
* @dev Standard Mintable ERC20 Token that can only be sent to an authorized address
* Based on Consensys' TokenFoundry's ControllableToken
* @author U-Zyn Chua <uzyn@zynesis.com>
*/
contract RestrictedToken is BasicToken, Ownable {
string public name;
string public symbol;
uint8 public decimals;
// Authorized senders are able to transfer tokens freely, usu. Sale contract
address public issuer;
// Vesting period for exchanging of RestrictedToken to non-restricted token
// This is for reference by exchange contract and no inherit use for this contract
uint256 public vestingPeriod;
// Holders of RestrictedToken are only able to transfer token to authorizedRecipients, usu. Exchange contract
mapping(address => bool) public authorizedRecipients;
// Whether recipients are ERC223-compliant
mapping(address => bool) public erc223Recipients;
// Last issued time of token per recipient
mapping(address => uint256) public lastIssuedTime;
event Issue(address indexed to, uint256 value);
/**
* @dev Throws if called by any account other than the issuer.
*/
modifier onlyIssuer() {
require(msg.sender == issuer);
_;
}
/**
* @dev Modifier to check if a transfer is allowed
*/
modifier isAuthorizedRecipient(address _recipient) {
require(authorizedRecipients[_recipient]);
_;
}
constructor (
uint256 _supply,
string _name,
string _symbol,
uint8 _decimals,
uint256 _vestingPeriod,
address _owner, // usu. human
address _issuer // usu. sale contract
) public {
require(_supply != 0);
require(_owner != address(0));
require(_issuer != address(0));
name = _name;
symbol = _symbol;
decimals = _decimals;
vestingPeriod = _vestingPeriod;
owner = _owner;
issuer = _issuer;
totalSupply_ = _supply;
balances[_issuer] = _supply;
emit Transfer(address(0), _issuer, _supply);
}
/**
* @dev Allows owner to authorize or deauthorize recipients
*/
function authorize(address _recipient, bool _isERC223) public onlyOwner {
require(_recipient != address(0));
authorizedRecipients[_recipient] = true;
erc223Recipients[_recipient] = _isERC223;
}
function deauthorize(address _recipient) public onlyOwner isAuthorizedRecipient(_recipient) {
authorizedRecipients[_recipient] = false;
erc223Recipients[_recipient] = false;
}
/**
* @dev Only allow transfer to authorized recipients
*/
function transfer(address _to, uint256 _value) public isAuthorizedRecipient(_to) returns (bool) {
if (erc223Recipients[_to]) {
BasicERC223Receiver receiver = BasicERC223Receiver(_to);
bytes memory empty;
receiver.tokenFallback(msg.sender, _value, empty);
}
return super.transfer(_to, _value);
}
/**
* Issue token
* @dev also records the token issued time
*/
function issue(address _to, uint256 _value) public onlyIssuer returns (bool) {
lastIssuedTime[_to] = block.timestamp;
emit Issue(_to, _value);
return super.transfer(_to, _value);
}
}
/**
* @title Sparrow Token private sale
*/
contract PrivateSale is TokenlessCrowdsale, WhitelistedAICrowdsale, FiatCappedCrowdsale, PausableCrowdsale {
using SafeMath for uint256;
// The 2 tokens being sold
RestrictedToken public tokenR0; // SPX-R0 - restricted token with no vesting
RestrictedToken public tokenR6; // SPX-R6 - restricted token with 6-month vesting
uint8 constant bonusPct = 30;
constructor (address _wallet, uint256 _millWeiRate) TokenlessCrowdsale(_wallet)
FiatCappedCrowdsale(
5000000 * (10 ** 3), // millCap: USD 5 million
10000 * (10 ** 3), // minMillPurchase: USD 10,000
(10 ** 18) / 50, // millLeconteRate: 1 SPX = USD 0.05
_millWeiRate
)
public {
tokenR0 = new RestrictedToken(
2 * 100000000 * (10 ** 18), // supply: 100 million (* 2 for edge safety)
'Sparrow Token (Restricted)', // name
'SPX-R0', // symbol
18, // decimals
0, // no vesting
msg.sender, // owner
this // issuer
);
// SPX-R6: Only 30 mil needed if all contributors are AI, 130 mil needed if all contributors are non-AIs
tokenR6 = new RestrictedToken(
2 * 130000000 * (10 ** 18), // supply: 130 million (* 2 for edge safety)
'Sparrow Token (Restricted with 6-month vesting)', // name
'SPX-R6', // symbol
18, // decimals
6 * 30 * 86400, // vesting: 6 months
msg.sender, // owner
this // issuer
);
}
// If accredited, non-bonus tokens are given as tokenR0, bonus tokens are given as tokenR6
// If non-accredited, non-bonus and bonus tokens are given as tokenR6
function _processPurchaseInWei(address _beneficiary, uint256 _weiAmount) internal {
super._processPurchaseInWei(_beneficiary, _weiAmount);
uint256 tokens = _toLeconte(_weiAmount);
uint256 bonus = tokens.mul(bonusPct).div(100);
// Accredited
if (accredited[_beneficiary]) {
tokenR0.issue(_beneficiary, tokens);
tokenR6.issue(_beneficiary, bonus);
} else {
tokenR6.issue(_beneficiary, tokens.add(bonus));
}
}
}
|
Returns the amount in USD mill given ETH wei _weiAmount Amount in ETH wei return amount in mill/
|
function _toMill(uint256 _weiAmount) internal returns (uint256) {
return _weiAmount.div(millWeiRate);
}
| 1,746,450
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.