file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
|---|---|---|---|
/*
Copyright 2021 Empty Set Squad <emptysetsquad@protonmail.com>
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.17;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/lifecycle/Pausable.sol";
import "../registry/RegistryAccessor.sol";
import "../lib/Decimal.sol";
import "../Interfaces.sol";
/**
* @title Migrator
* @notice Migration contract that allows users to burn their ESD v1 assets into Continuous ESDS
* @dev Migration Properties:
* - The ESDS:ESD ratio will be fixed once bonding is disabled by one of the migration preparation v1 EIPs
* - All v1 ESD that is bonded will be burned as part of the migration process
* - There will perpetually be outstanding v1 assets in the form of:
* (1) Circulating v1 ESD
* (2) Unredeemed underlying coupons
* (3) ESDS stake in the v1 DAO
*
* This contract allows the batched conversion of a user's (1) circulating ESD and (3) ESDS stake, but
* does not support directly converting from (2) unredeemed coupons (a user must redeem these beforehand)
*
* In order to initialize this contract, the Continuous ESD protocol must fund it with ESDS such that all
* v1 assets can be redeemed. This should not be initialized until the v1 supply is fixed (e.g. regulation
* paused, epoch advancement turned off, and governance frozen). In the event that this is not possible,
* this contract may be topped up via governance after initialization if there is insufficient available ESDS.
*/
contract Migrator is RegistryAccessor, Pausable {
using SafeMath for uint256;
using Decimal for Decimal.D256;
using SafeERC20 for IERC20;
/**
* @notice Emitted when `owner` initialized this contract after funding with at least `outstandingStake` ESDS
*/
event Initialized(address owner, uint256 outstandingStake);
/**
* @notice Emitted when `account` migrates `dollarAmount` v1 ESD and `stakeAmount` v1 ESDS
*/
event Migration(address account, uint256 dollarAmount, uint256 stakeAmount);
/**
* @notice Emitted when the owner withdraws `amount` ESDS to the reserve due to excess funding
*/
event Withdrawal(uint256 amount);
/**
* @notice Ratio of ESDS granted for ESD burned
* @dev Determined based on the final bonding exchange rate in the v1 DAO
*/
Decimal.D256 public ratio;
/**
* @notice Address of the v1 ESD DAO
*/
IDAO public dao;
/**
* @notice Address of the v1 ESD stablecoin
*/
address public dollar;
/**
* @notice Construct the Migrator contract
* @param ratio_ Ratio of ESDS granted for ESD burned
* @param dao_ Address of the v1 ESD DAO
* @param dollar_ Address of the v1 ESD stablecoin
* @param registry_ Address of the Continuous ESDS contract registry
*/
constructor(uint256 ratio_, IDAO dao_, address dollar_, address registry_) public {
ratio = Decimal.D256({value: ratio_});
dao = dao_;
dollar = dollar_;
setRegistry(registry_);
pause();
}
// ADMIN
/**
* @notice Initializes and unpauses the migrator contract for use
* @dev Owner only - governance hook
* Verifies that this contract is sufficiently funded - reverts if not
*/
function initialize() external onlyOwner {
_verifyBalance();
unpause();
emit Initialized(owner(), outstandingStake());
}
/**
* @notice ESDS-equivalent value of the total outstanding v1 assets
* @return Total ESDS value outstanding
*/
function outstandingStake() public view returns (uint256) {
// Total supply of ESDS from bonded ESD
uint256 bondedStake = dao.totalSupply();
// Total circulating ESD
uint256 circulatingDollar = IERC20(dollar).totalSupply();
// Total ESD locked as coupon underlying
uint256 circulatingCouponUnderlying = dao.totalCouponUnderlying();
// Convertible ESDS from total ESD supply
uint256 circulatingStake = ratio.mul(circulatingDollar.add(circulatingCouponUnderlying)).asUint256();
return bondedStake.add(circulatingStake);
}
/**
* @notice Allows the owner to withdraw `amount` ESDS to the reserve
* @dev Owner only - governance hook
* Verifies that this contract is sufficiently funded - reverts if not
*/
function withdraw(uint256 amount) external onlyOwner {
IERC20(registry.stake()).safeTransfer(registry.reserve(), amount);
_verifyBalance();
emit Withdrawal(amount);
}
/**
* @notice Check that this contract is sufficiently funded with Continuous ESDS for the remaining
* {outstandingStake}
* @dev Internal only - helper
* Verifies that this contract is sufficiently funded - reverts if not
*/
function _verifyBalance() private view {
require(IERC20(registry.stake()).balanceOf(address(this)) >= outstandingStake(), "Migrator: insufficient funds");
}
// MIGRATE
/**
* @notice Migrates `dollarAmount` v1 ESD and `stakeAmount` v1 ESDS for the caller to Continuous ESDS
* @dev Contract must be initialized to call
* @param dollarAmount Amount of v1 ESD to migrate
* @param stakeAmount Amount of v1 ESDS to migrate
*/
function migrate(uint256 dollarAmount, uint256 stakeAmount) external whenNotPaused {
_migrateDollar(msg.sender, dollarAmount);
_migrateStake(msg.sender, stakeAmount);
emit Migration(msg.sender, dollarAmount, stakeAmount);
}
/**
* @notice Migrates `dollarAmount` v1 ESD for `account` to Continuous ESDS
* @dev Internal only - helper
* @param account Account to migrate funds for
* @param dollarAmount Amount of v1 ESD to migrate
*/
function _migrateDollar(address account, uint256 dollarAmount) private {
IERC20(dollar).safeTransferFrom(account, address(this), dollarAmount);
IManagedToken(dollar).burn(dollarAmount);
IERC20(registry.stake()).safeTransfer(account, ratio.mul(dollarAmount).asUint256());
}
/**
* @notice Migrates `stakeAmount` v1 ESDS for `account` to Continuous ESDS
* @dev Internal only - helper
* @param account Account to migrate funds for
* @param stakeAmount Amount of v1 ESDS to migrate
*/
function _migrateStake(address account, uint256 stakeAmount) private {
dao.burn(account, stakeAmount);
IERC20(registry.stake()).safeTransfer(account, stakeAmount);
}
}
/**
* @title IDAO
* @notice Interface for applicable functions on the v1 ESD DAO
*/
interface IDAO {
/**
* @notice Burns the `amount` v1 ESDS from `account`
* @dev callable by the migrator contract only
* @param account Account to burn funds from
* @param amount Amount of v1 ESDS to burn
*/
function burn(address account, uint256 amount) external;
/**
* @notice Total supply of v1 ESDS tokens
* @return v1 ESDS total supply
*/
function totalSupply() external view returns (uint256);
/**
* @notice Total amount of unredeemed v1 coupon underlying
* @return v1 Total coupon underlying
*/
function totalCouponUnderlying() external view returns (uint256);
}
|
Migrates `dollarAmount` v1 ESD for `account` to Continuous ESDS Internal only - helper account Account to migrate funds for dollarAmount Amount of v1 ESD to migrate/
|
function _migrateDollar(address account, uint256 dollarAmount) private {
IERC20(dollar).safeTransferFrom(account, address(this), dollarAmount);
IManagedToken(dollar).burn(dollarAmount);
IERC20(registry.stake()).safeTransfer(account, ratio.mul(dollarAmount).asUint256());
}
| 12,591,622
|
./full_match/1/0xe3a0701b5c8E7c256BEB5f9173620dAD00F46E2C/sources/inari.sol
|
Interface for depositing and withdrawing assets from KASHI.
|
interface IKashi {
function asset() external returns (IERC20);
function addAsset(
address to,
bool skim,
uint256 share
) external returns (uint256 fraction);
function removeAsset(address to, uint256 fraction) external returns (uint256 share);
}
| 8,292,614
|
./full_match/1/0x41CEAe393db3720A848103d7769f31457D5246F3/sources/contracts/Configuration.sol
|
@inheritdoc IConfiguration/
|
function overrideAddressUint96(
address caller,
bytes32 key,
address value0,
uint96 value1
) external override onlyController {
uint256 val = uint256(uint160(value0));
val |= uint256(value1) << 160;
_overrides[caller][key] = val;
emit ParameterOverridden(caller, key, value0, value1);
}
| 4,835,225
|
./partial_match/1/0xC5FDf3569af74f3B3e97E46A187a626352D2d508/sources/ZINU.sol
|
Get tokens to stay in contractGet tokens to swap for ETHSwap for ethSend eth share to distribute to tax walletsSend lp share along with tokens to add LPBurnLeave the remaining eth in contract itself for buybackingProcess buyback
|
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
function processDistributions(uint256 tokens) private {
uint256 totalTokensFee = sBurnFee + sMarketingFee + sLPFee + sBuybackFee;
uint tokensForBurn = (tokens * sBurnFee / totalTokensFee);
uint tokensForETHSwap = tokens - (tokensForBurn + tokensForBurn);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(tokensForETHSwap);
uint256 newETHBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = newETHBalance * sMarketingFee / (totalTokensFee - (sLPFee/2) - sBurnFee);
uint256 ethForLP = newETHBalance * (sLPFee/2) / (totalTokensFee - (sLPFee/2) - sBurnFee);
sendETHToFee(ethForMarketing);
addLiquidity(tokensForLP, ethForLP);
_burn(address(this), tokensForBurn);
if(address(this).balance >= buybackThreshold) {
buyBackTokens();
}
}
| 4,487,087
|
/**
*Submitted for verification at Etherscan.io on 2020-12-11
*/
//"SPDX-License-Identifier: UNLICENSED"sdgeryjewrtrwedcvdfbasAFwe
//frgwert34rgvfev
//frgwert34rgvfev
pragma solidity ^0.6.0;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV
//frgwert34rgvfev9[4R]
abstract contract Context {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUA
//frgwert34rgvfevCV9[4R]
function _msgSender() internal view virtual returns (address payable) {////////sdfert/weh98pWSEI;Jdsewr78
//frgwert34rgvfev039- Q70wgQY3HEwnqdNBHSUACV9[4R]
return msg.sender;}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
function _msgData() internal view virtual returns (bytes memory) {////////sdfert/weh98pWSEI;Jdsewr78
//frgwert34rgvfev039- Q70wgQY3HEwnqdNBHSUACV9[4R]
this;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HE
//frgwert34rgvfevwnqdNBHSUACV9[4R]
return msg.data;}}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
interface IERC20 {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
function totalSupply() external view returns (uint256);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
//frgwert34rgvfev
function balanceOf(address account)external view returns (uint256);////////sdfert/weh98pWSEI;Jdsewr78039- Q70
//frgwert34rgvfevwgQY3HEwnqdNBHSUACV9[4R]
function transfer(address recipient, uint256 amount) external returns (bool);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
function allowance(address owner,address spender) external view returns (uint256);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
function approve(address spender,uint256 amount) external returns (bool);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQ
//frgwert34rgvfevY3HEwnqdNBHSUACV9[4R]
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
event Transfer(address indexed from, address indexed to, uint256 value);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
event Approval(address indexed owner, address indexed spender, uint256 value);}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
library SafeMath {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
function add(uint256 a, uint256 b) internal pure returns (uint256) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
uint256 c = a + b + 0;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
require(c >= (a+0), "SafeMath: addition overflow");////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
return c;}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
function sub(uint256 a, uint256 b) internal pure returns (uint256) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
return sub(a, b, "SafeMath: subtraction overflow");}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
require(b <= a, errorMessage);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
uint256 c = a - b;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
return c;}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
function mul(uint256 a, uint256 b) internal pure returns (uint256) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
if (a == 0) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
return 0;}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
uint256 c = a * b * 1;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
require(c / a == b, "SafeMath: multiplication overflow");////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
return c;}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
function div(uint256 a, uint256 b) internal pure returns (uint256) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
return div(a, b, "SafeMath: division by zero");}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
function diwegrwergw43t5t3h356hv(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
require(b > 0, errorMessage);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
uint256 c = a / b;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
return c;}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
require(b > 0, errorMessage);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
uint256 c = a / b;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
return c;}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
function mod(uint256 a, uint256 b) internal pure returns (uint256) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqEwnqdNBHSUACVRTHHHHHHGFEER15666WERF
//frgwert34rgvfevdNBHSUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
return mod(a, b, "SafeMath: modulo by zero");}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHEwnqdNBHSUACVRTHHHHHHGFEER15666WERF
//frgwert34rgvfevSUACV9[4R]
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
//frgwert34rgvfevHEwnqdNBHSUACV9[4R]
require(b != 0, errorMessage);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnEwnqdNBHSUACVRTHHHHHHGFEER15666WERF
//frgwert34rgvfevqdNBHSUACV9[4R]
return a % b;}}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEEwnqdNBHSUACVRTHHHHHHGFEER15666WERF
//frgwert34rgvfevwnqdNBHSUACV9[4R]
pragma solidity ^0.6.2;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUAEwnqdNBHSUACVRTHHHHHHGFEER15666WERF
//frgwert34rgvfevCV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
library Address {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUA
//frgwert34rgvfevCV9[4R]
function isContract(address account) internal view returns (bool) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
uint256 size;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
assembly { size := extcodesize(account) }////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQ
//frgwert34rgvfevY3HEwnqdNBHSUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
return size > 0;}////////sdfert/weh98pWSEI;JdsewEwnqdNBHSUACVRTHHHHHHGFEER15666WERFr78039- Q70wgQY3HEwnqdNBHSUACV9
//frgwert34rgvfev[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
function sendValue(address payable recipient, uint256 amount) internal {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACVRTHHHHHHGFEER15666WERF
//frgwert34rgvfev9[4R]
require(address(this).balance >= amount, "Address: insufficient balance");///////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HE
//frgwert34rgvfevvwnqdNBHSUACV9[4R]
(bool success, ) = recipient.call{ value: amount }("");////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
//frgwert34rgvfev
require(success, "Address: unable to send value, recipient may have reverted");}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBH
//frgwert34rgvfev
//frgwert34rgvfevSUACV9[4R]
function functionCall(address target, bytes memory data) internal returns (bytes memory) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBH
//frgwert34rgvfevSUACV9[4R]
return functionCall(target, data, "Address: low-level call failed");}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wg
//frgwert34rgvfevQY3HEwnqdNBHSUACV9[4R]
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSU
//frgwert34rgvfevACV9[4R]
return _functionCallWithValue(target, data, 0, errorMessage);}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
//frgwert34rgvfev
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
//frgwert34rgvfev
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
//frgwert34rgvfev
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {////////sdfert/weh98pWSEI;Jdsewr78039-
//frgwert34rgvfev Q70wgQY3HEwnqdNBHSUACV9[4R]
require(address(this).balance >= value, "Address: insufficient balance for call");////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
//frgwert34rgvfev
return _functionCallWithValue(target, data, value, errorMessage);}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70
//frgwert34rgvfevwgQY3HEwnqdNBHSUACV9[4R]
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3
//frgwert34rgvfevHEwnqdNBHSUACV9[4R]returndata.length > returndata.length > returndata.length > returndata.length > returndata.length >
require(isContract(target), "Address: call to non-contract");////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSU
//frgwert34rgvfevACV9[4R]
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/we
//frgwert34rgvfevh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
if (success) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQ
//frgwert34rgvfevY3HEwnqdNBHSUACV9[4R]////////sreturndata.length > dfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
return returndata;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQreturndata.length >
//frgwert34rgvfevY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
} else {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSU
//frgwert34rgvfevACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
if (0 < returndata.length) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
assembly {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
let returndata_size := mload(returndata)////////sdfert/weh98pWSEI;Jdsewr78039-
//frgwert34rgvfev Q70wgQY3HEwnqdNBHSUACV9[4R]
revert(add(32, returndata), returndata_size)}}else {revert(errorMessage);}}}}////////EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
//frgwert34rgvfevsdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr7803
//frgwert34rgvfev9- Q70wgQY3HEwnqdNBHSUACV9[4R]
pragma solidity ^0.6.0;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
//frgwert34rgvfev
contract ERC20 is Context, IERC20 {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
using SafeMath for uint256;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
//frgwert34rgvfev
using Address for address;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
mapping (address => uint256) private _balances;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
mapping (address => mapping (address => uint256)) private _allowances;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
uint256 private _totalSupply;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
//frgwert34rgvfev
string private _name;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
string private _symbol;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
uint8 private _decimals;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
//frgwert34rgvfev
constructor (string memory name, string memory symbol) public {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
_name = name;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
//frgwert34rgvfev
_symbol = symbol;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
_decimals = 10;}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
function name() public view returns (string memory) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
return _name;}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]V////////sdfert/weh98pWSEI;Jdsewr78039-
//frgwert34rgvfevQ70wgQY3HEwnqdNBHSUACV9[4R]
function symbol() public view returns (string memory) {////////sdfert/weh98pWSEI;34TJdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
return _symbol;}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
//frgwert34rgvfev
//frgwert34rgvfev
function decimals() public view returns (uint8) {////////sdfert/weh98pWSEI;JdsewrWFERG78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
return _decimals;}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9XA[4R]////////sdfert/weh98pWSEI;Jdsewr78039-
//frgwert34rgvfev Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
function totalSupply() public view override returns (uint256) {////////sdfert/weh98pWERDCSXWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV
//frgwert34rgvfev9[4R]
return _totalSupply;}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUAXCVBFCV9[4R]
function balanceOf(address account) public view override returns (uint256) {////////sdfert/weh98pWSEI;Jdsewr780XCVBXCV39- Q70wgQY3HEwnqdNBHSUACV9[4R]
//frgwert34rgvfev
return _balances[account];}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWERHSDGVBWSEI;JdseSDFGSwr78039
//frgwert34rgvfev- Q70wgQY3HEwnqdNBHSUACV9[4R]
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {////////sdfert/weh98pWSEI;Jdsewr78039- SDFGWQ70wgQY3HEwnq
//frgwert34rgvfevdNBHSUACV
//frgwert34rgvfev9[4R]
_transfer(_msgSender(), recipient, amount);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]//WERTWEHSFBSF//////sdfert/weh98pWSEI;Jdsewr78039
//frgwert34rgvfev- Q70wgQY3HEwnqdNBHSUACV9[4R]
return true;}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]V////////sdfert/weh98pWSEWTHW453I;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
function allowance(address owner, address spender) public view virtual override returns (uint256) {///ERTHWERHG/////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSU
//frgwert34rgvfevACV9[4R]
return _allowances[owner][spender];}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqWERGWRTdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
function approve(address spender, uint256 amount) public virtual override returns (bool) {//WEYWER//////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
//frgwert34rgvfev
_approve(_msgSender(), spender, amount);////////sdfert/weh98pWSEI;Jdsewr78039- WERG Q70wgQY3HEwnqdNBHSUACV9[4R]
return true;}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]SEFWYW
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3EYHERTHHEwFSFnqdNBHSUACV9[4R]
_transfer(sender, recipient, amount);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSFS
//frgwert34rgvfevFUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));////////sdfert/weh98pWSEI;JdsewRYJMRHr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
return true;}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]JM
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBQ34R45Y65HTBGBNH
//frgwert34rgvfevSUACV9[4R]
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdDFGBDREW4NBHSUACV9[4R]
return true;}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnq34562345dNBHSUACV9[
//frgwert34rgvfev4R]
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {////////sdfert/weh98pWSEI;Jdsewr7803234T234T9- Q70wgQYERWER3HEwnqdNBHSUACV9[4R]
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));//RTHE5//////sdfert/weh98pWSEI;
//frgwert34rgvfevJdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
return true;}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;JdsewRYJ76544536r78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
function _transfer(address sender, address recipient, uint256 amount) internal virtual {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
require(sender != address(0), "ERC20: transfer from the zero address");////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSGUACV9[4R]
//frgwert34rgvfev
require(recipient != address(0), "ERC20: transfer to the zero address");////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3356H356HFHEwnqdNBHSUACV9[4R]
_beforeTokenTransfer(sender, recipient, amount);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]WERG4
//frgwert34rgvfev
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");////////sdfert/weh98pWSEI;JdseDFGBERTwr78039- Q70wgQY3HEwnqdNBHSUA
//frgwert34rgvfevCV9[4R]
_balances[recipient] = _balances[recipient].add(amount);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUSGFBRACV9[4R]
emit Transfer(sender, recipient, amount);}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]5TWE5T
//frgwert34rgvfev
function _mint(address account, uint256 amount) internal virtual {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBFGBR5BHSUACV9[4R]
require(account != address(0), "ERC20: mint to the zero address");////////sdfert/weh98pWSEI;Jdsewr78039- Q70ERTERGFVwgQY3HEwnqdNBHSUACV9[4R]
//frgwert34rgvfev
_beforeTokenTransfer(address(0), account, amount);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqSDFETEdNBHSUACV9[4R]
_totalSupply = _totalSupply.add(amount);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]SDFBRTE
_balances[account] = _balances[account].add(amount);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNSDFBSRTET4BHSUACV9[4R]
//frgwert34rgvfev
emit Transfer(address(0), account, amount);}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]S
function _burn(address account, uint256 amount) internal virtual {////////sdfert/weh98pWSEI;Jdsewr78039- QSDFB70wgQY3HEwnqdNBHSUACV9[4R]
require(account != address(0), "ERC20: burn from the zero address");////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBGSHSUACV9[4R]
//frgwert34rgvfev
_beforeTokenTransfer(account, address(0), amount);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9SRDGSDFGSDR[4R]
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");////////sdfert/weh98pWSEDI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
//frgwert34rgvfev
_totalSupply = _totalSupply.sub(amount);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]ASWEE
emit Transfer(account, address(0), amount);}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]GSDFGVXC
//frgwert34rgvfev
function _approve(address owner, address spender, uint256 amount) internal virtual {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgVZFGRQY3HEwnqdNBHSUACV9[4R]
//frgwert34rgvfev
require(owner != address(0), "ERC20: approve from the zero address");////////sdfert/weh98pWSEI;JdsewrEwnqdNBHSUACVRTHHHHHHGFEER15666WERF78039- Q70wgQRTERGDFVZXY3HEwnqdNBHSUACV9[4R]
//frgwert34rgvfevEwnqdNBHSUACVRTHHHHHHGFEER15666WERF
require(spender != address(0), "ERC20: approve to the zero address");////////sdfert/weh98pWSEI;JdEwnqdNBHSUACVRTHHHHHHGFEER15666WERFsewr78039- Q7RFVZ0wgQY3HEwnqdNBHSUACV9[4R]
_allowances[owner][spender] = amount;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUAEwnqdNBHSUACVRTHHHHHHGFEER15666WERFCV9[4R]ZXCRGTW
//frgwert34rgvfevEwnqdNBHSUACVRTHHHHHHGFEER15666WERF
emit Approval(owner, spender, amount);}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUAEwnqdNBHSUACVRTHHHHHHGFEER15666WERFCVASDF9[4R]
//frgwert34rgvfevEwnqdNBHSUACVRTHHHHHHGFEER15666WERF
function _setupDecimals(uint8 decimals_) internal {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQYEwnqdNBHSUACVRTHHHHHHGFEER15666WERF3HEwWTHnqdNBHSUACV9[4R]
_decimals = decimals_;}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]WERTEwnqdNBHSUACVRTHHHHHHGFEER15666WERFWERT
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }}////////sdfeREwnqdNBHSUACVRTHHHHHHGFEER15666WERFETWERTrt/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
//frgwert34rgvfev
abstract contract ERC20Burnable is Context, ERC20 {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqEwnqdNBHSUACVRTHHHHHHGFEER15666WERFdNBHSUACERTWERTV9[4R]
//frgwert34rgvfev
function burn(uint256 amount) public virtual {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBEwnqdNBHSUACVRTHHHHHHGFEER15666WERFHSUACV9[4R]
//frgwert34rgvfev
//frgwert34rgvfev
_burn(_msgSender(), amount);}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]TWETEwnqdNBHSUACVRTHHHHHHGFEER15666WERF
//frgwert34rgvfev
function burnFrom(address account, uint256 amount) public virtual {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHS5TWERUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERFEwnqdNBHSUACVRTHHHHHHGFEER15666WERF
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");////////sdfert/weh98pWSEI;RTG5TJEwnqdNBHSUACVRTHHHHHHGFEER15666WERFdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
//frgwert34rgvfevEwnqdNBHSUACVRTHHHHHHGFEER15666WERF
_approve(account, _msgSender(), decreasedAllowance);////////sdfert/weh98pWSEI;JdsewET34YJHDBFr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]EEwnqdNBHSUACVRTHHHHHHGFEER15666WERFwnqdNBHSUACVRTHHHHHHGFEER15666WERF
//frgwert34rgvfev
_burn(account, amount);}}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNB4T5HSUACV6U3569[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSURGWEYACV9[4R]
//frgwert34rgvfev
///////////////////////////////GSDFG/////////////////////////////////////////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
//frgwert34rgvfev
////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUTWERGDFACV9[4R]
//frgwert34rgvfevEwnqdNBHSUACVRTHHHHHHGFEER15666WERF
/////////////////////////////////////////////////////////////SDFE///////////////sdferERFDSFt/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
//frgwert34rgvfev
////////////////////////////////////////////////////////////////////////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
//frgwert34rgvfev
////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfeERTrt/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
//frgwert34rgvfev
contract EasyToken is ERC20, ERC20Burnable {////////sdfert/weh98pWSEI;Jdsewr78039- Q7EWTRE0wgQY3HEwnqdNBERTHSUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
constructor(uint256 initialSupply) public ERC20("easify.network", "EASY") {////////sdfert/weFGDSFDGh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
//frgwert34rgvfev
//frgwert34rgvfevEwnqdNBHSUACVRTHHHHHHGFEER15666WERF
initialSupply = 10000000e10;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]//RT//////sdfertDFGDF/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
//frgwert34rgvfev
_mint(msg.sender, initialSupply);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R45Y]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
//frgwert34rgvfev
}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]YTH4563
//frgwert34rgvfev
}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]EWRGWRYJ6Y5RE
//frgwert34rgvfev
|
/ERTHWERHG/sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSU
|
function allowance(address owner, address spender) public view virtual override returns (uint256) {
| 2,079,371
|
pragma solidity 0.4.24;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @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 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;
}
}
/**
* @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;
}
}
/**
* @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 Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/issues/20
* Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_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);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @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;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
/**
* @title Pausable token
* @dev StandardToken modified with pausable transfers.
**/
contract PausableToken is StandardToken, 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 increaseApproval(
address _spender,
uint _addedValue
)
public
whenNotPaused
returns (bool success)
{
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
whenNotPaused
returns (bool success)
{
return super.decreaseApproval(_spender, _subtractedValue);
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
contract RepublicToken is PausableToken, BurnableToken {
string public constant name = "Republic Token";
string public constant symbol = "REN";
uint8 public constant decimals = 18;
uint256 public constant INITIAL_SUPPLY = 1000000000 * 10**uint256(decimals);
/// @notice The RepublicToken Constructor.
constructor() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
}
function transferTokens(address beneficiary, uint256 amount) public onlyOwner returns (bool) {
/* solium-disable error-reason */
require(amount > 0);
balances[owner] = balances[owner].sub(amount);
balances[beneficiary] = balances[beneficiary].add(amount);
emit Transfer(owner, beneficiary, amount);
return true;
}
}
/**
* @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 = 0x0;
/**
* @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 Ownable {
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 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;
// RepublicToken.
RepublicToken public ren;
/// @notice The contract constructor.
///
/// @param _VERSION A string defining the contract version.
/// @param _ren The address of the RepublicToken contract.
constructor(
string _VERSION,
RepublicToken _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 _darknodeOwner,
uint256 _bond,
bytes _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 the darknode. If the bond is being
/// decreased, the difference is sent to the owner of this contract.
function updateDarknodeBond(address darknodeID, uint256 bond) external onlyOwner {
uint256 previousBond = darknodeRegistry[darknodeID].bond;
darknodeRegistry[darknodeID].bond = bond;
if (previousBond > bond) {
require(ren.transfer(owner, previousBond - bond), "cannot transfer bond");
}
}
/// @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) {
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) {
return darknodeRegistry[darknodeID].publicKey;
}
}
/// @notice DarknodeRegistry is responsible for the registration and
/// deregistration of Darknodes.
contract DarknodeRegistry is Ownable {
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;
address public slasher;
/// 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;
address public nextSlasher;
/// The current and previous epoch
Epoch public currentEpoch;
Epoch public previousEpoch;
/// Republic ERC20 token contract used to transfer bonds.
RepublicToken public ren;
/// Darknode Registry Store is the storage contract for darknodes.
DarknodeRegistryStore public store;
/// @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 _darknodeID, uint256 _bond);
/// @notice Emitted when a darknode is deregistered.
/// @param _darknodeID The darknode ID that was deregistered.
event LogDarknodeDeregistered(address _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 _owner, uint256 _amount);
/// @notice Emitted when a new epoch has begun.
event LogNewEpoch();
/// @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(slasher == msg.sender, "must be slasher");
_;
}
/// @notice The contract constructor.
///
/// @param _VERSION A string defining the contract version.
/// @param _renAddress The address of the RepublicToken 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 _VERSION,
RepublicToken _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. The
/// caller must provide a public encryption key for the darknode as well as
/// a bond in REN. The bond must be provided as an ERC20 allowance. The dark
/// node 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.
/// @param _bond The bond that will be paid. It must be greater than, or
/// equal to, the minimum bond.
function register(address _darknodeID, bytes _publicKey, uint256 _bond) external onlyRefunded(_darknodeID) {
// REN allowance
require(_bond >= minimumBond, "insufficient bond");
// require(ren.allowance(msg.sender, address(this)) >= _bond);
require(ren.transferFrom(msg.sender, address(this), _bond), "bond transfer failed");
ren.transfer(address(store), _bond);
// Flag this darknode for registration
store.appendDarknode(
_darknodeID,
msg.sender,
_bond,
_publicKey,
currentEpoch.blocknumber + minimumEpochInterval,
0
);
numDarknodesNextEpoch += 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) {
// Flag the darknode for deregistration
store.updateDarknodeDeregisteredAt(_darknodeID, currentEpoch.blocknumber + minimumEpochInterval);
numDarknodesNextEpoch -= 1;
// Emit an event
emit LogDarknodeDeregistered(_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 + 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(slasher, nextSlasher);
}
// Emit an event
emit LogNewEpoch();
}
/// @notice Allows the contract owner to transfer ownership of the
/// DarknodeRegistryStore.
/// @param _newOwner The address to transfer the ownership to.
function transferStoreOwnership(address _newOwner) external onlyOwner {
store.transferOwnership(_newOwner);
}
/// @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(address _slasher) external onlyOwner {
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)) {
store.updateDarknodeDeregisteredAt(_prover, currentEpoch.blocknumber + minimumEpochInterval);
numDarknodesNextEpoch -= 1;
emit LogDarknodeDeregistered(_prover);
}
// Reward the challengers with less than the penalty so that it is not
// worth challenging yourself
ren.transfer(store.darknodeOwner(_challenger1), reward);
ren.transfer(store.darknodeOwner(_challenger2), reward);
}
/// @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
ren.transfer(darknodeOwner, amount);
// 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) {
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) {
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[]) {
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[]) {
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 _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[]) {
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 == 0x0) {
next = store.begin();
}
// Iterate until all registered Darknodes have been collected
while (n < count) {
if (next == 0x0) {
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;
}
}
/**
* @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;
}
}
/// @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;
/// @notice Calls transfer on the token and reverts if the call fails.
function safeTransfer(address token, address to, uint256 amount) internal {
CompatibleERC20(token).transfer(to, amount);
require(previousReturnValue(), "transfer failed");
}
/// @notice Calls transferFrom on the token and reverts if the call fails.
function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
CompatibleERC20(token).transferFrom(from, to, amount);
require(previousReturnValue(), "transferFrom failed");
}
/// @notice Calls approve on the token and reverts if the call fails.
function safeApprove(address token, address spender, uint256 amount) internal {
CompatibleERC20(token).approve(spender, amount);
require(previousReturnValue(), "approve failed");
}
/// @notice Calls transferFrom on the token, reverts if the call fails and
/// returns the value transferred after fees.
function safeTransferFromWithFees(address token, address from, address to, uint256 amount) internal returns (uint256) {
uint256 balancesBefore = CompatibleERC20(token).balanceOf(to);
CompatibleERC20(token).transferFrom(from, to, amount);
require(previousReturnValue(), "transferFrom failed");
uint256 balancesAfter = CompatibleERC20(token).balanceOf(to);
return Math.min256(amount, balancesAfter.sub(balancesBefore));
}
/// @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(0x0, 0x0, 32)
// Load the return data into returnData
returnData := mload(0x0)
}
// Other return size: return false
default { }
}
return returnData != 0;
}
}
/// @notice ERC20 interface which doesn't specify the return type for transfer,
/// transferFrom and approve.
interface CompatibleERC20 {
// Modified to not return boolean
function transfer(address to, uint256 value) external;
function transferFrom(address from, address to, uint256 value) external;
function approve(address spender, uint256 value) external;
// Not modifier
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);
}
/// @notice The DarknodeRewardVault contract is responsible for holding fees
/// for darknodes for settling orders. Fees can be withdrawn to the address of
/// the darknode's operator. Fees can be in ETH or in ERC20 tokens.
/// Docs: https://github.com/republicprotocol/republic-sol/blob/master/docs/02-darknode-reward-vault.md
contract DarknodeRewardVault is Ownable {
using SafeMath for uint256;
using CompatibleERC20Functions for CompatibleERC20;
string public VERSION; // Passed in as a constructor parameter.
/// @notice The special address for Ether.
address constant public ETHEREUM = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
DarknodeRegistry public darknodeRegistry;
mapping(address => mapping(address => uint256)) public darknodeBalances;
event LogDarknodeRegistryUpdated(DarknodeRegistry previousDarknodeRegistry, DarknodeRegistry nextDarknodeRegistry);
/// @notice The contract constructor.
///
/// @param _VERSION A string defining the contract version.
/// @param _darknodeRegistry The DarknodeRegistry contract that is used by
/// the vault to lookup Darknode owners.
constructor(string _VERSION, DarknodeRegistry _darknodeRegistry) public {
VERSION = _VERSION;
darknodeRegistry = _darknodeRegistry;
}
function updateDarknodeRegistry(DarknodeRegistry _newDarknodeRegistry) public onlyOwner {
emit LogDarknodeRegistryUpdated(darknodeRegistry, _newDarknodeRegistry);
darknodeRegistry = _newDarknodeRegistry;
}
/// @notice Deposit fees into the vault for a Darknode. The Darknode
/// registration is not checked (to reduce gas fees); the caller must be
/// careful not to call this function for a Darknode that is not registered
/// otherwise any fees deposited to that Darknode can be withdrawn by a
/// malicious adversary (by registering the Darknode before the honest
/// party and claiming ownership).
///
/// @param _darknode The address of the Darknode that will receive the
/// fees.
/// @param _token The address of the ERC20 token being used to pay the fee.
/// A special address is used for Ether.
/// @param _value The amount of fees in the smallest unit of the token.
function deposit(address _darknode, ERC20 _token, uint256 _value) public payable {
uint256 receivedValue = _value;
if (address(_token) == ETHEREUM) {
require(msg.value == _value, "mismatched ether value");
} else {
require(msg.value == 0, "unexpected ether value");
receivedValue = CompatibleERC20(_token).safeTransferFromWithFees(msg.sender, address(this), _value);
}
darknodeBalances[_darknode][_token] = darknodeBalances[_darknode][_token].add(receivedValue);
}
/// @notice Withdraw fees earned by a Darknode. The fees will be sent to
/// the owner of the Darknode. If a Darknode is not registered the fees
/// cannot be withdrawn.
///
/// @param _darknode The address of the Darknode whose fees are being
/// withdrawn. The owner of this Darknode will receive the fees.
/// @param _token The address of the ERC20 token to withdraw.
function withdraw(address _darknode, ERC20 _token) public {
address darknodeOwner = darknodeRegistry.getDarknodeOwner(address(_darknode));
require(darknodeOwner != 0x0, "invalid darknode owner");
uint256 value = darknodeBalances[_darknode][_token];
darknodeBalances[_darknode][_token] = 0;
if (address(_token) == ETHEREUM) {
darknodeOwner.transfer(value);
} else {
CompatibleERC20(_token).safeTransfer(darknodeOwner, value);
}
}
}
/// @notice The BrokerVerifier interface defines the functions that a settlement
/// layer's broker verifier contract must implement.
interface BrokerVerifier {
/// @notice The function signature that will be called when a trader opens
/// an order.
///
/// @param _trader The trader requesting the withdrawal.
/// @param _signature The 65-byte signature from the broker.
/// @param _orderID The 32-byte order ID.
function verifyOpenSignature(
address _trader,
bytes _signature,
bytes32 _orderID
) external returns (bool);
}
/// @notice The Settlement interface defines the functions that a settlement
/// layer must implement.
/// Docs: https://github.com/republicprotocol/republic-sol/blob/nightly/docs/05-settlement.md
interface Settlement {
function submitOrder(
bytes _details,
uint64 _settlementID,
uint64 _tokens,
uint256 _price,
uint256 _volume,
uint256 _minimumVolume
) external;
function submissionGasPriceLimit() external view returns (uint256);
function settle(
bytes32 _buyID,
bytes32 _sellID
) external;
/// @notice orderStatus should return the status of the order, which should
/// be:
/// 0 - Order not seen before
/// 1 - Order details submitted
/// >1 - Order settled, or settlement no longer possible
function orderStatus(bytes32 _orderID) external view returns (uint8);
}
/// @notice SettlementRegistry allows a Settlement layer to register the
/// contracts used for match settlement and for broker signature verification.
contract SettlementRegistry is Ownable {
string public VERSION; // Passed in as a constructor parameter.
struct SettlementDetails {
bool registered;
Settlement settlementContract;
BrokerVerifier brokerVerifierContract;
}
// Settlement IDs are 64-bit unsigned numbers
mapping(uint64 => SettlementDetails) public settlementDetails;
// Events
event LogSettlementRegistered(uint64 settlementID, Settlement settlementContract, BrokerVerifier brokerVerifierContract);
event LogSettlementUpdated(uint64 settlementID, Settlement settlementContract, BrokerVerifier brokerVerifierContract);
event LogSettlementDeregistered(uint64 settlementID);
/// @notice The contract constructor.
///
/// @param _VERSION A string defining the contract version.
constructor(string _VERSION) public {
VERSION = _VERSION;
}
/// @notice Returns the settlement contract of a settlement layer.
function settlementRegistration(uint64 _settlementID) external view returns (bool) {
return settlementDetails[_settlementID].registered;
}
/// @notice Returns the settlement contract of a settlement layer.
function settlementContract(uint64 _settlementID) external view returns (Settlement) {
return settlementDetails[_settlementID].settlementContract;
}
/// @notice Returns the broker verifier contract of a settlement layer.
function brokerVerifierContract(uint64 _settlementID) external view returns (BrokerVerifier) {
return settlementDetails[_settlementID].brokerVerifierContract;
}
/// @param _settlementID A unique 64-bit settlement identifier.
/// @param _settlementContract The address to use for settling matches.
/// @param _brokerVerifierContract The decimals to use for verifying
/// broker signatures.
function registerSettlement(uint64 _settlementID, Settlement _settlementContract, BrokerVerifier _brokerVerifierContract) public onlyOwner {
bool alreadyRegistered = settlementDetails[_settlementID].registered;
settlementDetails[_settlementID] = SettlementDetails({
registered: true,
settlementContract: _settlementContract,
brokerVerifierContract: _brokerVerifierContract
});
if (alreadyRegistered) {
emit LogSettlementUpdated(_settlementID, _settlementContract, _brokerVerifierContract);
} else {
emit LogSettlementRegistered(_settlementID, _settlementContract, _brokerVerifierContract);
}
}
/// @notice Deregisteres a settlement layer, clearing the details.
/// @param _settlementID The unique 64-bit settlement identifier.
function deregisterSettlement(uint64 _settlementID) external onlyOwner {
require(settlementDetails[_settlementID].registered, "not registered");
delete settlementDetails[_settlementID];
emit LogSettlementDeregistered(_settlementID);
}
}
/**
* @title Eliptic curve signature operations
* @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d
* TODO Remove this library once solidity supports passing a signature to ecrecover.
* See https://github.com/ethereum/solidity/issues/864
*/
library ECRecovery {
/**
* @dev Recover signer address from a message by using their signature
* @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address.
* @param sig bytes signature, the signature is generated using web3.eth.sign()
*/
function recover(bytes32 hash, bytes sig)
internal
pure
returns (address)
{
bytes32 r;
bytes32 s;
uint8 v;
// Check the signature length
if (sig.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solium-disable-next-line security/no-inline-assembly
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address
if (v != 27 && v != 28) {
return (address(0));
} else {
// solium-disable-next-line arg-overflow
return ecrecover(hash, v, r, s);
}
}
/**
* toEthSignedMessageHash
* @dev prefix a bytes32 value with "\x19Ethereum Signed Message:"
* and hash the result
*/
function toEthSignedMessageHash(bytes32 hash)
internal
pure
returns (bytes32)
{
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)
);
}
}
library Utils {
/**
* @notice Converts a number to its string/bytes representation
*
* @param _v the uint to convert
*/
function uintToBytes(uint256 _v) internal pure returns (bytes) {
uint256 v = _v;
if (v == 0) {
return "0";
}
uint256 digits = 0;
uint256 v2 = v;
while (v2 > 0) {
v2 /= 10;
digits += 1;
}
bytes memory result = new bytes(digits);
for (uint256 i = 0; i < digits; i++) {
result[digits - i - 1] = bytes1((v % 10) + 48);
v /= 10;
}
return result;
}
/**
* @notice Retrieves the address from a signature
*
* @param _hash the message that was signed (any length of bytes)
* @param _signature the signature (65 bytes)
*/
function addr(bytes _hash, bytes _signature) internal pure returns (address) {
bytes memory prefix = "\x19Ethereum Signed Message:\n";
bytes memory encoded = abi.encodePacked(prefix, uintToBytes(_hash.length), _hash);
bytes32 prefixedHash = keccak256(encoded);
return ECRecovery.recover(prefixedHash, _signature);
}
}
/// @notice The Orderbook contract stores the state and priority of orders and
/// allows the Darknodes to easily reach consensus. Eventually, this contract
/// will only store a subset of order states, such as cancellation, to improve
/// the throughput of orders.
contract Orderbook is Ownable {
string public VERSION; // Passed in as a constructor parameter.
/// @notice OrderState enumerates the possible states of an order. All
/// orders default to the Undefined state.
enum OrderState {Undefined, Open, Confirmed, Canceled}
/// @notice Order stores a subset of the public data associated with an order.
struct Order {
OrderState state; // State of the order
address trader; // Trader that owns the order
address confirmer; // Darknode that confirmed the order in a match
uint64 settlementID; // The settlement that signed the order opening
uint256 priority; // Logical time priority of this order
uint256 blockNumber; // Block number of the most recent state change
bytes32 matchedOrder; // Order confirmed in a match with this order
}
DarknodeRegistry public darknodeRegistry;
SettlementRegistry public settlementRegistry;
bytes32[] private orderbook;
// Order details are exposed through directly accessing this mapping, or
// through the getter functions below for each of the order's fields.
mapping(bytes32 => Order) public orders;
event LogFeeUpdated(uint256 previousFee, uint256 nextFee);
event LogDarknodeRegistryUpdated(DarknodeRegistry previousDarknodeRegistry, DarknodeRegistry nextDarknodeRegistry);
/// @notice Only allow registered dark nodes.
modifier onlyDarknode(address _sender) {
require(darknodeRegistry.isRegistered(address(_sender)), "must be registered darknode");
_;
}
/// @notice The contract constructor.
///
/// @param _VERSION A string defining the contract version.
/// @param _darknodeRegistry The address of the DarknodeRegistry contract.
/// @param _settlementRegistry The address of the SettlementRegistry
/// contract.
constructor(
string _VERSION,
DarknodeRegistry _darknodeRegistry,
SettlementRegistry _settlementRegistry
) public {
VERSION = _VERSION;
darknodeRegistry = _darknodeRegistry;
settlementRegistry = _settlementRegistry;
}
/// @notice Allows the owner to update the address of the DarknodeRegistry
/// contract.
function updateDarknodeRegistry(DarknodeRegistry _newDarknodeRegistry) external onlyOwner {
emit LogDarknodeRegistryUpdated(darknodeRegistry, _newDarknodeRegistry);
darknodeRegistry = _newDarknodeRegistry;
}
/// @notice Open an order in the orderbook. The order must be in the
/// Undefined state.
///
/// @param _signature Signature of the message that defines the trader. The
/// message is "Republic Protocol: open: {orderId}".
/// @param _orderID The hash of the order.
function openOrder(uint64 _settlementID, bytes _signature, bytes32 _orderID) external {
require(orders[_orderID].state == OrderState.Undefined, "invalid order status");
address trader = msg.sender;
// Verify the order signature
require(settlementRegistry.settlementRegistration(_settlementID), "settlement not registered");
BrokerVerifier brokerVerifier = settlementRegistry.brokerVerifierContract(_settlementID);
require(brokerVerifier.verifyOpenSignature(trader, _signature, _orderID), "invalid broker signature");
orders[_orderID] = Order({
state: OrderState.Open,
trader: trader,
confirmer: 0x0,
settlementID: _settlementID,
priority: orderbook.length + 1,
blockNumber: block.number,
matchedOrder: 0x0
});
orderbook.push(_orderID);
}
/// @notice Confirm an order match between orders. The confirmer must be a
/// registered Darknode and the orders must be in the Open state. A
/// malicious confirmation by a Darknode will result in a bond slash of the
/// Darknode.
///
/// @param _orderID The hash of the order.
/// @param _matchedOrderID The hashes of the matching order.
function confirmOrder(bytes32 _orderID, bytes32 _matchedOrderID) external onlyDarknode(msg.sender) {
require(orders[_orderID].state == OrderState.Open, "invalid order status");
require(orders[_matchedOrderID].state == OrderState.Open, "invalid order status");
orders[_orderID].state = OrderState.Confirmed;
orders[_orderID].confirmer = msg.sender;
orders[_orderID].matchedOrder = _matchedOrderID;
orders[_orderID].blockNumber = block.number;
orders[_matchedOrderID].state = OrderState.Confirmed;
orders[_matchedOrderID].confirmer = msg.sender;
orders[_matchedOrderID].matchedOrder = _orderID;
orders[_matchedOrderID].blockNumber = block.number;
}
/// @notice Cancel an open order in the orderbook. An order can be cancelled
/// by the trader who opened the order, or by the broker verifier contract.
/// This allows the settlement layer to implement their own logic for
/// cancelling orders without trader interaction (e.g. to ban a trader from
/// a specific darkpool, or to use multiple order-matching platforms)
///
/// @param _orderID The hash of the order.
function cancelOrder(bytes32 _orderID) external {
require(orders[_orderID].state == OrderState.Open, "invalid order state");
// Require the msg.sender to be the trader or the broker verifier
address brokerVerifier = address(settlementRegistry.brokerVerifierContract(orders[_orderID].settlementID));
require(msg.sender == orders[_orderID].trader || msg.sender == brokerVerifier, "not authorized");
orders[_orderID].state = OrderState.Canceled;
orders[_orderID].blockNumber = block.number;
}
/// @notice returns status of the given orderID.
function orderState(bytes32 _orderID) external view returns (OrderState) {
return orders[_orderID].state;
}
/// @notice returns a list of matched orders to the given orderID.
function orderMatch(bytes32 _orderID) external view returns (bytes32) {
return orders[_orderID].matchedOrder;
}
/// @notice returns the priority of the given orderID.
/// The priority is the index of the order in the orderbook.
function orderPriority(bytes32 _orderID) external view returns (uint256) {
return orders[_orderID].priority;
}
/// @notice returns the trader of the given orderID.
/// Trader is the one who signs the message and does the actual trading.
function orderTrader(bytes32 _orderID) external view returns (address) {
return orders[_orderID].trader;
}
/// @notice returns the darknode address which confirms the given orderID.
function orderConfirmer(bytes32 _orderID) external view returns (address) {
return orders[_orderID].confirmer;
}
/// @notice returns the block number when the order being last modified.
function orderBlockNumber(bytes32 _orderID) external view returns (uint256) {
return orders[_orderID].blockNumber;
}
/// @notice returns the block depth of the orderId
function orderDepth(bytes32 _orderID) external view returns (uint256) {
if (orders[_orderID].blockNumber == 0) {
return 0;
}
return (block.number - orders[_orderID].blockNumber);
}
/// @notice returns the number of orders in the orderbook
function ordersCount() external view returns (uint256) {
return orderbook.length;
}
/// @notice returns order details of the orders starting from the offset.
function getOrders(uint256 _offset, uint256 _limit) external view returns (bytes32[], address[], uint8[]) {
if (_offset >= orderbook.length) {
return;
}
// If the provided limit is more than the number of orders after the offset,
// decrease the limit
uint256 limit = _limit;
if (_offset + limit > orderbook.length) {
limit = orderbook.length - _offset;
}
bytes32[] memory orderIDs = new bytes32[](limit);
address[] memory traderAddresses = new address[](limit);
uint8[] memory states = new uint8[](limit);
for (uint256 i = 0; i < limit; i++) {
bytes32 order = orderbook[i + _offset];
orderIDs[i] = order;
traderAddresses[i] = orders[order].trader;
states[i] = uint8(orders[order].state);
}
return (orderIDs, traderAddresses, states);
}
}
/// @notice A library for calculating and verifying order match details
library SettlementUtils {
struct OrderDetails {
uint64 settlementID;
uint64 tokens;
uint256 price;
uint256 volume;
uint256 minimumVolume;
}
/// @notice Calculates the ID of the order.
/// @param details Order details that are not required for settlement
/// execution. They are combined as a single byte array.
/// @param order The order details required for settlement execution.
function hashOrder(bytes details, OrderDetails memory order) internal pure returns (bytes32) {
return keccak256(
abi.encodePacked(
details,
order.settlementID,
order.tokens,
order.price,
order.volume,
order.minimumVolume
)
);
}
/// @notice Verifies that two orders match when considering the tokens,
/// price, volumes / minimum volumes and settlement IDs. verifyMatchDetails is used
/// my the DarknodeSlasher to verify challenges. Settlement layers may also
/// use this function.
/// @dev When verifying two orders for settlement, you should also:
/// 1) verify the orders have been confirmed together
/// 2) verify the orders' traders are distinct
/// @param _buy The buy order details.
/// @param _sell The sell order details.
function verifyMatchDetails(OrderDetails memory _buy, OrderDetails memory _sell) internal pure returns (bool) {
// Buy and sell tokens should match
if (!verifyTokens(_buy.tokens, _sell.tokens)) {
return false;
}
// Buy price should be greater than sell price
if (_buy.price < _sell.price) {
return false;
}
// // Buy volume should be greater than sell minimum volume
if (_buy.volume < _sell.minimumVolume) {
return false;
}
// Sell volume should be greater than buy minimum volume
if (_sell.volume < _buy.minimumVolume) {
return false;
}
// Require that the orders were submitted to the same settlement layer
if (_buy.settlementID != _sell.settlementID) {
return false;
}
return true;
}
/// @notice Verifies that two token requirements can be matched and that the
/// tokens are formatted correctly.
/// @param _buyTokens The buy token details.
/// @param _sellToken The sell token details.
function verifyTokens(uint64 _buyTokens, uint64 _sellToken) internal pure returns (bool) {
return ((
uint32(_buyTokens) == uint32(_sellToken >> 32)) && (
uint32(_sellToken) == uint32(_buyTokens >> 32)) && (
uint32(_buyTokens >> 32) <= uint32(_buyTokens))
);
}
}
/// @notice RenExTokens is a registry of tokens that can be traded on RenEx.
contract RenExTokens is Ownable {
string public VERSION; // Passed in as a constructor parameter.
struct TokenDetails {
address addr;
uint8 decimals;
bool registered;
}
// Storage
mapping(uint32 => TokenDetails) public tokens;
mapping(uint32 => bool) private detailsSubmitted;
// Events
event LogTokenRegistered(uint32 tokenCode, address tokenAddress, uint8 tokenDecimals);
event LogTokenDeregistered(uint32 tokenCode);
/// @notice The contract constructor.
///
/// @param _VERSION A string defining the contract version.
constructor(string _VERSION) public {
VERSION = _VERSION;
}
/// @notice Allows the owner to register and the details for a token.
/// Once details have been submitted, they cannot be overwritten.
/// To re-register the same token with different details (e.g. if the address
/// has changed), a different token identifier should be used and the
/// previous token identifier should be deregistered.
/// If a token is not Ethereum-based, the address will be set to 0x0.
///
/// @param _tokenCode A unique 32-bit token identifier.
/// @param _tokenAddress The address of the token.
/// @param _tokenDecimals The decimals to use for the token.
function registerToken(uint32 _tokenCode, address _tokenAddress, uint8 _tokenDecimals) public onlyOwner {
require(!tokens[_tokenCode].registered, "already registered");
// If a token is being re-registered, the same details must be provided.
if (detailsSubmitted[_tokenCode]) {
require(tokens[_tokenCode].addr == _tokenAddress, "different address");
require(tokens[_tokenCode].decimals == _tokenDecimals, "different decimals");
} else {
detailsSubmitted[_tokenCode] = true;
}
tokens[_tokenCode] = TokenDetails({
addr: _tokenAddress,
decimals: _tokenDecimals,
registered: true
});
emit LogTokenRegistered(_tokenCode, _tokenAddress, _tokenDecimals);
}
/// @notice Sets a token as being deregistered. The details are still stored
/// to prevent the token from being re-registered with different details.
///
/// @param _tokenCode The unique 32-bit token identifier.
function deregisterToken(uint32 _tokenCode) external onlyOwner {
require(tokens[_tokenCode].registered, "not registered");
tokens[_tokenCode].registered = false;
emit LogTokenDeregistered(_tokenCode);
}
}
/// @notice RenExSettlement implements the Settlement interface. It implements
/// the on-chain settlement for the RenEx settlement layer, and the fee payment
/// for the RenExAtomic settlement layer.
contract RenExSettlement is Ownable {
using SafeMath for uint256;
string public VERSION; // Passed in as a constructor parameter.
// This contract handles the settlements with ID 1 and 2.
uint32 constant public RENEX_SETTLEMENT_ID = 1;
uint32 constant public RENEX_ATOMIC_SETTLEMENT_ID = 2;
// Fees in RenEx are 0.2%. To represent this as integers, it is broken into
// a numerator and denominator.
uint256 constant public DARKNODE_FEES_NUMERATOR = 2;
uint256 constant public DARKNODE_FEES_DENOMINATOR = 1000;
// Constants used in the price / volume inputs.
int16 constant private PRICE_OFFSET = 12;
int16 constant private VOLUME_OFFSET = 12;
// Constructor parameters, updatable by the owner
Orderbook public orderbookContract;
RenExTokens public renExTokensContract;
RenExBalances public renExBalancesContract;
address public slasherAddress;
uint256 public submissionGasPriceLimit;
enum OrderStatus {None, Submitted, Settled, Slashed}
struct TokenPair {
RenExTokens.TokenDetails priorityToken;
RenExTokens.TokenDetails secondaryToken;
}
// A uint256 tuple representing a value and an associated fee
struct ValueWithFees {
uint256 value;
uint256 fees;
}
// A uint256 tuple representing a fraction
struct Fraction {
uint256 numerator;
uint256 denominator;
}
// We use left and right because the tokens do not always represent the
// priority and secondary tokens.
struct SettlementDetails {
uint256 leftVolume;
uint256 rightVolume;
uint256 leftTokenFee;
uint256 rightTokenFee;
address leftTokenAddress;
address rightTokenAddress;
}
// Events
event LogOrderbookUpdated(Orderbook previousOrderbook, Orderbook nextOrderbook);
event LogRenExTokensUpdated(RenExTokens previousRenExTokens, RenExTokens nextRenExTokens);
event LogRenExBalancesUpdated(RenExBalances previousRenExBalances, RenExBalances nextRenExBalances);
event LogSubmissionGasPriceLimitUpdated(uint256 previousSubmissionGasPriceLimit, uint256 nextSubmissionGasPriceLimit);
event LogSlasherUpdated(address previousSlasher, address nextSlasher);
// Order Storage
mapping(bytes32 => SettlementUtils.OrderDetails) public orderDetails;
mapping(bytes32 => address) public orderSubmitter;
mapping(bytes32 => OrderStatus) public orderStatus;
// Match storage (match details are indexed by [buyID][sellID])
mapping(bytes32 => mapping(bytes32 => uint256)) public matchTimestamp;
/// @notice Prevents a function from being called with a gas price higher
/// than the specified limit.
///
/// @param _gasPriceLimit The gas price upper-limit in Wei.
modifier withGasPriceLimit(uint256 _gasPriceLimit) {
require(tx.gasprice <= _gasPriceLimit, "gas price too high");
_;
}
/// @notice Restricts a function to only being called by the slasher
/// address.
modifier onlySlasher() {
require(msg.sender == slasherAddress, "unauthorized");
_;
}
/// @notice The contract constructor.
///
/// @param _VERSION A string defining the contract version.
/// @param _orderbookContract The address of the Orderbook contract.
/// @param _renExBalancesContract The address of the RenExBalances
/// contract.
/// @param _renExTokensContract The address of the RenExTokens contract.
constructor(
string _VERSION,
Orderbook _orderbookContract,
RenExTokens _renExTokensContract,
RenExBalances _renExBalancesContract,
address _slasherAddress,
uint256 _submissionGasPriceLimit
) public {
VERSION = _VERSION;
orderbookContract = _orderbookContract;
renExTokensContract = _renExTokensContract;
renExBalancesContract = _renExBalancesContract;
slasherAddress = _slasherAddress;
submissionGasPriceLimit = _submissionGasPriceLimit;
}
/// @notice The owner of the contract can update the Orderbook address.
/// @param _newOrderbookContract The address of the new Orderbook contract.
function updateOrderbook(Orderbook _newOrderbookContract) external onlyOwner {
emit LogOrderbookUpdated(orderbookContract, _newOrderbookContract);
orderbookContract = _newOrderbookContract;
}
/// @notice The owner of the contract can update the RenExTokens address.
/// @param _newRenExTokensContract The address of the new RenExTokens
/// contract.
function updateRenExTokens(RenExTokens _newRenExTokensContract) external onlyOwner {
emit LogRenExTokensUpdated(renExTokensContract, _newRenExTokensContract);
renExTokensContract = _newRenExTokensContract;
}
/// @notice The owner of the contract can update the RenExBalances address.
/// @param _newRenExBalancesContract The address of the new RenExBalances
/// contract.
function updateRenExBalances(RenExBalances _newRenExBalancesContract) external onlyOwner {
emit LogRenExBalancesUpdated(renExBalancesContract, _newRenExBalancesContract);
renExBalancesContract = _newRenExBalancesContract;
}
/// @notice The owner of the contract can update the order submission gas
/// price limit.
/// @param _newSubmissionGasPriceLimit The new gas price limit.
function updateSubmissionGasPriceLimit(uint256 _newSubmissionGasPriceLimit) external onlyOwner {
emit LogSubmissionGasPriceLimitUpdated(submissionGasPriceLimit, _newSubmissionGasPriceLimit);
submissionGasPriceLimit = _newSubmissionGasPriceLimit;
}
/// @notice The owner of the contract can update the slasher address.
/// @param _newSlasherAddress The new slasher address.
function updateSlasher(address _newSlasherAddress) external onlyOwner {
emit LogSlasherUpdated(slasherAddress, _newSlasherAddress);
slasherAddress = _newSlasherAddress;
}
/// @notice Stores the details of an order.
///
/// @param _prefix The miscellaneous details of the order required for
/// calculating the order id.
/// @param _settlementID The settlement identifier.
/// @param _tokens The encoding of the token pair (buy token is encoded as
/// the first 32 bytes and sell token is encoded as the last 32
/// bytes).
/// @param _price The price of the order. Interpreted as the cost for 1
/// standard unit of the non-priority token, in 1e12 (i.e.
/// PRICE_OFFSET) units of the priority token).
/// @param _volume The volume of the order. Interpreted as the maximum
/// number of 1e-12 (i.e. VOLUME_OFFSET) units of the non-priority
/// token that can be traded by this order.
/// @param _minimumVolume The minimum volume the trader is willing to
/// accept. Encoded the same as the volume.
function submitOrder(
bytes _prefix,
uint64 _settlementID,
uint64 _tokens,
uint256 _price,
uint256 _volume,
uint256 _minimumVolume
) external withGasPriceLimit(submissionGasPriceLimit) {
SettlementUtils.OrderDetails memory order = SettlementUtils.OrderDetails({
settlementID: _settlementID,
tokens: _tokens,
price: _price,
volume: _volume,
minimumVolume: _minimumVolume
});
bytes32 orderID = SettlementUtils.hashOrder(_prefix, order);
require(orderStatus[orderID] == OrderStatus.None, "order already submitted");
require(orderbookContract.orderState(orderID) == Orderbook.OrderState.Confirmed, "unconfirmed order");
orderSubmitter[orderID] = msg.sender;
orderStatus[orderID] = OrderStatus.Submitted;
orderDetails[orderID] = order;
}
/// @notice Settles two orders that are matched. `submitOrder` must have been
/// called for each order before this function is called.
///
/// @param _buyID The 32 byte ID of the buy order.
/// @param _sellID The 32 byte ID of the sell order.
function settle(bytes32 _buyID, bytes32 _sellID) external {
require(orderStatus[_buyID] == OrderStatus.Submitted, "invalid buy status");
require(orderStatus[_sellID] == OrderStatus.Submitted, "invalid sell status");
// Check the settlement ID (only have to check for one, since
// `verifyMatchDetails` checks that they are the same)
require(
orderDetails[_buyID].settlementID == RENEX_ATOMIC_SETTLEMENT_ID ||
orderDetails[_buyID].settlementID == RENEX_SETTLEMENT_ID,
"invalid settlement id"
);
// Verify that the two order details are compatible.
require(SettlementUtils.verifyMatchDetails(orderDetails[_buyID], orderDetails[_sellID]), "incompatible orders");
// Verify that the two orders have been confirmed to one another.
require(orderbookContract.orderMatch(_buyID) == _sellID, "unconfirmed orders");
// Retrieve token details.
TokenPair memory tokens = getTokenDetails(orderDetails[_buyID].tokens);
// Require that the tokens have been registered.
require(tokens.priorityToken.registered, "unregistered priority token");
require(tokens.secondaryToken.registered, "unregistered secondary token");
address buyer = orderbookContract.orderTrader(_buyID);
address seller = orderbookContract.orderTrader(_sellID);
require(buyer != seller, "orders from same trader");
execute(_buyID, _sellID, buyer, seller, tokens);
/* solium-disable-next-line security/no-block-members */
matchTimestamp[_buyID][_sellID] = now;
// Store that the orders have been settled.
orderStatus[_buyID] = OrderStatus.Settled;
orderStatus[_sellID] = OrderStatus.Settled;
}
/// @notice Slashes the bond of a guilty trader. This is called when an
/// atomic swap is not executed successfully.
/// To open an atomic order, a trader must have a balance equivalent to
/// 0.6% of the trade in the Ethereum-based token. 0.2% is always paid in
/// darknode fees when the order is matched. If the remaining amount is
/// is slashed, it is distributed as follows:
/// 1) 0.2% goes to the other trader, covering their fee
/// 2) 0.2% goes to the slasher address
/// Only one order in a match can be slashed.
///
/// @param _guiltyOrderID The 32 byte ID of the order of the guilty trader.
function slash(bytes32 _guiltyOrderID) external onlySlasher {
require(orderDetails[_guiltyOrderID].settlementID == RENEX_ATOMIC_SETTLEMENT_ID, "slashing non-atomic trade");
bytes32 innocentOrderID = orderbookContract.orderMatch(_guiltyOrderID);
require(orderStatus[_guiltyOrderID] == OrderStatus.Settled, "invalid order status");
require(orderStatus[innocentOrderID] == OrderStatus.Settled, "invalid order status");
orderStatus[_guiltyOrderID] = OrderStatus.Slashed;
(bytes32 buyID, bytes32 sellID) = isBuyOrder(_guiltyOrderID) ?
(_guiltyOrderID, innocentOrderID) : (innocentOrderID, _guiltyOrderID);
TokenPair memory tokens = getTokenDetails(orderDetails[buyID].tokens);
SettlementDetails memory settlementDetails = calculateAtomicFees(buyID, sellID, tokens);
// Transfer the fee amount to the other trader
renExBalancesContract.transferBalanceWithFee(
orderbookContract.orderTrader(_guiltyOrderID),
orderbookContract.orderTrader(innocentOrderID),
settlementDetails.leftTokenAddress,
settlementDetails.leftTokenFee,
0,
0x0
);
// Transfer the fee amount to the slasher
renExBalancesContract.transferBalanceWithFee(
orderbookContract.orderTrader(_guiltyOrderID),
slasherAddress,
settlementDetails.leftTokenAddress,
settlementDetails.leftTokenFee,
0,
0x0
);
}
/// @notice Retrieves the settlement details of an order.
/// For atomic swaps, it returns the full volumes, not the settled fees.
///
/// @param _orderID The order to lookup the details of. Can be the ID of a
/// buy or a sell order.
/// @return [
/// a boolean representing whether or not the order has been settled,
/// a boolean representing whether or not the order is a buy
/// the 32-byte order ID of the matched order
/// the volume of the priority token,
/// the volume of the secondary token,
/// the fee paid in the priority token,
/// the fee paid in the secondary token,
/// the token code of the priority token,
/// the token code of the secondary token
/// ]
function getMatchDetails(bytes32 _orderID)
external view returns (
bool settled,
bool orderIsBuy,
bytes32 matchedID,
uint256 priorityVolume,
uint256 secondaryVolume,
uint256 priorityFee,
uint256 secondaryFee,
uint32 priorityToken,
uint32 secondaryToken
) {
matchedID = orderbookContract.orderMatch(_orderID);
orderIsBuy = isBuyOrder(_orderID);
(bytes32 buyID, bytes32 sellID) = orderIsBuy ?
(_orderID, matchedID) : (matchedID, _orderID);
SettlementDetails memory settlementDetails = calculateSettlementDetails(
buyID,
sellID,
getTokenDetails(orderDetails[buyID].tokens)
);
return (
orderStatus[_orderID] == OrderStatus.Settled || orderStatus[_orderID] == OrderStatus.Slashed,
orderIsBuy,
matchedID,
settlementDetails.leftVolume,
settlementDetails.rightVolume,
settlementDetails.leftTokenFee,
settlementDetails.rightTokenFee,
uint32(orderDetails[buyID].tokens >> 32),
uint32(orderDetails[buyID].tokens)
);
}
/// @notice Exposes the hashOrder function for computing a hash of an
/// order's details. An order hash is used as its ID. See `submitOrder`
/// for the parameter descriptions.
///
/// @return The 32-byte hash of the order.
function hashOrder(
bytes _prefix,
uint64 _settlementID,
uint64 _tokens,
uint256 _price,
uint256 _volume,
uint256 _minimumVolume
) external pure returns (bytes32) {
return SettlementUtils.hashOrder(_prefix, SettlementUtils.OrderDetails({
settlementID: _settlementID,
tokens: _tokens,
price: _price,
volume: _volume,
minimumVolume: _minimumVolume
}));
}
/// @notice Called by `settle`, executes the settlement for a RenEx order
/// or distributes the fees for a RenExAtomic swap.
///
/// @param _buyID The 32 byte ID of the buy order.
/// @param _sellID The 32 byte ID of the sell order.
/// @param _buyer The address of the buy trader.
/// @param _seller The address of the sell trader.
/// @param _tokens The details of the priority and secondary tokens.
function execute(
bytes32 _buyID,
bytes32 _sellID,
address _buyer,
address _seller,
TokenPair memory _tokens
) private {
// Calculate the fees for atomic swaps, and the settlement details
// otherwise.
SettlementDetails memory settlementDetails = (orderDetails[_buyID].settlementID == RENEX_ATOMIC_SETTLEMENT_ID) ?
settlementDetails = calculateAtomicFees(_buyID, _sellID, _tokens) :
settlementDetails = calculateSettlementDetails(_buyID, _sellID, _tokens);
// Transfer priority token value
renExBalancesContract.transferBalanceWithFee(
_buyer,
_seller,
settlementDetails.leftTokenAddress,
settlementDetails.leftVolume,
settlementDetails.leftTokenFee,
orderSubmitter[_buyID]
);
// Transfer secondary token value
renExBalancesContract.transferBalanceWithFee(
_seller,
_buyer,
settlementDetails.rightTokenAddress,
settlementDetails.rightVolume,
settlementDetails.rightTokenFee,
orderSubmitter[_sellID]
);
}
/// @notice Calculates the details required to execute two matched orders.
///
/// @param _buyID The 32 byte ID of the buy order.
/// @param _sellID The 32 byte ID of the sell order.
/// @param _tokens The details of the priority and secondary tokens.
/// @return A struct containing the settlement details.
function calculateSettlementDetails(
bytes32 _buyID,
bytes32 _sellID,
TokenPair memory _tokens
) private view returns (SettlementDetails memory) {
// Calculate the mid-price (using numerator and denominator to not loose
// precision).
Fraction memory midPrice = Fraction(orderDetails[_buyID].price + orderDetails[_sellID].price, 2);
// Calculate the lower of the two max volumes of each trader
uint256 commonVolume = Math.min256(orderDetails[_buyID].volume, orderDetails[_sellID].volume);
uint256 priorityTokenVolume = joinFraction(
commonVolume.mul(midPrice.numerator),
midPrice.denominator,
int16(_tokens.priorityToken.decimals) - PRICE_OFFSET - VOLUME_OFFSET
);
uint256 secondaryTokenVolume = joinFraction(
commonVolume,
1,
int16(_tokens.secondaryToken.decimals) - VOLUME_OFFSET
);
// Calculate darknode fees
ValueWithFees memory priorityVwF = subtractDarknodeFee(priorityTokenVolume);
ValueWithFees memory secondaryVwF = subtractDarknodeFee(secondaryTokenVolume);
return SettlementDetails({
leftVolume: priorityVwF.value,
rightVolume: secondaryVwF.value,
leftTokenFee: priorityVwF.fees,
rightTokenFee: secondaryVwF.fees,
leftTokenAddress: _tokens.priorityToken.addr,
rightTokenAddress: _tokens.secondaryToken.addr
});
}
/// @notice Calculates the fees to be transferred for an atomic swap.
///
/// @param _buyID The 32 byte ID of the buy order.
/// @param _sellID The 32 byte ID of the sell order.
/// @param _tokens The details of the priority and secondary tokens.
/// @return A struct containing the fee details.
function calculateAtomicFees(
bytes32 _buyID,
bytes32 _sellID,
TokenPair memory _tokens
) private view returns (SettlementDetails memory) {
// Calculate the mid-price (using numerator and denominator to not loose
// precision).
Fraction memory midPrice = Fraction(orderDetails[_buyID].price + orderDetails[_sellID].price, 2);
// Calculate the lower of the two max volumes of each trader
uint256 commonVolume = Math.min256(orderDetails[_buyID].volume, orderDetails[_sellID].volume);
if (isEthereumBased(_tokens.secondaryToken.addr)) {
uint256 secondaryTokenVolume = joinFraction(
commonVolume,
1,
int16(_tokens.secondaryToken.decimals) - VOLUME_OFFSET
);
// Calculate darknode fees
ValueWithFees memory secondaryVwF = subtractDarknodeFee(secondaryTokenVolume);
return SettlementDetails({
leftVolume: 0,
rightVolume: 0,
leftTokenFee: secondaryVwF.fees,
rightTokenFee: secondaryVwF.fees,
leftTokenAddress: _tokens.secondaryToken.addr,
rightTokenAddress: _tokens.secondaryToken.addr
});
} else if (isEthereumBased(_tokens.priorityToken.addr)) {
uint256 priorityTokenVolume = joinFraction(
commonVolume.mul(midPrice.numerator),
midPrice.denominator,
int16(_tokens.priorityToken.decimals) - PRICE_OFFSET - VOLUME_OFFSET
);
// Calculate darknode fees
ValueWithFees memory priorityVwF = subtractDarknodeFee(priorityTokenVolume);
return SettlementDetails({
leftVolume: 0,
rightVolume: 0,
leftTokenFee: priorityVwF.fees,
rightTokenFee: priorityVwF.fees,
leftTokenAddress: _tokens.priorityToken.addr,
rightTokenAddress: _tokens.priorityToken.addr
});
} else {
// Currently, at least one token must be Ethereum-based.
// This will be implemented in the future.
revert("non-eth atomic swaps are not supported");
}
}
/// @notice Order parity is set by the order tokens are listed. This returns
/// whether an order is a buy or a sell.
/// @return true if _orderID is a buy order.
function isBuyOrder(bytes32 _orderID) private view returns (bool) {
uint64 tokens = orderDetails[_orderID].tokens;
uint32 firstToken = uint32(tokens >> 32);
uint32 secondaryToken = uint32(tokens);
return (firstToken < secondaryToken);
}
/// @return (value - fee, fee) where fee is 0.2% of value
function subtractDarknodeFee(uint256 _value) private pure returns (ValueWithFees memory) {
uint256 newValue = (_value * (DARKNODE_FEES_DENOMINATOR - DARKNODE_FEES_NUMERATOR)) / DARKNODE_FEES_DENOMINATOR;
return ValueWithFees(newValue, _value - newValue);
}
/// @notice Gets the order details of the priority and secondary token from
/// the RenExTokens contract and returns them as a single struct.
///
/// @param _tokens The 64-bit combined token identifiers.
/// @return A TokenPair struct containing two TokenDetails structs.
function getTokenDetails(uint64 _tokens) private view returns (TokenPair memory) {
(
address priorityAddress,
uint8 priorityDecimals,
bool priorityRegistered
) = renExTokensContract.tokens(uint32(_tokens >> 32));
(
address secondaryAddress,
uint8 secondaryDecimals,
bool secondaryRegistered
) = renExTokensContract.tokens(uint32(_tokens));
return TokenPair({
priorityToken: RenExTokens.TokenDetails(priorityAddress, priorityDecimals, priorityRegistered),
secondaryToken: RenExTokens.TokenDetails(secondaryAddress, secondaryDecimals, secondaryRegistered)
});
}
/// @return true if _tokenAddress is 0x0, representing a token that is not
/// on Ethereum
function isEthereumBased(address _tokenAddress) private pure returns (bool) {
return (_tokenAddress != address(0x0));
}
/// @notice Computes (_numerator / _denominator) * 10 ** _scale
function joinFraction(uint256 _numerator, uint256 _denominator, int16 _scale) private pure returns (uint256) {
if (_scale >= 0) {
// Check that (10**_scale) doesn't overflow
assert(_scale <= 77); // log10(2**256) = 77.06
return _numerator.mul(10 ** uint256(_scale)) / _denominator;
} else {
/// @dev If _scale is less than -77, 10**-_scale would overflow.
// For now, -_scale > -24 (when a token has 0 decimals and
// VOLUME_OFFSET and PRICE_OFFSET are each 12). It is unlikely these
// will be increased to add to more than 77.
// assert((-_scale) <= 77); // log10(2**256) = 77.06
return (_numerator / _denominator) / 10 ** uint256(-_scale);
}
}
}
/// @notice RenExBrokerVerifier implements the BrokerVerifier contract,
/// verifying broker signatures for order opening and fund withdrawal.
contract RenExBrokerVerifier is Ownable {
string public VERSION; // Passed in as a constructor parameter.
// Events
event LogBalancesContractUpdated(address previousBalancesContract, address nextBalancesContract);
event LogBrokerRegistered(address broker);
event LogBrokerDeregistered(address broker);
// Storage
mapping(address => bool) public brokers;
mapping(address => uint256) public traderNonces;
address public balancesContract;
modifier onlyBalancesContract() {
require(msg.sender == balancesContract, "not authorized");
_;
}
/// @notice The contract constructor.
///
/// @param _VERSION A string defining the contract version.
constructor(string _VERSION) public {
VERSION = _VERSION;
}
/// @notice Allows the owner of the contract to update the address of the
/// RenExBalances contract.
///
/// @param _balancesContract The address of the new balances contract
function updateBalancesContract(address _balancesContract) external onlyOwner {
emit LogBalancesContractUpdated(balancesContract, _balancesContract);
balancesContract = _balancesContract;
}
/// @notice Approved an address to sign order-opening and withdrawals.
/// @param _broker The address of the broker.
function registerBroker(address _broker) external onlyOwner {
require(!brokers[_broker], "already registered");
brokers[_broker] = true;
emit LogBrokerRegistered(_broker);
}
/// @notice Reverts the a broker's registration.
/// @param _broker The address of the broker.
function deregisterBroker(address _broker) external onlyOwner {
require(brokers[_broker], "not registered");
brokers[_broker] = false;
emit LogBrokerDeregistered(_broker);
}
/// @notice Verifies a broker's signature for an order opening.
/// The data signed by the broker is a prefixed message and the order ID.
///
/// @param _trader The trader requesting the withdrawal.
/// @param _signature The 65-byte signature from the broker.
/// @param _orderID The 32-byte order ID.
/// @return True if the signature is valid, false otherwise.
function verifyOpenSignature(
address _trader,
bytes _signature,
bytes32 _orderID
) external view returns (bool) {
bytes memory data = abi.encodePacked("Republic Protocol: open: ", _trader, _orderID);
address signer = Utils.addr(data, _signature);
return (brokers[signer] == true);
}
/// @notice Verifies a broker's signature for a trader withdrawal.
/// The data signed by the broker is a prefixed message, the trader address
/// and a 256-bit trader nonce, which is incremented every time a valid
/// signature is checked.
///
/// @param _trader The trader requesting the withdrawal.
/// @param _signature 65-byte signature from the broker.
/// @return True if the signature is valid, false otherwise.
function verifyWithdrawSignature(
address _trader,
bytes _signature
) external onlyBalancesContract returns (bool) {
bytes memory data = abi.encodePacked("Republic Protocol: withdraw: ", _trader, traderNonces[_trader]);
address signer = Utils.addr(data, _signature);
if (brokers[signer]) {
traderNonces[_trader] += 1;
return true;
}
return false;
}
}
/// @notice RenExBalances is responsible for holding RenEx trader funds.
contract RenExBalances is Ownable {
using SafeMath for uint256;
using CompatibleERC20Functions for CompatibleERC20;
string public VERSION; // Passed in as a constructor parameter.
RenExSettlement public settlementContract;
RenExBrokerVerifier public brokerVerifierContract;
DarknodeRewardVault public rewardVaultContract;
/// @dev Should match the address in the DarknodeRewardVault
address constant public ETHEREUM = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
// Delay between a trader calling `withdrawSignal` and being able to call
// `withdraw` without a broker signature.
uint256 constant public SIGNAL_DELAY = 48 hours;
// Events
event LogBalanceDecreased(address trader, ERC20 token, uint256 value);
event LogBalanceIncreased(address trader, ERC20 token, uint256 value);
event LogRenExSettlementContractUpdated(address previousRenExSettlementContract, address newRenExSettlementContract);
event LogRewardVaultContractUpdated(address previousRewardVaultContract, address newRewardVaultContract);
event LogBrokerVerifierContractUpdated(address previousBrokerVerifierContract, address newBrokerVerifierContract);
// Storage
mapping(address => mapping(address => uint256)) public traderBalances;
mapping(address => mapping(address => uint256)) public traderWithdrawalSignals;
/// @notice The contract constructor.
///
/// @param _VERSION A string defining the contract version.
/// @param _rewardVaultContract The address of the RewardVault contract.
constructor(
string _VERSION,
DarknodeRewardVault _rewardVaultContract,
RenExBrokerVerifier _brokerVerifierContract
) public {
VERSION = _VERSION;
rewardVaultContract = _rewardVaultContract;
brokerVerifierContract = _brokerVerifierContract;
}
/// @notice Restricts a function to only being called by the RenExSettlement
/// contract.
modifier onlyRenExSettlementContract() {
require(msg.sender == address(settlementContract), "not authorized");
_;
}
/// @notice Restricts trader withdrawing to be called if a signature from a
/// RenEx broker is provided, or if a certain amount of time has passed
/// since a trader has called `signalBackupWithdraw`.
/// @dev If the trader is withdrawing after calling `signalBackupWithdraw`,
/// this will reset the time to zero, writing to storage.
modifier withBrokerSignatureOrSignal(address _token, bytes _signature) {
address trader = msg.sender;
// If a signature has been provided, verify it - otherwise, verify that
// the user has signalled the withdraw
if (_signature.length > 0) {
require (brokerVerifierContract.verifyWithdrawSignature(trader, _signature), "invalid signature");
} else {
require(traderWithdrawalSignals[trader][_token] != 0, "not signalled");
/* solium-disable-next-line security/no-block-members */
require((now - traderWithdrawalSignals[trader][_token]) > SIGNAL_DELAY, "signal time remaining");
traderWithdrawalSignals[trader][_token] = 0;
}
_;
}
/// @notice Allows the owner of the contract to update the address of the
/// RenExSettlement contract.
///
/// @param _newSettlementContract the address of the new settlement contract
function updateRenExSettlementContract(RenExSettlement _newSettlementContract) external onlyOwner {
emit LogRenExSettlementContractUpdated(settlementContract, _newSettlementContract);
settlementContract = _newSettlementContract;
}
/// @notice Allows the owner of the contract to update the address of the
/// DarknodeRewardVault contract.
///
/// @param _newRewardVaultContract the address of the new reward vault contract
function updateRewardVaultContract(DarknodeRewardVault _newRewardVaultContract) external onlyOwner {
emit LogRewardVaultContractUpdated(rewardVaultContract, _newRewardVaultContract);
rewardVaultContract = _newRewardVaultContract;
}
/// @notice Allows the owner of the contract to update the address of the
/// RenExBrokerVerifier contract.
///
/// @param _newBrokerVerifierContract the address of the new broker verifier contract
function updateBrokerVerifierContract(RenExBrokerVerifier _newBrokerVerifierContract) external onlyOwner {
emit LogBrokerVerifierContractUpdated(brokerVerifierContract, _newBrokerVerifierContract);
brokerVerifierContract = _newBrokerVerifierContract;
}
/// @notice Transfer a token value from one trader to another, transferring
/// a fee to the RewardVault. Can only be called by the RenExSettlement
/// contract.
///
/// @param _traderFrom The address of the trader to decrement the balance of.
/// @param _traderTo The address of the trader to increment the balance of.
/// @param _token The token's address.
/// @param _value The number of tokens to decrement the balance by (in the
/// token's smallest unit).
/// @param _fee The fee amount to forward on to the RewardVault.
/// @param _feePayee The recipient of the fee.
function transferBalanceWithFee(address _traderFrom, address _traderTo, address _token, uint256 _value, uint256 _fee, address _feePayee)
external onlyRenExSettlementContract {
require(traderBalances[_traderFrom][_token] >= _fee, "insufficient funds for fee");
if (address(_token) == ETHEREUM) {
rewardVaultContract.deposit.value(_fee)(_feePayee, ERC20(_token), _fee);
} else {
CompatibleERC20(_token).safeApprove(rewardVaultContract, _fee);
rewardVaultContract.deposit(_feePayee, ERC20(_token), _fee);
}
privateDecrementBalance(_traderFrom, ERC20(_token), _value + _fee);
if (_value > 0) {
privateIncrementBalance(_traderTo, ERC20(_token), _value);
}
}
/// @notice Deposits ETH or an ERC20 token into the contract.
///
/// @param _token The token's address (must be a registered token).
/// @param _value The amount to deposit in the token's smallest unit.
function deposit(ERC20 _token, uint256 _value) external payable {
address trader = msg.sender;
uint256 receivedValue = _value;
if (address(_token) == ETHEREUM) {
require(msg.value == _value, "mismatched value parameter and tx value");
} else {
require(msg.value == 0, "unexpected ether transfer");
receivedValue = CompatibleERC20(_token).safeTransferFromWithFees(trader, this, _value);
}
privateIncrementBalance(trader, _token, receivedValue);
}
/// @notice Withdraws ETH or an ERC20 token from the contract. A broker
/// signature is required to guarantee that the trader has a sufficient
/// balance after accounting for open orders. As a trustless backup,
/// traders can withdraw 48 hours after calling `signalBackupWithdraw`.
///
/// @param _token The token's address.
/// @param _value The amount to withdraw in the token's smallest unit.
/// @param _signature The broker signature
function withdraw(ERC20 _token, uint256 _value, bytes _signature) external withBrokerSignatureOrSignal(_token, _signature) {
address trader = msg.sender;
privateDecrementBalance(trader, _token, _value);
if (address(_token) == ETHEREUM) {
trader.transfer(_value);
} else {
CompatibleERC20(_token).safeTransfer(trader, _value);
}
}
/// @notice A trader can withdraw without needing a broker signature if they
/// first call `signalBackupWithdraw` for the token they want to withdraw.
/// The trader can only withdraw the particular token once for each call to
/// this function. Traders can signal the intent to withdraw multiple
/// tokens.
/// Once this function is called, brokers will not sign order-opens for the
/// trader until the trader has withdrawn, guaranteeing that they won't have
/// orders open for the particular token.
function signalBackupWithdraw(address _token) external {
/* solium-disable-next-line security/no-block-members */
traderWithdrawalSignals[msg.sender][_token] = now;
}
function privateIncrementBalance(address _trader, ERC20 _token, uint256 _value) private {
traderBalances[_trader][_token] = traderBalances[_trader][_token].add(_value);
emit LogBalanceIncreased(_trader, _token, _value);
}
function privateDecrementBalance(address _trader, ERC20 _token, uint256 _value) private {
require(traderBalances[_trader][_token] >= _value, "insufficient funds");
traderBalances[_trader][_token] = traderBalances[_trader][_token].sub(_value);
emit LogBalanceDecreased(_trader, _token, _value);
}
}
|
Verifies that two orders match when considering the tokens, price, volumes / minimum volumes and settlement IDs. verifyMatchDetails is used my the DarknodeSlasher to verify challenges. Settlement layers may also use this function. When verifying two orders for settlement, you should also: 1) verify the orders have been confirmed together 2) verify the orders' traders are distinct _buy The buy order details. _sell The sell order details. Buy and sell tokens should match Buy price should be greater than sell price Buy volume should be greater than sell minimum volume Sell volume should be greater than buy minimum volume Require that the orders were submitted to the same settlement layer
|
function verifyMatchDetails(OrderDetails memory _buy, OrderDetails memory _sell) internal pure returns (bool) {
if (!verifyTokens(_buy.tokens, _sell.tokens)) {
return false;
}
if (_buy.price < _sell.price) {
return false;
}
if (_buy.volume < _sell.minimumVolume) {
return false;
}
if (_sell.volume < _buy.minimumVolume) {
return false;
}
if (_buy.settlementID != _sell.settlementID) {
return false;
}
return true;
}
| 1,044,504
|
./full_match/4/0xcD7799Cf329b25210189719a1bFe9b1b01A14004/sources/contracts/MultiTokenTradingContract.sol
|
The stakeInternal function is the function which handles investment into a MultiTokenTradingContract. Theamount invested will be saved in the form of a fraction which corresponds to the amount invested corrected by pastprofit of the contract.The wallets and walletsArray will hold all wallets which have staked in the TradingContract.The amount invested will be swapped to the current allocations of the PairedTokens. The rest will remain in BaseToken.
|
function stakeInternal(uint256 amount) internal {
require(amount > 0);
uint256 oldTotalSupply = getTotalSupply().sub(amount);
if (!wallets[msg.sender]) {
if (!walletHasInvested[msg.sender]) {
walletsArray.push(msg.sender);
walletHasInvested[msg.sender]=true;
}
wallets[msg.sender]=true;
}
totalInvested = totalInvested.add(amount);
totalInvestedInBNB = totalInvestedInBNB.add(getAmountOutMin(baseTokenAddress, WETHAddress, amount,true));
invested[msg.sender] = invested[msg.sender].add(amount);
investedInUSD[msg.sender] = investedInUSD[msg.sender].add(getAmountOutMin(baseTokenAddress, BUSDAddress, amount,false));
investedInBNB[msg.sender] = investedInBNB[msg.sender].add(getAmountOutMin(baseTokenAddress, WETHAddress, amount,true));
require(totalInvestedInBNB <= maxTotalCap, "Max total cap");
for (uint i=0; i < pairedTokenArray.length; i++) {
swapAutoSlippage(baseTokenAddress,
pairedTokens[pairedTokenArray[i]].tokenAddress,
amount.mul(pairedTokens[pairedTokenArray[i]].maxAllocation.mul(UNITY.sub(pairedTokens[pairedTokenArray[i]].currentAvailableAllocation))).div(UNITY).div(UNITY),
pairedTokens[pairedTokenArray[i]].directPath);
}
uint256 totalSupply = getTotalSupply();
if (oldTotalSupply == 0){
_init_fraction = totalSupply.sub(oldTotalSupply);
_init_fraction = totalSupply.sub(oldTotalSupply).mul(totalFractions).div(oldTotalSupply);
}
for (uint i=0; i < pairedTokenArray.length; i++) {
_totalBalance = _totalBalance.add(
getAmountOutMin(pairedTokens[pairedTokenArray[i]].tokenAddress,baseTokenAddress,
pairedTokens[pairedTokenArray[i]].token.balanceOf(address(this))
.mul(_init_fraction).div(totalFractions.add(_init_fraction)),pairedTokens[pairedTokenArray[i]].directPath));
}
uint256 _updatedOldValue = totalSupply.sub(_amountIn);
uint256 newFraction;
if (_updatedOldValue == 0){
newFraction = _amountIn;
}
else{
newFraction = _amountIn.mul(totalFractions).div(_updatedOldValue);
}
fractions[msg.sender] = fractions[msg.sender].add(newFraction);
totalFractions = totalFractions.add(newFraction);
emit Staked(msg.sender, amount);
}
| 757,005
|
pragma solidity ^0.4.14;
// Contract for storing legal Scenario's on the blockchain
//
// Author: Ben Rogmans
//
contract Scenario {
bytes32 public name;
uint public lastVersion;
address public creator;
mapping(uint => Version) public versions;
struct Version
{
uint effectiveDate;
string content;
}
// require msg.sender == publisher
modifier creatorOnly {
if(msg.sender != creator) {
revert();
} else {
_;
}
}
// Create the contract
function Scenario(bytes32 _name) public {
name = _name;
creator = msg.sender;
}
// Publish a new Scenario
function publishScenarioVersion(uint _effectiveDate, string _content) creatorOnly public {
// Only newer versions can be published
if(_effectiveDate <= lastVersion) revert();
versions[_effectiveDate] = Version({
effectiveDate: _effectiveDate,
content: _content
});
lastVersion = _effectiveDate;
}
function getScenario(uint _version) public constant returns(string) {
return(versions[_version].content);
}
}
|
Create the contract
|
function Scenario(bytes32 _name) public {
name = _name;
creator = msg.sender;
}
| 12,804,987
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../interfaces/INFTComplexGemPoolData.sol";
import "../interfaces/ISwapQueryHelper.sol";
import "../interfaces/INFTGemMultiToken.sol";
import "../interfaces/INFTGemGovernor.sol";
import "../interfaces/INFTComplexGemPool.sol";
import "../interfaces/INFTGemFeeManager.sol";
import "../libs/AddressSet.sol";
library ComplexPoolLib {
using AddressSet for AddressSet.Set;
/**
* @dev Event generated when an NFT claim is created using base currency
*/
event NFTGemClaimCreated(
address indexed account,
address indexed pool,
uint256 indexed claimHash,
uint256 length,
uint256 quantity,
uint256 amountPaid
);
/**
* @dev Event generated when an NFT claim is created using ERC20 tokens
*/
event NFTGemERC20ClaimCreated(
address indexed account,
address indexed pool,
uint256 indexed claimHash,
uint256 length,
address token,
uint256 quantity,
uint256 conversionRate
);
/**
* @dev Event generated when an NFT claim is redeemed
*/
event NFTGemClaimRedeemed(
address indexed account,
address indexed pool,
uint256 indexed claimHash,
uint256 amountPaid,
uint256 quantity,
uint256 feeAssessed
);
/**
* @dev Event generated when an NFT erc20 claim is redeemed
*/
event NFTGemERC20ClaimRedeemed(
address indexed account,
address indexed pool,
uint256 indexed claimHash,
address token,
uint256 ethPrice,
uint256 tokenAmount,
uint256 quantity,
uint256 feeAssessed
);
/**
* @dev Event generated when a gem is created
*/
event NFTGemCreated(
address account,
address pool,
uint256 claimHash,
uint256 gemHash,
uint256 quantity
);
/**
* @dev data describes complex pool
*/
struct ComplexPoolData {
// governor and multitoken target
address pool;
address multitoken;
address governor;
address feeTracker;
address swapHelper;
uint256 category;
bool visible;
// it all starts with a symbol and a nams
string symbol;
string name;
string description;
// magic economy numbers
uint256 ethPrice;
uint256 minTime;
uint256 maxTime;
uint256 diffstep;
uint256 maxClaims;
uint256 maxQuantityPerClaim;
uint256 maxClaimsPerAccount;
bool validateerc20;
bool allowPurchase;
bool enabled;
INFTComplexGemPoolData.PriceIncrementType priceIncrementType;
mapping(uint256 => INFTGemMultiToken.TokenType) tokenTypes;
mapping(uint256 => uint256) tokenIds;
mapping(uint256 => address) tokenSources;
AddressSet.Set allowedTokenSources;
uint256[] tokenHashes;
// next ids of things
uint256 nextGemIdVal;
uint256 nextClaimIdVal;
uint256 totalStakedEth;
// records claim timestamp / ETH value / ERC token and amount sent
mapping(uint256 => uint256) claimLockTimestamps;
mapping(uint256 => address) claimLockToken;
mapping(uint256 => uint256) claimAmountPaid;
mapping(uint256 => uint256) claimQuant;
mapping(uint256 => uint256) claimTokenAmountPaid;
mapping(uint256 => mapping(address => uint256)) importedLegacyToken;
// input NFTs storage
mapping(uint256 => uint256) gemClaims;
mapping(uint256 => uint256[]) claimIds;
mapping(uint256 => uint256[]) claimQuantities;
mapping(address => bool) controllers;
mapping(address => uint256) claimsMade;
INFTComplexGemPoolData.InputRequirement[] inputRequirements;
AddressSet.Set allowedTokens;
}
function checkGemRequirement(
ComplexPoolData storage self,
uint256 _inputIndex,
address _holderAddress,
uint256 _quantity
) internal view returns (address) {
address gemtoken;
int256 required = int256(
self.inputRequirements[_inputIndex].minVal * _quantity
);
uint256[] memory hashes = INFTGemMultiToken(
self.inputRequirements[_inputIndex].token
).heldTokens(_holderAddress);
for (
uint256 _hashIndex = 0;
_hashIndex < hashes.length;
_hashIndex += 1
) {
uint256 hashAt = hashes[_hashIndex];
if (
INFTComplexGemPoolData(self.inputRequirements[_inputIndex].pool)
.tokenType(hashAt) == INFTGemMultiToken.TokenType.GEM
) {
gemtoken = self.inputRequirements[_inputIndex].token;
uint256 balance = IERC1155(
self.inputRequirements[_inputIndex].token
).balanceOf(_holderAddress, hashAt);
if (balance > uint256(required)) {
balance = uint256(required);
}
if (balance == 0) {
continue;
}
required = required - int256(balance);
}
if (
required == 0 &&
self.inputRequirements[_inputIndex].exactAmount == false
) {
break;
}
if (required < 0) {
require(required == 0, "EXACT_AMOUNT_REQUIRED");
}
}
require(required == 0, "UNMET_GEM_REQUIREMENT");
return gemtoken;
}
/**
* @dev checks to see that account owns all the pool requirements needed to mint at least the given quantity of NFT
*/
function requireInputReqs(
ComplexPoolData storage self,
address _holderAddress,
uint256 _quantity
) public view {
for (
uint256 _inputIndex = 0;
_inputIndex < self.inputRequirements.length;
_inputIndex += 1
) {
if (
self.inputRequirements[_inputIndex].inputType ==
INFTComplexGemPool.RequirementType.ERC20
) {
require(
IERC20(self.inputRequirements[_inputIndex].token).balanceOf(
_holderAddress
) >=
self.inputRequirements[_inputIndex].minVal *
(_quantity),
"UNMET_ERC20_REQUIREMENT"
);
} else if (
self.inputRequirements[_inputIndex].inputType ==
INFTComplexGemPool.RequirementType.ERC1155
) {
require(
IERC1155(self.inputRequirements[_inputIndex].token)
.balanceOf(
_holderAddress,
self.inputRequirements[_inputIndex].tokenId
) >=
self.inputRequirements[_inputIndex].minVal *
(_quantity),
"UNMET_ERC1155_REQUIREMENT"
);
} else if (
self.inputRequirements[_inputIndex].inputType ==
INFTComplexGemPool.RequirementType.POOL
) {
checkGemRequirement(
self,
_inputIndex,
_holderAddress,
_quantity
);
}
}
}
/**
* @dev Transfer a quantity of input reqs from to
*/
function takeInputReqsFrom(
ComplexPoolData storage self,
uint256 _claimHash,
address _fromAddress,
uint256 _quantity
) internal {
address gemtoken;
for (
uint256 _inputIndex = 0;
_inputIndex < self.inputRequirements.length;
_inputIndex += 1
) {
if (!self.inputRequirements[_inputIndex].takeCustody) {
continue;
}
if (
self.inputRequirements[_inputIndex].inputType ==
INFTComplexGemPool.RequirementType.ERC20
) {
IERC20 token = IERC20(
self.inputRequirements[_inputIndex].token
);
token.transferFrom(
_fromAddress,
self.pool,
self.inputRequirements[_inputIndex].minVal * (_quantity)
);
} else if (
self.inputRequirements[_inputIndex].inputType ==
INFTComplexGemPool.RequirementType.ERC1155
) {
IERC1155 token = IERC1155(
self.inputRequirements[_inputIndex].token
);
token.safeTransferFrom(
_fromAddress,
self.pool,
self.inputRequirements[_inputIndex].tokenId,
self.inputRequirements[_inputIndex].minVal * (_quantity),
""
);
} else if (
self.inputRequirements[_inputIndex].inputType ==
INFTComplexGemPool.RequirementType.POOL
) {
gemtoken = checkGemRequirement(
self,
_inputIndex,
_fromAddress,
_quantity
);
}
}
if (self.claimIds[_claimHash].length > 0 && gemtoken != address(0)) {
IERC1155(gemtoken).safeBatchTransferFrom(
_fromAddress,
self.pool,
self.claimIds[_claimHash],
self.claimQuantities[_claimHash],
""
);
}
}
/**
* @dev Return the returnable input requirements for claimhash to account
*/
function returnInputReqsTo(
ComplexPoolData storage self,
uint256 _claimHash,
address _toAddress,
uint256 _quantity
) internal {
address gemtoken;
for (uint256 i = 0; i < self.inputRequirements.length; i++) {
if (
self.inputRequirements[i].inputType ==
INFTComplexGemPool.RequirementType.ERC20 &&
self.inputRequirements[i].burn == false &&
self.inputRequirements[i].takeCustody == true
) {
IERC20 token = IERC20(self.inputRequirements[i].token);
token.transferFrom(
self.pool,
_toAddress,
self.inputRequirements[i].minVal * (_quantity)
);
} else if (
self.inputRequirements[i].inputType ==
INFTComplexGemPool.RequirementType.ERC1155 &&
self.inputRequirements[i].burn == false &&
self.inputRequirements[i].takeCustody == true
) {
IERC1155 token = IERC1155(self.inputRequirements[i].token);
token.safeTransferFrom(
self.pool,
_toAddress,
self.inputRequirements[i].tokenId,
self.inputRequirements[i].minVal * (_quantity),
""
);
} else if (
self.inputRequirements[i].inputType ==
INFTComplexGemPool.RequirementType.POOL &&
self.inputRequirements[i].burn == false &&
self.inputRequirements[i].takeCustody == true
) {
gemtoken = self.inputRequirements[i].token;
}
}
if (self.claimIds[_claimHash].length > 0 && gemtoken != address(0)) {
IERC1155(gemtoken).safeBatchTransferFrom(
self.pool,
_toAddress,
self.claimIds[_claimHash],
self.claimQuantities[_claimHash],
""
);
}
}
/**
* @dev add an input requirement for this token
*/
function addInputRequirement(
ComplexPoolData storage self,
address token,
address pool,
INFTComplexGemPool.RequirementType inputType,
uint256 tokenId,
uint256 minAmount,
bool takeCustody,
bool burn,
bool exactAmount
) public {
require(token != address(0), "INVALID_TOKEN");
require(
inputType == INFTComplexGemPool.RequirementType.ERC20 ||
inputType == INFTComplexGemPool.RequirementType.ERC1155 ||
inputType == INFTComplexGemPool.RequirementType.POOL,
"INVALID_INPUTTYPE"
);
require(
(inputType == INFTComplexGemPool.RequirementType.POOL &&
pool != address(0)) ||
inputType != INFTComplexGemPool.RequirementType.POOL,
"INVALID_POOL"
);
require(
(inputType == INFTComplexGemPool.RequirementType.ERC20 &&
tokenId == 0) ||
inputType == INFTComplexGemPool.RequirementType.ERC1155 ||
(inputType == INFTComplexGemPool.RequirementType.POOL &&
tokenId == 0),
"INVALID_TOKENID"
);
require(minAmount != 0, "ZERO_AMOUNT");
require(!(!takeCustody && burn), "INVALID_TOKENSTATE");
self.inputRequirements.push(
INFTComplexGemPoolData.InputRequirement(
token,
pool,
inputType,
tokenId,
minAmount,
takeCustody,
burn,
exactAmount
)
);
}
/**
* @dev update input requirement at index
*/
function updateInputRequirement(
ComplexPoolData storage self,
uint256 _index,
address _tokenAddress,
address _poolAddress,
INFTComplexGemPool.RequirementType _inputRequirementType,
uint256 _tokenId,
uint256 _minAmount,
bool _takeCustody,
bool _burn,
bool _exactAmount
) public {
require(_index < self.inputRequirements.length, "OUT_OF_RANGE");
require(_tokenAddress != address(0), "INVALID_TOKEN");
require(
_inputRequirementType == INFTComplexGemPool.RequirementType.ERC20 ||
_inputRequirementType ==
INFTComplexGemPool.RequirementType.ERC1155 ||
_inputRequirementType ==
INFTComplexGemPool.RequirementType.POOL,
"INVALID_INPUTTYPE"
);
require(
(_inputRequirementType == INFTComplexGemPool.RequirementType.POOL &&
_poolAddress != address(0)) ||
_inputRequirementType !=
INFTComplexGemPool.RequirementType.POOL,
"INVALID_POOL"
);
require(
(_inputRequirementType ==
INFTComplexGemPool.RequirementType.ERC20 &&
_tokenId == 0) ||
_inputRequirementType ==
INFTComplexGemPool.RequirementType.ERC1155 ||
(_inputRequirementType ==
INFTComplexGemPool.RequirementType.POOL &&
_tokenId == 0),
"INVALID_TOKENID"
);
require(_minAmount != 0, "ZERO_AMOUNT");
require(!(!_takeCustody && _burn), "INVALID_TOKENSTATE");
self.inputRequirements[_index] = INFTComplexGemPoolData
.InputRequirement(
_tokenAddress,
_poolAddress,
_inputRequirementType,
_tokenId,
_minAmount,
_takeCustody,
_burn,
_exactAmount
);
}
/**
* @dev count of input requirements
*/
function allInputRequirementsLength(ComplexPoolData storage self)
public
view
returns (uint256)
{
return self.inputRequirements.length;
}
/**
* @dev input requirements at index
*/
function allInputRequirements(ComplexPoolData storage self, uint256 _index)
public
view
returns (
address,
address,
INFTComplexGemPool.RequirementType,
uint256,
uint256,
bool,
bool,
bool
)
{
require(_index < self.inputRequirements.length, "OUT_OF_RANGE");
INFTComplexGemPoolData.InputRequirement memory req = self
.inputRequirements[_index];
return (
req.token,
req.pool,
req.inputType,
req.tokenId,
req.minVal,
req.takeCustody,
req.burn,
req.exactAmount
);
}
/**
* @dev attempt to create a claim using the given timeframe with count
*/
function createClaims(
ComplexPoolData storage self,
uint256 _timeframe,
uint256 _count
) public {
// enabled
require(self.enabled == true, "DISABLED");
// minimum timeframe
require(_timeframe >= self.minTime, "TIMEFRAME_TOO_SHORT");
// no ETH
require(msg.value != 0, "ZERO_BALANCE");
// zero qty
require(_count != 0, "ZERO_QUANTITY");
// maximum timeframe
require(
(self.maxTime != 0 && _timeframe <= self.maxTime) ||
self.maxTime == 0,
"TIMEFRAME_TOO_LONG"
);
// max quantity per claim
require(
(self.maxQuantityPerClaim != 0 &&
_count <= self.maxQuantityPerClaim) ||
self.maxQuantityPerClaim == 0,
"MAX_QUANTITY_EXCEEDED"
);
require(
(self.maxClaimsPerAccount != 0 &&
self.claimsMade[msg.sender] < self.maxClaimsPerAccount) ||
self.maxClaimsPerAccount == 0,
"MAX_QUANTITY_EXCEEDED"
);
uint256 adjustedBalance = msg.value / (_count);
// cost given this timeframe
uint256 cost = (self.ethPrice * (self.minTime)) / (_timeframe);
require(adjustedBalance >= cost, "INSUFFICIENT_ETH");
// get the nest claim hash, revert if no more claims
uint256 claimHash = nextClaimHash(self);
require(claimHash != 0, "NO_MORE_CLAIMABLE");
// require the user to have the input requirements
requireInputReqs(self, msg.sender, _count);
// mint the new claim to the caller's address
INFTGemMultiToken(self.multitoken).mint(msg.sender, claimHash, 1);
INFTGemMultiToken(self.multitoken).setTokenData(
claimHash,
INFTGemMultiToken.TokenType.CLAIM,
address(this)
);
addToken(self, claimHash, INFTGemMultiToken.TokenType.CLAIM);
// record the claim unlock time and cost paid for this claim
uint256 claimUnlockTimestamp = block.timestamp + (_timeframe);
self.claimLockTimestamps[claimHash] = claimUnlockTimestamp;
self.claimAmountPaid[claimHash] = cost * (_count);
self.claimQuant[claimHash] = _count;
self.claimsMade[msg.sender] = self.claimsMade[msg.sender] + (1);
// tranasfer NFT input requirements from user to pool
takeInputReqsFrom(self, claimHash, msg.sender, _count);
// emit an event about it
emit NFTGemClaimCreated(
msg.sender,
address(self.pool),
claimHash,
_timeframe,
_count,
cost
);
// increase the staked eth balance
self.totalStakedEth = self.totalStakedEth + (cost * (_count));
// return the extra to sender
if (msg.value > cost * (_count)) {
(bool success, ) = payable(msg.sender).call{
value: msg.value - (cost * (_count))
}("");
require(success, "REFUND_FAILED");
}
}
function getPoolFee(ComplexPoolData storage self, address tokenUsed)
internal
view
returns (uint256)
{
// get the fee for this pool if it exists
uint256 poolDivFeeHash = uint256(
keccak256(abi.encodePacked("pool_fee", address(self.pool)))
);
uint256 poolFee = INFTGemFeeManager(self.feeTracker).fee(
poolDivFeeHash
);
// get the pool fee for this token if it exists
uint256 poolTokenFeeHash = uint256(
keccak256(abi.encodePacked("pool_fee", address(tokenUsed)))
);
uint256 poolTokenFee = INFTGemFeeManager(self.feeTracker).fee(
poolTokenFeeHash
);
// get the default fee amoutn for this token
uint256 defaultFeeHash = uint256(
keccak256(abi.encodePacked("pool_fee"))
);
uint256 defaultFee = INFTGemFeeManager(self.feeTracker).fee(
defaultFeeHash
);
defaultFee = defaultFee == 0 ? 2000 : defaultFee;
// get the fee, preferring the token fee if available
uint256 feeNum = poolFee != poolTokenFee
? (poolTokenFee != 0 ? poolTokenFee : poolFee)
: poolFee;
// set the fee to default if it is 0
return feeNum == 0 ? defaultFee : feeNum;
}
function getMinimumLiquidity(
ComplexPoolData storage self,
address tokenUsed
) internal view returns (uint256) {
// get the fee for this pool if it exists
uint256 poolDivFeeHash = uint256(
keccak256(abi.encodePacked("min_liquidity", address(self.pool)))
);
uint256 poolFee = INFTGemFeeManager(self.feeTracker).fee(
poolDivFeeHash
);
// get the pool fee for this token if it exists
uint256 poolTokenFeeHash = uint256(
keccak256(abi.encodePacked("min_liquidity", address(tokenUsed)))
);
uint256 poolTokenFee = INFTGemFeeManager(self.feeTracker).fee(
poolTokenFeeHash
);
// get the default fee amoutn for this token
uint256 defaultFeeHash = uint256(
keccak256(abi.encodePacked("min_liquidity"))
);
uint256 defaultFee = INFTGemFeeManager(self.feeTracker).fee(
defaultFeeHash
);
defaultFee = defaultFee == 0 ? 50 : defaultFee;
// get the fee, preferring the token fee if available
uint256 feeNum = poolFee != poolTokenFee
? (poolTokenFee != 0 ? poolTokenFee : poolFee)
: poolFee;
// set the fee to default if it is 0
return feeNum == 0 ? defaultFee : feeNum;
}
/**
* @dev crate multiple gem claim using an erc20 token. this token must be tradeable in Uniswap or this call will fail
*/
function createERC20Claims(
ComplexPoolData storage self,
address erc20token,
uint256 tokenAmount,
uint256 count
) public {
// enabled
require(self.enabled == true, "DISABLED");
// must be a valid address
require(erc20token != address(0), "INVALID_ERC20_TOKEN");
// token is allowed
require(
(self.allowedTokens.count() > 0 &&
self.allowedTokens.exists(erc20token)) ||
self.allowedTokens.count() == 0,
"TOKEN_DISALLOWED"
);
// zero qty
require(count != 0, "ZERO_QUANTITY");
// max quantity per claim
require(
(self.maxQuantityPerClaim != 0 &&
count <= self.maxQuantityPerClaim) ||
self.maxQuantityPerClaim == 0,
"MAX_QUANTITY_EXCEEDED"
);
require(
(self.maxClaimsPerAccount != 0 &&
self.claimsMade[msg.sender] < self.maxClaimsPerAccount) ||
self.maxClaimsPerAccount == 0,
"MAX_QUANTITY_EXCEEDED"
);
// require the user to have the input requirements
requireInputReqs(self, msg.sender, count);
// Uniswap pool must exist
require(
ISwapQueryHelper(self.swapHelper).hasPool(erc20token) == true,
"NO_UNISWAP_POOL"
);
// must have an amount specified
require(tokenAmount >= 0, "NO_PAYMENT_INCLUDED");
// get a quote in ETH for the given token.
(
uint256 ethereum,
uint256 tokenReserve,
uint256 ethReserve
) = ISwapQueryHelper(self.swapHelper).coinQuote(
erc20token,
tokenAmount / (count)
);
// TODO: update liquidity multiple from fee manager
if (self.validateerc20 == true) {
uint256 minLiquidity = getMinimumLiquidity(self, erc20token);
// make sure the convertible amount is has reserves > 100x the token
require(
ethReserve >= ethereum * minLiquidity * (count),
"INSUFFICIENT_ETH_LIQUIDITY"
);
// make sure the convertible amount is has reserves > 100x the token
require(
tokenReserve >= tokenAmount * minLiquidity * (count),
"INSUFFICIENT_TOKEN_LIQUIDITY"
);
}
// make sure the convertible amount is less than max price
require(ethereum <= self.ethPrice, "OVERPAYMENT");
// calculate the maturity time given the converted eth
uint256 maturityTime = (self.ethPrice * (self.minTime)) / (ethereum);
// make sure the convertible amount is less than max price
require(maturityTime >= self.minTime, "INSUFFICIENT_TIME");
// get the next claim hash, revert if no more claims
uint256 claimHash = nextClaimHash(self);
require(claimHash != 0, "NO_MORE_CLAIMABLE");
// mint the new claim to the caller's address
INFTGemMultiToken(self.multitoken).mint(msg.sender, claimHash, 1);
INFTGemMultiToken(self.multitoken).setTokenData(
claimHash,
INFTGemMultiToken.TokenType.CLAIM,
address(this)
);
addToken(self, claimHash, INFTGemMultiToken.TokenType.CLAIM);
// record the claim unlock time and cost paid for this claim
uint256 claimUnlockTimestamp = block.timestamp + (maturityTime);
self.claimLockTimestamps[claimHash] = claimUnlockTimestamp;
self.claimAmountPaid[claimHash] = ethereum;
self.claimLockToken[claimHash] = erc20token;
self.claimTokenAmountPaid[claimHash] = tokenAmount;
self.claimQuant[claimHash] = count;
self.claimsMade[msg.sender] = self.claimsMade[msg.sender] + (1);
// tranasfer NFT input requirements from user to pool
takeInputReqsFrom(self, claimHash, msg.sender, count);
// increase staked eth amount
self.totalStakedEth = self.totalStakedEth + (ethereum);
// emit a message indicating that an erc20 claim has been created
emit NFTGemERC20ClaimCreated(
msg.sender,
address(self.pool),
claimHash,
maturityTime,
erc20token,
count,
ethereum
);
// transfer the caller's ERC20 tokens into the pool
IERC20(erc20token).transferFrom(
msg.sender,
address(self.pool),
tokenAmount
);
}
/**
* @dev collect an open claim (take custody of the funds the claim is redeeemable for and maybe a gem too)
*/
function collectClaim(
ComplexPoolData storage self,
uint256 _claimHash,
bool _requireMature
) public {
// enabled
require(self.enabled == true, "DISABLED");
// check the maturity of the claim - only issue gem if mature
uint256 unlockTime = self.claimLockTimestamps[_claimHash];
bool isMature = unlockTime < block.timestamp;
require(
!_requireMature || (_requireMature && isMature),
"IMMATURE_CLAIM"
);
__collectClaim(self, _claimHash);
}
/**
* @dev collect an open claim (take custody of the funds the claim is redeeemable for and maybe a gem too)
*/
function __collectClaim(ComplexPoolData storage self, uint256 claimHash)
internal
{
// validation checks - disallow if not owner (holds coin with claimHash)
// or if the unlockTime amd unlockPaid data is in an invalid state
require(
IERC1155(self.multitoken).balanceOf(msg.sender, claimHash) == 1,
"NOT_CLAIM_OWNER"
);
uint256 unlockTime = self.claimLockTimestamps[claimHash];
uint256 unlockPaid = self.claimAmountPaid[claimHash];
require(unlockTime != 0 && unlockPaid > 0, "INVALID_CLAIM");
// grab the erc20 token info if there is any
address tokenUsed = self.claimLockToken[claimHash];
uint256 unlockTokenPaid = self.claimTokenAmountPaid[claimHash];
// check the maturity of the claim - only issue gem if mature
bool isMature = unlockTime < block.timestamp;
// burn claim and transfer money back to user
INFTGemMultiToken(self.multitoken).burn(msg.sender, claimHash, 1);
// if they used erc20 tokens stake their claim, return their tokens
if (tokenUsed != address(0)) {
// calculate fee portion using fee tracker
uint256 feePortion = 0;
if (isMature == true) {
feePortion = unlockTokenPaid / getPoolFee(self, tokenUsed);
}
// assess a fee for minting the NFT. Fee is collectec in fee tracker
IERC20(tokenUsed).transferFrom(
address(self.pool),
self.feeTracker,
feePortion
);
// send the principal minus fees to the caller
IERC20(tokenUsed).transferFrom(
address(self.pool),
msg.sender,
unlockTokenPaid - (feePortion)
);
// emit an event that the claim was redeemed for ERC20
emit NFTGemERC20ClaimRedeemed(
msg.sender,
address(self.pool),
claimHash,
tokenUsed,
unlockPaid,
unlockTokenPaid,
self.claimQuant[claimHash],
feePortion
);
} else {
// calculate fee portion using fee tracker
uint256 feePortion = 0;
if (isMature == true) {
feePortion = unlockPaid / getPoolFee(self, address(0));
}
// transfer the ETH fee to fee tracker
payable(self.feeTracker).transfer(feePortion);
// transfer the ETH back to user
payable(msg.sender).transfer(unlockPaid - (feePortion));
// emit an event that the claim was redeemed for ETH
emit NFTGemClaimRedeemed(
msg.sender,
address(self.pool),
claimHash,
unlockPaid,
self.claimQuant[claimHash],
feePortion
);
}
// tranasfer NFT input requirements from pool to user
returnInputReqsTo(
self,
claimHash,
msg.sender,
self.claimQuant[claimHash]
);
// deduct the total staked ETH balance of the pool
self.totalStakedEth = self.totalStakedEth - (unlockPaid);
// if all this is happening before the unlocktime then we exit
// without minting a gem because the user is withdrawing early
if (!isMature) {
return;
}
// get the next gem hash, increase the staking sifficulty
// for the pool, and mint a gem token back to account
uint256 nextHash = nextGemHash(self);
// associate gem and claim
self.gemClaims[nextHash] = claimHash;
// mint the gem
INFTGemMultiToken(self.multitoken).mint(
msg.sender,
nextHash,
self.claimQuant[claimHash]
);
addToken(self, nextHash, INFTGemMultiToken.TokenType.GEM);
// emit an event about a gem getting created
emit NFTGemCreated(
msg.sender,
address(self.pool),
claimHash,
nextHash,
self.claimQuant[claimHash]
);
}
/**
* @dev purchase gem(s) at the listed pool price
*/
function purchaseGems(
ComplexPoolData storage self,
address sender,
uint256 value,
uint256 count
) public {
// enabled
require(self.enabled == true, "DISABLED");
// non-zero balance
require(value != 0, "ZERO_BALANCE");
// non-zero quantity
require(count != 0, "ZERO_QUANTITY");
// sufficient input eth
uint256 adjustedBalance = value / (count);
require(adjustedBalance >= self.ethPrice, "INSUFFICIENT_ETH");
require(self.allowPurchase == true, "PURCHASE_DISALLOWED");
// get the next gem hash, increase the staking sifficulty
// for the pool, and mint a gem token back to account
uint256 nextHash = nextGemHash(self);
// mint the gem
INFTGemMultiToken(self.multitoken).mint(sender, nextHash, count);
addToken(self, nextHash, INFTGemMultiToken.TokenType.GEM);
// transfer the funds for the gem to the fee tracker
payable(self.feeTracker).transfer(value);
// emit an event about a gem getting created
emit NFTGemCreated(sender, address(self.pool), 0, nextHash, count);
}
/**
* @dev create a token of token hash / token type
*/
function addToken(
ComplexPoolData storage self,
uint256 tokenHash,
INFTGemMultiToken.TokenType tokenType
) public {
require(
tokenType == INFTGemMultiToken.TokenType.CLAIM ||
tokenType == INFTGemMultiToken.TokenType.GEM,
"INVALID_TOKENTYPE"
);
self.tokenHashes.push(tokenHash);
self.tokenTypes[tokenHash] = tokenType;
self.tokenIds[tokenHash] = tokenType ==
INFTGemMultiToken.TokenType.CLAIM
? nextClaimId(self)
: nextGemId(self);
INFTGemMultiToken(self.multitoken).setTokenData(
tokenHash,
tokenType,
address(this)
);
if (tokenType == INFTGemMultiToken.TokenType.GEM) {
increaseDifficulty(self);
}
}
/**
* @dev get the next claim id
*/
function nextClaimId(ComplexPoolData storage self)
public
returns (uint256)
{
uint256 ncId = self.nextClaimIdVal;
self.nextClaimIdVal = self.nextClaimIdVal + (1);
return ncId;
}
/**
* @dev get the next gem id
*/
function nextGemId(ComplexPoolData storage self) public returns (uint256) {
uint256 ncId = self.nextGemIdVal;
self.nextGemIdVal = self.nextGemIdVal + (1);
return ncId;
}
/**
* @dev increase the pool's difficulty by calculating the step increase portion and adding it to the eth price of the market
*/
function increaseDifficulty(ComplexPoolData storage self) public {
if (
self.priceIncrementType ==
INFTComplexGemPoolData.PriceIncrementType.COMPOUND
) {
uint256 diffIncrease = self.ethPrice / (self.diffstep);
self.ethPrice = self.ethPrice + (diffIncrease);
} else if (
self.priceIncrementType ==
INFTComplexGemPoolData.PriceIncrementType.INVERSELOG
) {
uint256 diffIncrease = self.diffstep / (self.ethPrice);
self.ethPrice = self.ethPrice + (diffIncrease);
}
}
/**
* @dev the hash of the next gem to be minted
*/
function nextGemHash(ComplexPoolData storage self)
public
view
returns (uint256)
{
return
uint256(
keccak256(
abi.encodePacked(
"gem",
address(self.pool),
self.nextGemIdVal
)
)
);
}
/**
* @dev the hash of the next claim to be minted
*/
function nextClaimHash(ComplexPoolData storage self)
public
view
returns (uint256)
{
return
(self.maxClaims != 0 && self.nextClaimIdVal <= self.maxClaims) ||
self.maxClaims == 0
? uint256(
keccak256(
abi.encodePacked(
"claim",
address(self.pool),
self.nextClaimIdVal
)
)
)
: 0;
}
/**
* @dev get the token hash at index
*/
function allTokenHashes(ComplexPoolData storage self, uint256 ndx)
public
view
returns (uint256)
{
return self.tokenHashes[ndx];
}
/**
* @dev return the claim amount paid for this claim
*/
function claimAmount(ComplexPoolData storage self, uint256 claimHash)
public
view
returns (uint256)
{
return self.claimAmountPaid[claimHash];
}
/**
* @dev the claim quantity (count of gems staked) for the given claim hash
*/
function claimQuantity(ComplexPoolData storage self, uint256 claimHash)
public
view
returns (uint256)
{
return self.claimQuant[claimHash];
}
/**
* @dev the lock time for this claim hash. once past lock time a gem is minted
*/
function claimUnlockTime(ComplexPoolData storage self, uint256 claimHash)
public
view
returns (uint256)
{
return self.claimLockTimestamps[claimHash];
}
/**
* @dev return the claim token amount for this claim hash
*/
function claimTokenAmount(ComplexPoolData storage self, uint256 claimHash)
public
view
returns (uint256)
{
return self.claimTokenAmountPaid[claimHash];
}
/**
* @dev return the claim hash of the given gemhash
*/
function gemClaimHash(ComplexPoolData storage self, uint256 gemHash)
public
view
returns (uint256)
{
return self.gemClaims[gemHash];
}
/**
* @dev return the token that was staked to create the given token hash. 0 if the native token
*/
function stakedToken(ComplexPoolData storage self, uint256 claimHash)
public
view
returns (address)
{
return self.claimLockToken[claimHash];
}
/**
* @dev add a token that is allowed to be used to create a claim
*/
function addAllowedToken(ComplexPoolData storage self, address token)
public
{
if (!self.allowedTokens.exists(token)) {
self.allowedTokens.insert(token);
}
}
/**
* @dev remove a token that is allowed to be used to create a claim
*/
function removeAllowedToken(ComplexPoolData storage self, address token)
public
{
if (self.allowedTokens.exists(token)) {
self.allowedTokens.remove(token);
}
}
/**
* @dev deposit into pool
*/
function deposit(
ComplexPoolData storage self,
address erc20token,
uint256 tokenAmount
) public {
if (erc20token == address(0)) {
require(msg.sender.balance >= tokenAmount, "INSUFFICIENT_BALANCE");
self.totalStakedEth = self.totalStakedEth + (msg.sender.balance);
} else {
require(
IERC20(erc20token).balanceOf(msg.sender) >= tokenAmount,
"INSUFFICIENT_BALANCE"
);
IERC20(erc20token).transferFrom(
msg.sender,
address(self.pool),
tokenAmount
);
}
}
/**
* @dev deposit NFT into pool
*/
function depositNFT(
ComplexPoolData storage self,
address erc1155token,
uint256 tokenId,
uint256 tokenAmount
) public {
require(
IERC1155(erc1155token).balanceOf(msg.sender, tokenId) >=
tokenAmount,
"INSUFFICIENT_BALANCE"
);
IERC1155(erc1155token).safeTransferFrom(
msg.sender,
address(self.pool),
tokenId,
tokenAmount,
""
);
}
/**
* @dev withdraw pool contents
*/
function withdraw(
ComplexPoolData storage self,
address erc20token,
address destination,
uint256 tokenAmount
) public {
require(destination != address(0), "ZERO_ADDRESS");
require(
self.controllers[msg.sender] == true || msg.sender == self.governor,
"UNAUTHORIZED"
);
if (erc20token == address(0)) {
payable(destination).transfer(tokenAmount);
} else {
IERC20(erc20token).transferFrom(
address(self.pool),
address(destination),
tokenAmount
);
}
}
/**
* @dev withdraw pool NFT
*/
function withdrawNFT(
ComplexPoolData storage self,
address erc1155token,
address destination,
uint256 tokenId,
uint256 tokenAmount
) public {
require(
self.controllers[msg.sender] == true || msg.sender == self.governor,
"UNAUTHORIZED"
);
require(erc1155token != address(0), "ZERO_ADDRESS");
require(destination != address(0), "ZERO_ADDRESS");
require(
IERC1155(erc1155token).balanceOf(address(self.pool), tokenId) >=
tokenAmount,
"INSUFFICIENT_BALANCE"
);
IERC1155(erc1155token).safeTransferFrom(
address(self.pool),
address(destination),
tokenId,
tokenAmount,
""
);
}
/**
* @dev mint the genesis gems earned by the pools creator and funder
*/
function mintGenesisGems(
ComplexPoolData storage self,
address creator,
address funder
) public {
require(self.multitoken != address(0), "NO_MULTITOKEN");
require(
creator != address(0) && funder != address(0),
"ZERO_DESTINATION"
);
require(self.nextGemIdVal == 0, "ALREADY_MINTED");
uint256 gemHash = nextGemHash(self);
INFTGemMultiToken(self.multitoken).mint(creator, gemHash, 1);
addToken(self, gemHash, INFTGemMultiToken.TokenType.GEM);
// emit an event about a gem getting created
emit NFTGemCreated(creator, address(self.pool), 0, gemHash, 1);
gemHash = nextGemHash(self);
INFTGemMultiToken(self.multitoken).mint(funder, gemHash, 1);
addToken(self, gemHash, INFTGemMultiToken.TokenType.GEM);
// emit an event about a gem getting created
emit NFTGemCreated(funder, address(self.pool), 0, gemHash, 1);
}
}
|
create a token of token hash / token type/
|
function addToken(
ComplexPoolData storage self,
uint256 tokenHash,
INFTGemMultiToken.TokenType tokenType
) public {
require(
tokenType == INFTGemMultiToken.TokenType.CLAIM ||
tokenType == INFTGemMultiToken.TokenType.GEM,
"INVALID_TOKENTYPE"
);
self.tokenHashes.push(tokenHash);
self.tokenTypes[tokenHash] = tokenType;
self.tokenIds[tokenHash] = tokenType ==
INFTGemMultiToken.TokenType.CLAIM
? nextClaimId(self)
: nextGemId(self);
INFTGemMultiToken(self.multitoken).setTokenData(
tokenHash,
tokenType,
address(this)
);
if (tokenType == INFTGemMultiToken.TokenType.GEM) {
increaseDifficulty(self);
}
}
| 15,863,484
|
./full_match/1/0x666D080bD673679b927B7006bDbDF50925f27D9F/sources/contracts/MIRLStaking.sol
|
MIRLStaking / Update reward variables of the given pool. pid The index of the pool. See `poolInfo`. return pool Returns the pool that was updated. blocksCount
|
function updatePool(uint256 pid) public returns (PoolInfo memory pool) {
require(pid < poolInfo.length, 'Invalid pool id');
pool = poolInfo[pid];
uint256 startBlockPeriod = pool.lastRewardBlock > bonusStartBlock ? pool.lastRewardBlock : bonusStartBlock;
uint256 endBlockPeriod = (bonusEndBlock == 0 || block.number < bonusEndBlock) ? block.number : bonusEndBlock;
uint256 lpSupply = pool.totalSupply;
if (startBlockPeriod < endBlockPeriod && lpSupply > 0) {
uint256 blocks = endBlockPeriod.sub(startBlockPeriod);
uint256 mirlReward = blocks.mul(mirlPerBlock).mul(pool.allocPoint) / totalAllocPoint;
MIRL.mint(address(this), mirlReward);
pool.accumulatedMirlPerShare = pool.accumulatedMirlPerShare.add((mirlReward.mul(ACC_SUSHI_PRECISION) / lpSupply));
}
pool.lastRewardBlock = block.number.to64();
poolInfo[pid] = pool;
emit LogUpdatePool(pid, pool.lastRewardBlock, lpSupply, pool.accumulatedMirlPerShare);
}
| 9,625,479
|
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import './MadMouseTroupe.sol';
import './MadMouseStaking.sol';
import './lib/Ownable.sol';
contract MadMouseTroupeMetadata is Ownable {
using Strings for uint256;
MadMouseTroupe public madmouseTroupe;
MadMouseTroupeMetadata public metadataGenesis;
string specialURI;
string constant unrevealedURI = 'ipfs://QmW9NKUGYesTiYx5iSP1o82tn4Chq9i1yQV6DBnzznrHTH';
function setMadMouseAddress(MadMouseTroupe madmouseTroupe_, MadMouseTroupeMetadata metadataGenesis_)
external
onlyOwner
{
metadataGenesis = metadataGenesis_;
madmouseTroupe = madmouseTroupe_;
}
function setSpecialURI(string calldata uri) external onlyOwner {
specialURI = uri;
}
// will act as an ERC721 proxy
function balanceOf(address user) external view returns (uint256) {
return madmouseTroupe.numOwned(user);
}
// reuse metadata build from genesis collection
function buildMouseMetadata(uint256 tokenId, uint256 level) external returns (string memory) {
if (tokenId > 30) {
(, bytes memory data) = address(metadataGenesis).delegatecall(
abi.encodeWithSelector(this.buildMouseMetadata.selector, tokenId, level)
);
return abi.decode(data, (string));
}
return bytes(specialURI).length != 0 ? string.concat(specialURI, tokenId.toString()) : unrevealedURI;
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
// MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
// MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
// MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM`MMM NMM MMM MMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
// MMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMhMMMMMMM MMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
// MMMMMMMMMMMMMMMMMMMMMMMMMM MM-MMMMM MMMM MMMM lMMMDMMMMMMMMMMMMMMMMMMMMMMMMMM
// MMMMMMMMMMMMMMMMMMMMMMM jMMMMl MM MMM M MMM M MMMM MMMMMMMMMMMMMMMMMMMMMMM
// MMMMMMMMMMMMMMMMMMMM MMMMMMMMM , ` M Y MM MMM BMMMMMM MMMMMMMMMMMMMMMMMMMM
// MMMMMMMMMMMMMMMMM MMMMMMMMMMMM IM MM l MMM X MM. MMMMMMMMMM MMMMMMMMMMMMMMMMM
// MMMMMMMMMMMMMMMMMMMMMMMMMMMMMM.nlMMMMMMMMMMMMMMMMM]._ MMMMMMMMMMMMMMMNMMMMMMMMMMMMMM
// MMMMMMMMMMMMMM TMMMMMMMMMMMMMMMMMM +MMMMMMMMMMMM: rMMMMMMMMN MMMMMMMMMMMMMM
// MMMMMMMMMMMM MMMMMMMMMMMMMMMM MMMMMM MMMMMMMM qMMMMMMMMMMM
// MMMMMMMMMMMMMMMMMMMMMMMMMMM^ MMMb .MMMMMMMMMMMMMMMMMMM
// MMMMMMMMMM MMMMMMMMMMMMMMM MM MMMMMMM MMMMMMMMMM
// MMMMMMMMMMMMMMMMMMMMMMMMMM M gMMMMMMMMMMMMMMMMM
// MMMMMMMMu MMMMMMMMMMMMMMM MMMMMMM .MMMMMMMM
// MMMMMMMMMMMMMMMMMMMMMMMMM :MMMMMMMMMMMMMMMM
// MMMMMMM^ MMMMMMMMMMMMMMMl MMMMMMMM MMMMMMM
// MMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMM
// MMMMMMM MMMMMMMMMMMMMMMM MMMMMMMM MMMMMMM
// MMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMM
// MMMMMMr MMMMMMMMMMMMMMMM MMMMMMMM .MMMMMM
// MMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMM
// MMMMMMM MMMMMMMMMMMMMMMMM DMMMMMMMMMM MMMMMMM
// MMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMM
// MMMMMMM|`MMMMMMMMMMMMMMMM q MMMMMMMMMMMMMMMMMMM MMMMMMM
// MMMMMMMMMTMMMMMMMMMMMMMMM qMMMMMMMMMMMMMMMMMMgMMMMMMMMM
// MMMMMMMMq MMMMMMMMMMMMMMMh jMMMMMMMMMMMMMMMMMMM nMMMMMMMM
// MMMMMMMMMM MMMMMMMMMMMMMMMQ nc -MMMMMn MMMMMMMMMMMMMMMMMMMM MMMMMMMMMM
// MMMMMMMMMM.MMMMMMMMMMMMMMMMMMl M1 `MMMMMMMMMMMMMMMMMMMMMMrMMMMMMMMMM
// MMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMM :MMMMMMMMMM MMMMMMMMMMMM qMMMMMMMMMMM
// MMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMX MMMMMMMMMMMMMMM uMMMMMMMMMMMMMMMMMMMMMMMMM
// MMMMMMMMMMMMMM DMMMMMMMMM IMMMMMMMMMMMMMMMMMMMMMMM M Y MMMMMMMN MMMMMMMMMMMMMM
// MMMMMMMMMMMMMMMMM MMMMMM `` M MM MMM , MMMM Mv MMM MMMMMMMMMMMMMMMM
// MMMMMMMMMMMMMMMMMMM MMh Ml . M MMMM I MMMT M :M ,MMMMMMMMMMMMMMMMMMMMMM
// MMMMMMMMMMMMMMMMMMMM MMMMMMMMt MM MMMMB m ]MMM MMMM MMMMMM MMMMMMMMMMMMMMMMMMMM
// MMMMMMMMMMMMMMMMMMMMMMM MMMMM MMM TM MM 9U .MM _MMMMM MMMMMMMMMMMMMMMMMMMMMMM
// MMMMMMMMMMMMMMMMMMMMMMMMMM YMMMMMMMn MMMM +MMMMMMM1`MMMMMMMMMMMMMMMMMMMMMMMMMM
// MMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
// MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM.`MMM MMM MMMMM`.MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
// MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
// MM M M M M M______ ____ ___ __ __ ____ ___ M M M M M M MM
// MM M M M M M| || \ / \ | | || \ / _] M M M M M M MM
// MM M M M M M | || D ) || | || o ) [_ M M M M M M MM
// MM M M M M M M|_| |_|| /| O || | || _/ _] M M M M M MMM
// MM M M M M M M | | | \| || : || | | [_ M M M M M M MM
// MMM M M M M M | | | . \ || || | | | M M M M M MMM
// MM M M M M M |__| |__|\_|\___/ \__,_||__| |_____|M M M M M M MM
// MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
// MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM author: phaze MMM
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/utils/cryptography/ECDSA.sol';
import './lib/Ownable.sol';
import {VRFBaseMainnet as VRFBase} from './lib/VRFBase.sol';
import './Gouda.sol';
import './MadMouseStaking.sol';
error PublicSaleNotActive();
error WhitelistNotActive();
error InvalidAmount();
error ExceedsLimit();
error SignatureExceedsLimit();
error IncorrectValue();
error InvalidSignature();
error ContractCallNotAllowed();
error InvalidString();
error MaxLevelReached();
error MaxNumberReached();
error MinHoldDurationRequired();
error IncorrectHash();
error CollectionAlreadyRevealed();
error CollectionNotRevealed();
error TokenDataAlreadySet();
error MintAndStakeMinHoldDurationNotReached();
interface IMadMouseMetadata {
function buildMouseMetadata(uint256 tokenId, uint256 level) external view returns (string memory);
}
contract MadMouseTroupe is Ownable, MadMouseStaking, VRFBase {
using ECDSA for bytes32;
using UserDataOps for uint256;
using TokenDataOps for uint256;
using DNAOps for uint256;
bool public publicSaleActive;
uint256 constant MAX_SUPPLY = 5000;
uint256 constant MAX_PER_WALLET = 50;
uint256 constant PURCHASE_LIMIT = 3;
uint256 constant whitelistPrice = 0.075 ether;
address public metadata;
address public multiSigTreasury = 0xFB79a928C5d6c5932Ba83Aa8C7145cBDCDb9fd2E;
address signerAddress = 0x3ADE0c5e35cbF136245F4e4bBf4563BD151d39D1;
uint256 public totalLevel2Reached;
uint256 public totalLevel3Reached;
uint256 constant LEVEL_2_COST = 120 * 1e18;
uint256 constant LEVEL_3_COST = 350 * 1e18;
uint256 constant MAX_NUM_LEVEL_2 = 3300;
uint256 constant MAX_NUM_LEVEL_3 = 1200;
uint256 constant NAME_CHANGE_COST = 25 * 1e18;
uint256 constant BIO_CHANGE_COST = 15 * 1e18;
uint256 constant MAX_LEN_NAME = 20;
uint256 constant MAX_LEN_BIO = 35;
uint256 constant MINT_AND_STAKE_MIN_HOLD_DURATION = 3 days;
uint256 profileUpdateMinHoldDuration = 30 days;
mapping(uint256 => string) public mouseName;
mapping(uint256 => string) public mouseBio;
string public description;
string public imagesBaseURI;
string constant unrevealedURI = 'ipfs://QmW9NKUGYesTiYx5iSP1o82tn4Chq9i1yQV6DBnzznrHTH';
bool private revealed;
bytes32 immutable secretHash;
constructor(bytes32 secretHash_) MadMouseStaking(MAX_SUPPLY, MAX_PER_WALLET) {
secretHash = secretHash_;
_mintAndStake(msg.sender, 30, false);
}
/* ------------- External ------------- */
function mint(uint256 amount, bool stake) external payable noContract {
if (!publicSaleActive) revert PublicSaleNotActive();
if (PURCHASE_LIMIT < amount) revert ExceedsLimit();
uint256 price_ = price();
if (msg.value != price_ * amount) revert IncorrectValue();
if (price_ == 0) {
// free mints will at first be restricted to purchase limit
uint256 numMinted = _userData[msg.sender].numMinted();
if (numMinted + amount > PURCHASE_LIMIT) revert ExceedsLimit();
// free mints > 1 will be staked
if (amount != 1) stake = true;
}
_mintAndStake(msg.sender, amount, stake);
}
function whitelistMint(
uint256 amount,
uint256 limit,
bytes calldata signature,
bool stake
) external payable noContract {
if (publicSaleActive) revert WhitelistNotActive();
if (!validSignature(signature, limit)) revert InvalidSignature();
uint256 numMinted = _userData[msg.sender].numMinted();
if (numMinted + amount > limit) revert ExceedsLimit();
_mintAndStake(msg.sender, amount, stake);
}
function levelUp(uint256 tokenId) external payable {
uint256 tokenData = _tokenDataOf(tokenId);
address owner = tokenData.trueOwner();
if (owner != msg.sender) revert IncorrectOwner();
uint256 level = tokenData.level();
if (level > 2) revert MaxLevelReached();
if (level == 1) {
if (totalLevel2Reached >= MAX_NUM_LEVEL_2) revert MaxNumberReached();
gouda.burnFrom(msg.sender, LEVEL_2_COST);
++totalLevel2Reached;
} else {
if (totalLevel3Reached >= MAX_NUM_LEVEL_3) revert MaxNumberReached();
gouda.burnFrom(msg.sender, LEVEL_3_COST);
++totalLevel3Reached;
}
uint256 newTokenData = tokenData.increaseLevel().resetOwnerCount();
if (tokenData.staked() && revealed) {
uint256 userData = _claimReward();
(userData, newTokenData) = updateDataWhileStaked(userData, tokenId, tokenData, newTokenData);
_userData[msg.sender] = userData;
}
_tokenData[tokenId] = newTokenData;
}
function setName(uint256 tokenId, string calldata name) external payable onlyLongtermHolder(tokenId) {
if (!isValidString(name, MAX_LEN_NAME)) revert InvalidString();
gouda.burnFrom(msg.sender, NAME_CHANGE_COST);
mouseName[tokenId] = name;
}
function setBio(uint256 tokenId, string calldata bio) external payable onlyLongtermHolder(tokenId) {
if (!isValidString(bio, MAX_LEN_BIO)) revert InvalidString();
gouda.burnFrom(msg.sender, BIO_CHANGE_COST);
mouseBio[tokenId] = bio;
}
// only to be used by owner in extreme cases when these reflect negatively on the collection
// since they are automatically shown in the metadata (on OpenSea)
function resetName(uint256 tokenId) external payable {
address _owner = _tokenDataOf(tokenId).trueOwner();
if (_owner != msg.sender && owner() != msg.sender) revert IncorrectOwner();
delete mouseName[tokenId];
}
function resetBio(uint256 tokenId) external payable {
address _owner = _tokenDataOf(tokenId).trueOwner();
if (_owner != msg.sender && owner() != msg.sender) revert IncorrectOwner();
delete mouseBio[tokenId];
}
/* ------------- View ------------- */
function price() public view returns (uint256) {
return totalSupply < 3500 ? 0 ether : .02 ether;
}
function tokenURI(uint256 tokenId) public view override returns (string memory) {
if (!_exists(tokenId)) revert NonexistentToken();
if (!revealed || address(metadata) == address(0)) return unrevealedURI;
return IMadMouseMetadata(address(metadata)).buildMouseMetadata(tokenId, this.getLevel(tokenId));
}
function previewTokenURI(uint256 tokenId, uint256 level) external view returns (string memory) {
if (!_exists(tokenId)) revert NonexistentToken();
if (!revealed || address(metadata) == address(0)) return unrevealedURI;
return IMadMouseMetadata(address(metadata)).buildMouseMetadata(tokenId, level);
}
function getDNA(uint256 tokenId) external view onceRevealed returns (uint256) {
if (!_exists(tokenId)) revert NonexistentToken();
return computeDNA(tokenId);
}
function getLevel(uint256 tokenId) external view returns (uint256) {
return _tokenDataOf(tokenId).level();
}
/* ------------- Private ------------- */
function validSignature(bytes calldata signature, uint256 limit) private view returns (bool) {
bytes32 msgHash = keccak256(abi.encode(address(this), msg.sender, limit));
return msgHash.toEthSignedMessageHash().recover(signature) == signerAddress;
}
// not guarded for reveal
function computeDNA(uint256 tokenId) private view returns (uint256) {
return uint256(keccak256(abi.encodePacked(randomSeed, tokenId)));
}
/* ------------- Owner ------------- */
function setPublicSaleActive(bool active) external payable onlyOwner {
publicSaleActive = active;
}
function setProfileUpdateMinHoldDuration(uint256 duration) external payable onlyOwner {
profileUpdateMinHoldDuration = duration;
}
function giveAway(address[] calldata to, uint256[] calldata amounts) external payable onlyOwner {
for (uint256 i; i < to.length; ++i) _mintAndStake(to[i], amounts[i], false);
}
function setSignerAddress(address address_) external payable onlyOwner {
signerAddress = address_;
}
function setMetadataAddress(address metadata_) external payable onlyOwner {
metadata = metadata_;
}
function withdraw() external payable onlyOwner {
uint256 balance = address(this).balance;
multiSigTreasury.call{value: balance}('');
}
function recoverToken(IERC20 token) external payable onlyOwner {
uint256 balance = token.balanceOf(address(this));
token.transfer(msg.sender, balance);
}
function setDescription(string memory description_) external payable onlyOwner {
description = description_;
}
// requires that the reveal is first done through chainlink vrf
function setImagesBaseURI(string memory uri) external payable onlyOwner onceRevealed {
imagesBaseURI = uri;
}
// extra security for reveal:
// the owner sets a hash of a secret seed
// once chainlink randomness fulfills, the secret is revealed and shifts the secret seed set by chainlink
// Why? The final randomness should come from a trusted third party,
// however devs need time to generate the collection from the metadata.
// There is a time-frame in which an unfair advantage is gained after the seed is set and before the metadata is revealed.
// This eliminates any possibility of the team generating an unfair seed and any unfair advantage by snipers.
function reveal(string memory _imagesBaseURI, bytes32 secretSeed_) external payable onlyOwner whenRandomSeedSet {
if (revealed) revert CollectionAlreadyRevealed();
if (secretHash != keccak256(abi.encode(secretSeed_))) revert IncorrectHash();
revealed = true;
imagesBaseURI = _imagesBaseURI;
_shiftRandomSeed(uint256(secretSeed_));
}
/* ------------- Hooks ------------- */
// update role, level information when staking
function _beforeStakeDataTransform(
uint256 tokenId,
uint256 userData,
uint256 tokenData
) internal view override returns (uint256, uint256) {
// assumption that mint&stake won't have revealed yet
if (!tokenData.mintAndStake() && tokenData.role() == 0 && revealed)
tokenData = tokenData.setRoleAndRarity(computeDNA(tokenId));
userData = userData.updateUserDataStake(tokenData);
return (userData, tokenData);
}
function _beforeUnstakeDataTransform(
uint256,
uint256 userData,
uint256 tokenData
) internal view override returns (uint256, uint256) {
userData = userData.updateUserDataUnstake(tokenData);
if (tokenData.mintAndStake() && block.timestamp - tokenData.lastTransfer() < MINT_AND_STAKE_MIN_HOLD_DURATION)
revert MintAndStakeMinHoldDurationNotReached();
return (userData, tokenData);
}
function updateStakedTokenData(uint256[] calldata tokenIds) external payable onceRevealed {
uint256 userData = _claimReward();
uint256 tokenId;
uint256 tokenData;
for (uint256 i; i < tokenIds.length; ++i) {
tokenId = tokenIds[i];
tokenData = _tokenDataOf(tokenId);
if (tokenData.trueOwner() != msg.sender) revert IncorrectOwner();
if (!tokenData.staked()) revert TokenIdUnstaked(); // only useful for staked ids
if (tokenData.role() != 0) revert TokenDataAlreadySet();
(userData, tokenData) = updateDataWhileStaked(userData, tokenId, tokenData, tokenData);
_tokenData[tokenId] = tokenData;
}
_userData[msg.sender] = userData;
}
// note: must be guarded by check for revealed
function updateDataWhileStaked(
uint256 userData,
uint256 tokenId,
uint256 oldTokenData,
uint256 newTokenData
) private view returns (uint256, uint256) {
uint256 userDataX;
// add in the role and rarity data if not already
uint256 tokenDataX = newTokenData.role() != 0
? newTokenData
: newTokenData.setRoleAndRarity(computeDNA(tokenId));
// update userData as if to unstake with old tokenData and stake with new tokenData
userDataX = userData.updateUserDataUnstake(oldTokenData).updateUserDataStake(tokenDataX);
return applySafeDataTransform(userData, newTokenData, userDataX, tokenDataX);
}
// simulates a token update and only returns ids != 0 if
// the user gets a bonus increase upon updating staked data
function shouldUpdateStakedIds(address user) external view returns (uint256[] memory) {
if (!revealed) return new uint256[](0);
uint256[] memory stakedIds = this.tokenIdsOf(user, 1);
uint256 userData = _userData[user];
uint256 oldTotalBonus = totalBonus(user, userData);
uint256 tokenData;
for (uint256 i; i < stakedIds.length; ++i) {
tokenData = _tokenDataOf(stakedIds[i]);
if (tokenData.role() == 0)
(userData, ) = updateDataWhileStaked(userData, stakedIds[i], tokenData, tokenData);
else stakedIds[i] = 0;
}
uint256 newTotalBonus = totalBonus(user, userData);
return (newTotalBonus > oldTotalBonus) ? stakedIds : new uint256[](0);
}
/* ------------- Modifier ------------- */
modifier onceRevealed() {
if (!revealed) revert CollectionNotRevealed();
_;
}
modifier noContract() {
if (tx.origin != msg.sender) revert ContractCallNotAllowed();
_;
}
modifier onlyLongtermHolder(uint256 tokenId) {
uint256 tokenData = _tokenDataOf(tokenId);
uint256 timeHeld = block.timestamp - tokenData.lastTransfer();
if (tokenData.trueOwner() != msg.sender) revert IncorrectOwner();
if (timeHeld < profileUpdateMinHoldDuration) revert MinHoldDurationRequired();
_;
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import './Gouda.sol';
import './lib/ERC721M.sol';
import './lib/Ownable.sol';
error InvalidBoostToken();
error TransferFailed();
error BoostInEffect();
error NotSpecialGuestOwner();
error SpecialGuestIndexMustDiffer();
abstract contract MadMouseStaking is ERC721M, Ownable {
using UserDataOps for uint256;
event BoostActivation(address token);
Gouda public gouda;
uint256 constant dailyReward = 0.3 * 1e18;
uint256 constant ROLE_BONUS_3 = 2000;
uint256 constant ROLE_BONUS_5 = 3500;
uint256 constant TOKEN_BONUS = 1000;
uint256 constant TIME_BONUS = 1000;
uint256 constant RARITY_BONUS = 1000;
uint256 constant OG_BONUS = 2000;
uint256 constant SPECIAL_GUEST_BONUS = 1000;
uint256 immutable OG_BONUS_END;
uint256 immutable LAST_GOUDA_EMISSION_DATE;
uint256 constant TOKEN_BOOST_DURATION = 9 days;
uint256 constant TOKEN_BOOST_COOLDOWN = 9 days;
uint256 constant TIME_BONUS_STAKE_DURATION = 30 days;
mapping(IERC20 => uint256) tokenBoostCosts;
mapping(uint256 => IERC721) specialGuests;
mapping(IERC721 => bytes4) specialGuestsNumStakedSelector;
address constant burnAddress = 0x000000000000000000000000000000000000dEaD;
constructor(uint256 maxSupply_, uint256 maxPerWallet_)
ERC721M('MadMouseCircus', 'MMC', 1, maxSupply_, maxPerWallet_)
{
OG_BONUS_END = block.timestamp + 60 days;
LAST_GOUDA_EMISSION_DATE = block.timestamp + 5 * 365 days;
}
/* ------------- External ------------- */
function burnForBoost(IERC20 token) external payable {
uint256 userData = _claimReward();
uint256 boostCost = tokenBoostCosts[token];
if (boostCost == 0) revert InvalidBoostToken();
bool success = token.transferFrom(msg.sender, burnAddress, boostCost);
if (!success) revert TransferFailed();
uint256 boostStart = userData.boostStart();
if (boostStart + TOKEN_BOOST_DURATION + TOKEN_BOOST_COOLDOWN > block.timestamp) revert BoostInEffect();
_userData[msg.sender] = userData.setBoostStart(block.timestamp);
emit BoostActivation(address(token));
}
function claimSpecialGuest(uint256 collectionIndex) external payable {
uint256 userData = _claimReward();
uint256 specialGuestIndexOld = userData.specialGuestIndex();
if (collectionIndex == specialGuestIndexOld) revert SpecialGuestIndexMustDiffer();
if (collectionIndex != 0 && !hasSpecialGuest(msg.sender, collectionIndex)) revert NotSpecialGuestOwner();
_userData[msg.sender] = userData.setSpecialGuestIndex(collectionIndex);
}
function clearSpecialGuestData() external payable {
_userData[msg.sender] = _userData[msg.sender].setSpecialGuestIndex(0);
}
/* ------------- Internal ------------- */
function tokenBonus(uint256 userData) private view returns (uint256) {
unchecked {
uint256 lastClaimed = userData.lastClaimed();
uint256 boostEnd = userData.boostStart() + TOKEN_BOOST_DURATION;
if (lastClaimed > boostEnd) return 0;
if (block.timestamp <= boostEnd) return TOKEN_BONUS;
// follows: lastClaimed <= boostEnd < block.timestamp
// user is half-way through running out of boost, calculate exact fraction,
// as if claim was initiated once at end of boost and once now
// bonus * (time delta spent with boost bonus) / (complete duration)
return (TOKEN_BONUS * (boostEnd - lastClaimed)) / (block.timestamp - lastClaimed);
}
}
function roleBonus(uint256 userData) private pure returns (uint256) {
uint256 numRoles = userData.uniqueRoleCount();
return numRoles < 3 ? 0 : numRoles < 5 ? ROLE_BONUS_3 : ROLE_BONUS_5;
}
function rarityBonus(uint256 userData) private pure returns (uint256) {
unchecked {
uint256 numStaked = userData.numStaked();
return numStaked == 0 ? 0 : (userData.rarityPoints() * RARITY_BONUS) / numStaked;
}
}
function OGBonus(uint256 userData) private view returns (uint256) {
unchecked {
uint256 count = userData.OGCount();
uint256 lastClaimed = userData.lastClaimed();
if (count == 0 || lastClaimed > OG_BONUS_END) return 0;
// follows: 0 < count <= numStaked
uint256 bonus = (count * OG_BONUS) / userData.numStaked();
if (block.timestamp <= OG_BONUS_END) return bonus;
// follows: lastClaimed <= OG_BONUS_END < block.timestamp
return (bonus * (OG_BONUS_END - lastClaimed)) / (block.timestamp - lastClaimed);
}
}
function timeBonus(uint256 userData) private view returns (uint256) {
unchecked {
uint256 stakeStart = userData.stakeStart();
uint256 stakeBonusStart = stakeStart + TIME_BONUS_STAKE_DURATION;
if (block.timestamp < stakeBonusStart) return 0;
uint256 lastClaimed = userData.lastClaimed();
if (lastClaimed >= stakeBonusStart) return TIME_BONUS;
// follows: lastClaimed < stakeBonusStart <= block.timestamp
return (TIME_BONUS * (block.timestamp - stakeBonusStart)) / (block.timestamp - lastClaimed);
}
}
function hasSpecialGuest(address user, uint256 index) public view returns (bool) {
if (index == 0) return false;
// first 18 addresses are hardcoded to save gas
if (index < 19) {
address[19] memory guests = [
0x0000000000000000000000000000000000000000, // 0: reserved
0x4BB33f6E69fd62cf3abbcC6F1F43b94A5D572C2B, // 1: Bears Deluxe
0xbEA8123277142dE42571f1fAc045225a1D347977, // 2: DystoPunks
0x12d2D1beD91c24f878F37E66bd829Ce7197e4d14, // 3: Galactic Apes
0x0c2E57EFddbA8c768147D1fdF9176a0A6EBd5d83, // 4: Kaiju Kingz
0x6E5a65B5f9Dd7b1b08Ff212E210DCd642DE0db8B, // 5: Octohedz
0x17eD38f5F519C6ED563BE6486e629041Bed3dfbC, // 6: PXQuest Adventurer
0xdd67892E722bE69909d7c285dB572852d5F8897C, // 7: Scholarz
0x8a90CAb2b38dba80c64b7734e58Ee1dB38B8992e, // 8: Doodles
0x6F44Db5ed6b86d9cC6046D0C78B82caD9E600F6a, // 9: Digi Dragonz
0x219B8aB790dECC32444a6600971c7C3718252539, // 10: Sneaky Vampire Syndicate
0xC4a0b1E7AA137ADA8b2F911A501638088DFdD508, // 11: Uninterested Unicorns
0x9712228cEeDA1E2dDdE52Cd5100B88986d1Cb49c, // 12: Wulfz
0x56b391339615fd0e88E0D370f451fA91478Bb20F, // 13: Ethalien
0x648E8428e0104Ec7D08667866a3568a72Fe3898F, // 14: Dysto Apez
0xd2F668a8461D6761115dAF8Aeb3cDf5F40C532C6, // 15: Karafuru
0xbad6186E92002E312078b5a1dAfd5ddf63d3f731, // 16: Anonymice
0xcB4307F1c3B5556256748DDF5B86E81258990B3C, // 17: The Other Side
0x5c211B8E4f93F00E2BD68e82F4E00FbB3302b35c // 18: Global Citizen Club
];
if (IERC721(guests[index]).balanceOf(user) != 0) return true;
if (index == 10) return ISVSGraveyard(guests[index]).getBuriedCount(user) != 0;
else if (index == 12) return AWOO(guests[index]).getStakedAmount(user) != 0;
else if (index == 16) return CheethV2(guests[index]).stakedMiceQuantity(user) != 0;
} else {
IERC721 collection = specialGuests[index];
if (address(collection) != address(0)) {
if (collection.balanceOf(user) != 0) return true;
bytes4 selector = specialGuestsNumStakedSelector[collection];
if (selector != bytes4(0)) {
(bool success, bytes memory data) = address(collection).staticcall(
abi.encodeWithSelector(selector, user)
);
return success && abi.decode(data, (uint256)) != 0;
}
}
}
return false;
}
function specialGuestBonus(address user, uint256 userData) private view returns (uint256) {
uint256 index = userData.specialGuestIndex();
if (!hasSpecialGuest(user, index)) return 0;
return SPECIAL_GUEST_BONUS;
}
function _pendingReward(address user, uint256 userData) internal view override returns (uint256) {
uint256 lastClaimed = userData.lastClaimed();
if (lastClaimed == 0) return 0;
uint256 timestamp = min(LAST_GOUDA_EMISSION_DATE, block.timestamp);
unchecked {
uint256 delta = timestamp < lastClaimed ? 0 : timestamp - lastClaimed;
uint256 reward = (userData.baseReward() * delta * dailyReward) / (1 days);
if (reward == 0) return 0;
uint256 bonus = totalBonus(user, userData);
// needs to be calculated per myriad for more accuracy
return (reward * (10000 + bonus)) / 10000;
}
}
function totalBonus(address user, uint256 userData) internal view returns (uint256) {
unchecked {
return
roleBonus(userData) +
specialGuestBonus(user, userData) +
rarityBonus(userData) +
OGBonus(userData) +
timeBonus(userData) +
tokenBonus(userData);
}
}
function _payoutReward(address user, uint256 reward) internal override {
if (reward != 0) gouda.mint(user, reward);
}
/* ------------- View ------------- */
// for convenience
struct StakeInfo {
uint256 numStaked;
uint256 roleCount;
uint256 roleBonus;
uint256 specialGuestBonus;
uint256 tokenBoost;
uint256 stakeStart;
uint256 timeBonus;
uint256 rarityPoints;
uint256 rarityBonus;
uint256 OGCount;
uint256 OGBonus;
uint256 totalBonus;
uint256 multiplierBase;
uint256 dailyRewardBase;
uint256 dailyReward;
uint256 pendingReward;
int256 tokenBoostDelta;
uint256[3] levelBalances;
}
// calculates momentary totalBonus for display instead of effective bonus
function getUserStakeInfo(address user) external view returns (StakeInfo memory info) {
unchecked {
uint256 userData = _userData[user];
info.numStaked = userData.numStaked();
info.roleCount = userData.uniqueRoleCount();
info.roleBonus = roleBonus(userData) / 100;
info.specialGuestBonus = specialGuestBonus(user, userData) / 100;
info.tokenBoost = (block.timestamp < userData.boostStart() + TOKEN_BOOST_DURATION) ? TOKEN_BONUS / 100 : 0;
info.stakeStart = userData.stakeStart();
info.timeBonus = (info.stakeStart > 0 &&
block.timestamp > userData.stakeStart() + TIME_BONUS_STAKE_DURATION)
? TIME_BONUS / 100
: 0;
info.OGCount = userData.OGCount();
info.OGBonus = (block.timestamp > OG_BONUS_END || userData.numStaked() == 0)
? 0
: (userData.OGCount() * OG_BONUS) / userData.numStaked() / 100;
info.rarityPoints = userData.rarityPoints();
info.rarityBonus = rarityBonus(userData) / 100;
info.totalBonus =
info.roleBonus +
info.specialGuestBonus +
info.tokenBoost +
info.timeBonus +
info.rarityBonus +
info.OGBonus;
info.multiplierBase = userData.baseReward();
info.dailyRewardBase = info.multiplierBase * dailyReward;
info.dailyReward = (info.dailyRewardBase * (100 + info.totalBonus)) / 100;
info.pendingReward = _pendingReward(user, userData);
info.tokenBoostDelta = int256(TOKEN_BOOST_DURATION) - int256(block.timestamp - userData.boostStart());
info.levelBalances = userData.levelBalances();
}
}
/* ------------- Owner ------------- */
function setGoudaToken(Gouda gouda_) external payable onlyOwner {
gouda = gouda_;
}
function setSpecialGuests(IERC721[] calldata collections, uint256[] calldata indices) external payable onlyOwner {
for (uint256 i; i < indices.length; ++i) {
uint256 index = indices[i];
require(index != 0);
specialGuests[index] = collections[i];
}
}
function setSpecialGuestStakingSelector(IERC721 collection, bytes4 selector) external payable onlyOwner {
specialGuestsNumStakedSelector[collection] = selector;
}
function setBoostTokens(IERC20[] calldata _boostTokens, uint256[] calldata _boostCosts) external payable onlyOwner {
for (uint256 i; i < _boostTokens.length; ++i) tokenBoostCosts[_boostTokens[i]] = _boostCosts[i];
}
}
// Special guest's staking interfaces
interface ISVSGraveyard {
function getBuriedCount(address burier) external view returns (uint256);
}
interface AWOO {
function getStakedAmount(address staker) external view returns (uint256);
}
interface CheethV2 {
function stakedMiceQuantity(address _address) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
error CallerIsNotTheOwner();
abstract contract Ownable {
address _owner;
constructor() {
_owner = msg.sender;
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
if (msg.sender != _owner) revert CallerIsNotTheOwner();
_;
}
function transferOwnership(address newOwner) external onlyOwner {
_owner = newOwner;
}
}
// 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 (last updated v4.5.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import '@chainlink/contracts/src/v0.8/VRFConsumerBase.sol';
import './Ownable.sol';
error RandomSeedNotSet();
error RandomSeedAlreadySet();
contract VRFBase is VRFConsumerBase, Ownable {
bytes32 private immutable keyHash;
uint256 private immutable fee;
uint256 public randomSeed;
constructor(
bytes32 keyHash_,
uint256 fee_,
address vrfCoordinator_,
address link_
) VRFConsumerBase(vrfCoordinator_, link_) {
keyHash = keyHash_;
fee = fee_;
}
/* ------------- Owner ------------- */
function requestRandomSeed() external payable virtual onlyOwner whenRandomSeedUnset {
requestRandomness(keyHash, fee);
}
// this function should not be needed and is just an emergency fail-safe if
// for some reason chainlink is not able to fulfill the randomness callback
function forceFulfillRandomness() external payable virtual onlyOwner whenRandomSeedUnset {
randomSeed = uint256(blockhash(block.number - 1));
}
/* ------------- Internal ------------- */
function fulfillRandomness(bytes32, uint256 randomNumber) internal virtual override {
randomSeed = randomNumber;
}
function _shiftRandomSeed(uint256 randomNumber) internal {
randomSeed = uint256(keccak256(abi.encode(randomSeed, randomNumber)));
}
/* ------------- View ------------- */
function randomSeedSet() public view returns (bool) {
return randomSeed > 0;
}
/* ------------- Modifier ------------- */
modifier whenRandomSeedSet() {
if (!randomSeedSet()) revert RandomSeedNotSet();
_;
}
modifier whenRandomSeedUnset() {
if (randomSeedSet()) revert RandomSeedAlreadySet();
_;
}
}
// get your shit together Chainlink...
contract VRFBaseMainnet is
VRFBase(
0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445,
2 * 1e18,
0xf0d54349aDdcf704F77AE15b96510dEA15cb7952,
0x514910771AF9Ca656af840dff83E8264EcF986CA
)
{
}
contract VRFBaseRinkeby is
VRFBase(
0x2ed0feb3e7fd2022120aa84fab1945545a9f2ffc9076fd6156fa96eaff4c1311,
0.1 * 1e18,
0xb3dCcb4Cf7a26f6cf6B120Cf5A73875B7BBc655B,
0x01BE23585060835E02B77ef475b0Cc51aA1e0709
)
{}
contract VRFBaseMumbai is
VRFBase(
0x6e75b569a01ef56d18cab6a8e71e6600d6ce853834d4a5748b720d06f878b3a4,
0.0001 * 1e18,
0x8C7382F9D8f56b33781fE506E897a4F1e2d17255,
0x326C977E6efc84E512bB9C30f76E30c160eD06FB
)
{}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import '@openzeppelin/contracts/access/AccessControl.sol';
import '@openzeppelin/contracts/token/ERC20/ERC20.sol';
contract Gouda is ERC20, AccessControl {
bytes32 constant MINT_AUTHORITY = keccak256('MINT_AUTHORITY');
bytes32 constant BURN_AUTHORITY = keccak256('BURN_AUTHORITY');
bytes32 constant TREASURY = keccak256('TREASURY');
address public multiSigTreasury = 0xFB79a928C5d6c5932Ba83Aa8C7145cBDCDb9fd2E;
constructor(address madmouse) ERC20('Gouda', 'GOUDA') {
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(MINT_AUTHORITY, madmouse);
_setupRole(BURN_AUTHORITY, madmouse);
_setupRole(TREASURY, multiSigTreasury);
_mint(multiSigTreasury, 200_000 * 1e18);
}
/* ------------- Restricted ------------- */
function mint(address user, uint256 amount) external onlyRole(MINT_AUTHORITY) {
_mint(user, amount);
}
/* ------------- ERC20Burnable ------------- */
function burnFrom(address account, uint256 amount) public {
if (!hasRole(BURN_AUTHORITY, msg.sender)) _spendAllowance(account, msg.sender, amount);
_burn(account, amount);
}
}
// 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
pragma solidity ^0.8.0;
import "./interfaces/LinkTokenInterface.sol";
import "./VRFRequestIDBase.sol";
/** ****************************************************************************
* @notice Interface for contracts using VRF randomness
* *****************************************************************************
* @dev PURPOSE
*
* @dev Reggie the Random Oracle (not his real job) wants to provide randomness
* @dev to Vera the verifier in such a way that Vera can be sure he's not
* @dev making his output up to suit himself. Reggie provides Vera a public key
* @dev to which he knows the secret key. Each time Vera provides a seed to
* @dev Reggie, he gives back a value which is computed completely
* @dev deterministically from the seed and the secret key.
*
* @dev Reggie provides a proof by which Vera can verify that the output was
* @dev correctly computed once Reggie tells it to her, but without that proof,
* @dev the output is indistinguishable to her from a uniform random sample
* @dev from the output space.
*
* @dev The purpose of this contract is to make it easy for unrelated contracts
* @dev to talk to Vera the verifier about the work Reggie is doing, to provide
* @dev simple access to a verifiable source of randomness.
* *****************************************************************************
* @dev USAGE
*
* @dev Calling contracts must inherit from VRFConsumerBase, and can
* @dev initialize VRFConsumerBase's attributes in their constructor as
* @dev shown:
*
* @dev contract VRFConsumer {
* @dev constuctor(<other arguments>, address _vrfCoordinator, address _link)
* @dev VRFConsumerBase(_vrfCoordinator, _link) public {
* @dev <initialization with other arguments goes here>
* @dev }
* @dev }
*
* @dev The oracle will have given you an ID for the VRF keypair they have
* @dev committed to (let's call it keyHash), and have told you the minimum LINK
* @dev price for VRF service. Make sure your contract has sufficient LINK, and
* @dev call requestRandomness(keyHash, fee, seed), where seed is the input you
* @dev want to generate randomness from.
*
* @dev Once the VRFCoordinator has received and validated the oracle's response
* @dev to your request, it will call your contract's fulfillRandomness method.
*
* @dev The randomness argument to fulfillRandomness is the actual random value
* @dev generated from your seed.
*
* @dev The requestId argument is generated from the keyHash and the seed by
* @dev makeRequestId(keyHash, seed). If your contract could have concurrent
* @dev requests open, you can use the requestId to track which seed is
* @dev associated with which randomness. See VRFRequestIDBase.sol for more
* @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind,
* @dev if your contract could have multiple requests in flight simultaneously.)
*
* @dev Colliding `requestId`s are cryptographically impossible as long as seeds
* @dev differ. (Which is critical to making unpredictable randomness! See the
* @dev next section.)
*
* *****************************************************************************
* @dev SECURITY CONSIDERATIONS
*
* @dev A method with the ability to call your fulfillRandomness method directly
* @dev could spoof a VRF response with any random value, so it's critical that
* @dev it cannot be directly called by anything other than this base contract
* @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method).
*
* @dev For your users to trust that your contract's random behavior is free
* @dev from malicious interference, it's best if you can write it so that all
* @dev behaviors implied by a VRF response are executed *during* your
* @dev fulfillRandomness method. If your contract must store the response (or
* @dev anything derived from it) and use it later, you must ensure that any
* @dev user-significant behavior which depends on that stored value cannot be
* @dev manipulated by a subsequent VRF request.
*
* @dev Similarly, both miners and the VRF oracle itself have some influence
* @dev over the order in which VRF responses appear on the blockchain, so if
* @dev your contract could have multiple VRF requests in flight simultaneously,
* @dev you must ensure that the order in which the VRF responses arrive cannot
* @dev be used to manipulate your contract's user-significant behavior.
*
* @dev Since the ultimate input to the VRF is mixed with the block hash of the
* @dev block in which the request is made, user-provided seeds have no impact
* @dev on its economic security properties. They are only included for API
* @dev compatability with previous versions of this contract.
*
* @dev Since the block hash of the block which contains the requestRandomness
* @dev call is mixed into the input to the VRF *last*, a sufficiently powerful
* @dev miner could, in principle, fork the blockchain to evict the block
* @dev containing the request, forcing the request to be included in a
* @dev different block with a different hash, and therefore a different input
* @dev to the VRF. However, such an attack would incur a substantial economic
* @dev cost. This cost scales with the number of blocks the VRF oracle waits
* @dev until it calls responds to a request.
*/
abstract contract VRFConsumerBase is VRFRequestIDBase {
/**
* @notice fulfillRandomness handles the VRF response. Your contract must
* @notice implement it. See "SECURITY CONSIDERATIONS" above for important
* @notice principles to keep in mind when implementing your fulfillRandomness
* @notice method.
*
* @dev VRFConsumerBase expects its subcontracts to have a method with this
* @dev signature, and will call it once it has verified the proof
* @dev associated with the randomness. (It is triggered via a call to
* @dev rawFulfillRandomness, below.)
*
* @param requestId The Id initially returned by requestRandomness
* @param randomness the VRF output
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal virtual;
/**
* @dev In order to keep backwards compatibility we have kept the user
* seed field around. We remove the use of it because given that the blockhash
* enters later, it overrides whatever randomness the used seed provides.
* Given that it adds no security, and can easily lead to misunderstandings,
* we have removed it from usage and can now provide a simpler API.
*/
uint256 private constant USER_SEED_PLACEHOLDER = 0;
/**
* @notice requestRandomness initiates a request for VRF output given _seed
*
* @dev The fulfillRandomness method receives the output, once it's provided
* @dev by the Oracle, and verified by the vrfCoordinator.
*
* @dev The _keyHash must already be registered with the VRFCoordinator, and
* @dev the _fee must exceed the fee specified during registration of the
* @dev _keyHash.
*
* @dev The _seed parameter is vestigial, and is kept only for API
* @dev compatibility with older versions. It can't *hurt* to mix in some of
* @dev your own randomness, here, but it's not necessary because the VRF
* @dev oracle will mix the hash of the block containing your request into the
* @dev VRF seed it ultimately uses.
*
* @param _keyHash ID of public key against which randomness is generated
* @param _fee The amount of LINK to send with the request
*
* @return requestId unique ID for this request
*
* @dev The returned requestId can be used to distinguish responses to
* @dev concurrent requests. It is passed as the first argument to
* @dev fulfillRandomness.
*/
function requestRandomness(bytes32 _keyHash, uint256 _fee) internal returns (bytes32 requestId) {
LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER));
// This is the seed passed to VRFCoordinator. The oracle will mix this with
// the hash of the block containing this request to obtain the seed/input
// which is finally passed to the VRF cryptographic machinery.
uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]);
// nonces[_keyHash] must stay in sync with
// VRFCoordinator.nonces[_keyHash][this], which was incremented by the above
// successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest).
// This provides protection against the user repeating their input seed,
// which would result in a predictable/duplicate output, if multiple such
// requests appeared in the same block.
nonces[_keyHash] = nonces[_keyHash] + 1;
return makeRequestId(_keyHash, vRFSeed);
}
LinkTokenInterface internal immutable LINK;
address private immutable vrfCoordinator;
// Nonces for each VRF key from which randomness has been requested.
//
// Must stay in sync with VRFCoordinator[_keyHash][this]
mapping(bytes32 => uint256) /* keyHash */ /* nonce */
private nonces;
/**
* @param _vrfCoordinator address of VRFCoordinator contract
* @param _link address of LINK token contract
*
* @dev https://docs.chain.link/docs/link-token-contracts
*/
constructor(address _vrfCoordinator, address _link) {
vrfCoordinator = _vrfCoordinator;
LINK = LinkTokenInterface(_link);
}
// rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF
// proof. rawFulfillRandomness then calls fulfillRandomness, after validating
// the origin of the call
function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external {
require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill");
fulfillRandomness(requestId, randomness);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface LinkTokenInterface {
function allowance(address owner, address spender) external view returns (uint256 remaining);
function approve(address spender, uint256 value) external returns (bool success);
function balanceOf(address owner) external view returns (uint256 balance);
function decimals() external view returns (uint8 decimalPlaces);
function decreaseApproval(address spender, uint256 addedValue) external returns (bool success);
function increaseApproval(address spender, uint256 subtractedValue) external;
function name() external view returns (string memory tokenName);
function symbol() external view returns (string memory tokenSymbol);
function totalSupply() external view returns (uint256 totalTokensIssued);
function transfer(address to, uint256 value) external returns (bool success);
function transferAndCall(
address to,
uint256 value,
bytes calldata data
) external returns (bool success);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool success);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract VRFRequestIDBase {
/**
* @notice returns the seed which is actually input to the VRF coordinator
*
* @dev To prevent repetition of VRF output due to repetition of the
* @dev user-supplied seed, that seed is combined in a hash with the
* @dev user-specific nonce, and the address of the consuming contract. The
* @dev risk of repetition is mostly mitigated by inclusion of a blockhash in
* @dev the final seed, but the nonce does protect against repetition in
* @dev requests which are included in a single block.
*
* @param _userSeed VRF seed input provided by user
* @param _requester Address of the requesting contract
* @param _nonce User-specific nonce at the time of the request
*/
function makeVRFInputSeed(
bytes32 _keyHash,
uint256 _userSeed,
address _requester,
uint256 _nonce
) internal pure returns (uint256) {
return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce)));
}
/**
* @notice Returns the id for this request
* @param _keyHash The serviceAgreement ID to be used for this request
* @param _vRFInputSeed The seed to be passed directly to the VRF
* @return The id for this request
*
* @dev Note that _vRFInputSeed is not the seed passed by the consuming
* @dev contract, but the one generated by makeVRFInputSeed
*/
function makeRequestId(bytes32 _keyHash, uint256 _vRFInputSeed) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (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 (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/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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);
}
// 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
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/utils/Address.sol';
import '@openzeppelin/contracts/utils/Strings.sol';
import './ERC721MLibrary.sol';
error IncorrectOwner();
error NonexistentToken();
error QueryForZeroAddress();
error TokenIdUnstaked();
error ExceedsStakingLimit();
error MintToZeroAddress();
error MintZeroQuantity();
error MintMaxSupplyReached();
error MintMaxWalletReached();
error CallerNotOwnerNorApproved();
error ApprovalToCaller();
error ApproveToCurrentOwner();
error TransferFromIncorrectOwner();
error TransferToNonERC721ReceiverImplementer();
error TransferToZeroAddress();
abstract contract ERC721M {
using Address for address;
using Strings for uint256;
using UserDataOps for uint256;
using TokenDataOps for uint256;
event Transfer(address indexed from, address indexed to, uint256 indexed id);
event Approval(address indexed owner, address indexed spender, uint256 indexed id);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
string public name;
string public symbol;
mapping(uint256 => address) public getApproved;
mapping(address => mapping(address => bool)) public isApprovedForAll;
uint256 public totalSupply;
uint256 immutable startingIndex;
uint256 immutable collectionSize;
uint256 immutable maxPerWallet;
// note: hard limit of 255, otherwise overflows can happen
uint256 constant stakingLimit = 100;
mapping(uint256 => uint256) internal _tokenData;
mapping(address => uint256) internal _userData;
constructor(
string memory name_,
string memory symbol_,
uint256 startingIndex_,
uint256 collectionSize_,
uint256 maxPerWallet_
) {
name = name_;
symbol = symbol_;
collectionSize = collectionSize_;
maxPerWallet = maxPerWallet_;
startingIndex = startingIndex_;
}
/* ------------- External ------------- */
function stake(uint256[] calldata tokenIds) external payable {
uint256 userData = _claimReward();
for (uint256 i; i < tokenIds.length; ++i) userData = _stake(msg.sender, tokenIds[i], userData);
_userData[msg.sender] = userData;
}
function unstake(uint256[] calldata tokenIds) external payable {
uint256 userData = _claimReward();
for (uint256 i; i < tokenIds.length; ++i) userData = _unstake(msg.sender, tokenIds[i], userData);
_userData[msg.sender] = userData;
}
function claimReward() external payable {
_userData[msg.sender] = _claimReward();
}
/* ------------- Private ------------- */
function _stake(
address from,
uint256 tokenId,
uint256 userData
) private returns (uint256) {
uint256 _numStaked = userData.numStaked();
uint256 tokenData = _tokenDataOf(tokenId);
address owner = tokenData.owner();
if (_numStaked >= stakingLimit) revert ExceedsStakingLimit();
if (owner != from) revert IncorrectOwner();
delete getApproved[tokenId];
// hook, used for reading DNA, updating role balances,
(uint256 userDataX, uint256 tokenDataX) = _beforeStakeDataTransform(tokenId, userData, tokenData);
(userData, tokenData) = applySafeDataTransform(userData, tokenData, userDataX, tokenDataX);
tokenData = tokenData.setstaked();
userData = userData.decreaseBalance(1).increaseNumStaked(1);
if (_numStaked == 0) userData = userData.setStakeStart(block.timestamp);
_tokenData[tokenId] = tokenData;
emit Transfer(from, address(this), tokenId);
return userData;
}
function _unstake(
address to,
uint256 tokenId,
uint256 userData
) private returns (uint256) {
uint256 tokenData = _tokenDataOf(tokenId);
address owner = tokenData.trueOwner();
bool isStaked = tokenData.staked();
if (owner != to) revert IncorrectOwner();
if (!isStaked) revert TokenIdUnstaked();
(uint256 userDataX, uint256 tokenDataX) = _beforeUnstakeDataTransform(tokenId, userData, tokenData);
(userData, tokenData) = applySafeDataTransform(userData, tokenData, userDataX, tokenDataX);
// if mintAndStake flag is set, we need to make sure that next tokenData is set
// because tokenData in this case is implicit and needs to carry over
if (tokenData.mintAndStake()) {
unchecked {
tokenData = _ensureTokenDataSet(tokenId + 1, tokenData).unsetMintAndStake();
}
}
tokenData = tokenData.unsetstaked();
userData = userData.increaseBalance(1).decreaseNumStaked(1).setStakeStart(block.timestamp);
_tokenData[tokenId] = tokenData;
emit Transfer(address(this), to, tokenId);
return userData;
}
/* ------------- Internal ------------- */
function _mintAndStake(
address to,
uint256 quantity,
bool stake_
) internal {
unchecked {
uint256 totalSupply_ = totalSupply;
uint256 startTokenId = startingIndex + totalSupply_;
uint256 userData = _userData[to];
uint256 numMinted_ = userData.numMinted();
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
if (totalSupply_ + quantity > collectionSize) revert MintMaxSupplyReached();
if (numMinted_ + quantity > maxPerWallet && address(this).code.length != 0) revert MintMaxWalletReached();
// don't update for airdrops
if (to == msg.sender) userData = userData.increaseNumMinted(quantity);
uint256 tokenData = TokenDataOps.newTokenData(to, block.timestamp, stake_);
// don't have to care about next token data if only minting one
// could optimize to implicitly flag last token id of batch
if (quantity == 1) tokenData = tokenData.flagNextTokenDataSet();
if (stake_) {
uint256 _numStaked = userData.numStaked();
userData = claimReward(userData);
userData = userData.increaseNumStaked(quantity);
if (_numStaked + quantity > stakingLimit) revert ExceedsStakingLimit();
if (_numStaked == 0) userData = userData.setStakeStart(block.timestamp);
uint256 tokenId;
for (uint256 i; i < quantity; ++i) {
tokenId = startTokenId + i;
(userData, tokenData) = _beforeStakeDataTransform(tokenId, userData, tokenData);
emit Transfer(address(0), to, tokenId);
emit Transfer(to, address(this), tokenId);
}
} else {
userData = userData.increaseBalance(quantity);
for (uint256 i; i < quantity; ++i) emit Transfer(address(0), to, startTokenId + i);
}
_userData[to] = userData;
_tokenData[startTokenId] = tokenData;
totalSupply += quantity;
}
}
function _claimReward() internal returns (uint256) {
uint256 userData = _userData[msg.sender];
return claimReward(userData);
}
function claimReward(uint256 userData) private returns (uint256) {
uint256 reward = _pendingReward(msg.sender, userData);
userData = userData.setLastClaimed(block.timestamp);
_payoutReward(msg.sender, reward);
return userData;
}
function _tokenDataOf(uint256 tokenId) public view returns (uint256) {
if (!_exists(tokenId)) revert NonexistentToken();
for (uint256 curr = tokenId; ; curr--) {
uint256 tokenData = _tokenData[curr];
if (tokenData != 0) return (curr == tokenId) ? tokenData : tokenData.copy();
}
// unreachable
return 0;
}
function _exists(uint256 tokenId) internal view returns (bool) {
return startingIndex <= tokenId && tokenId < startingIndex + totalSupply;
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public {
// make sure no one is misled by token transfer events
if (to == address(this)) {
uint256 userData = _claimReward();
_userData[msg.sender] = _stake(msg.sender, tokenId, userData);
} else {
uint256 tokenData = _tokenDataOf(tokenId);
address owner = tokenData.owner();
bool isApprovedOrOwner = (msg.sender == owner ||
isApprovedForAll[owner][msg.sender] ||
getApproved[tokenId] == msg.sender);
if (!isApprovedOrOwner) revert CallerNotOwnerNorApproved();
if (to == address(0)) revert TransferToZeroAddress();
if (owner != from) revert TransferFromIncorrectOwner();
delete getApproved[tokenId];
unchecked {
_tokenData[tokenId] = _ensureTokenDataSet(tokenId + 1, tokenData)
.setOwner(to)
.setLastTransfer(block.timestamp)
.incrementOwnerCount();
}
_userData[from] = _userData[from].decreaseBalance(1);
_userData[to] = _userData[to].increaseBalance(1);
emit Transfer(from, to, tokenId);
}
}
function _ensureTokenDataSet(uint256 tokenId, uint256 tokenData) private returns (uint256) {
if (!tokenData.nextTokenDataSet() && _tokenData[tokenId] == 0 && _exists(tokenId))
_tokenData[tokenId] = tokenData.copy(); // make sure to not pass any token specific data in
return tokenData.flagNextTokenDataSet();
}
/* ------------- Virtual (hooks) ------------- */
function _beforeStakeDataTransform(
uint256, // tokenId
uint256 userData,
uint256 tokenData
) internal view virtual returns (uint256, uint256) {
return (userData, tokenData);
}
function _beforeUnstakeDataTransform(
uint256, // tokenId
uint256 userData,
uint256 tokenData
) internal view virtual returns (uint256, uint256) {
return (userData, tokenData);
}
function _pendingReward(address, uint256 userData) internal view virtual returns (uint256);
function _payoutReward(address user, uint256 reward) internal virtual;
/* ------------- View ------------- */
function ownerOf(uint256 tokenId) external view returns (address) {
return _tokenDataOf(tokenId).owner();
}
function trueOwnerOf(uint256 tokenId) external view returns (address) {
return _tokenDataOf(tokenId).trueOwner();
}
function balanceOf(address owner) external view returns (uint256) {
if (owner == address(0)) revert QueryForZeroAddress();
return _userData[owner].balance();
}
function numStaked(address user) external view returns (uint256) {
return _userData[user].numStaked();
}
function numOwned(address user) external view returns (uint256) {
uint256 userData = _userData[user];
return userData.balance() + userData.numStaked();
}
function numMinted(address user) external view returns (uint256) {
return _userData[user].numMinted();
}
function pendingReward(address user) external view returns (uint256) {
return _pendingReward(user, _userData[user]);
}
// O(N) read-only functions
function tokenIdsOf(address user, uint256 type_) external view returns (uint256[] memory) {
unchecked {
uint256 numTotal = type_ == 0 ? this.balanceOf(user) : type_ == 1
? this.numStaked(user)
: this.numOwned(user);
uint256[] memory ids = new uint256[](numTotal);
if (numTotal == 0) return ids;
uint256 count;
for (uint256 i = startingIndex; i < totalSupply + startingIndex; ++i) {
uint256 tokenData = _tokenDataOf(i);
if (user == tokenData.trueOwner()) {
bool staked = tokenData.staked();
if ((type_ == 0 && !staked) || (type_ == 1 && staked) || type_ == 2) {
ids[count++] = i;
if (numTotal == count) return ids;
}
}
}
return ids;
}
}
function totalNumStaked() external view returns (uint256) {
unchecked {
uint256 count;
for (uint256 i = startingIndex; i < startingIndex + totalSupply; ++i) {
if (_tokenDataOf(i).staked()) ++count;
}
return count;
}
}
/* ------------- ERC721 ------------- */
function tokenURI(uint256 id) public view virtual returns (string memory);
function supportsInterface(bytes4 interfaceId) external view virtual returns (bool) {
return
interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165
interfaceId == 0x80ac58cd || // ERC165 Interface ID for ERC721
interfaceId == 0x5b5e139f; // ERC165 Interface ID for ERC721Metadata
}
function approve(address spender, uint256 tokenId) external {
address owner = _tokenDataOf(tokenId).owner();
if (msg.sender != owner && !isApprovedForAll[owner][msg.sender]) revert CallerNotOwnerNorApproved();
getApproved[tokenId] = spender;
emit Approval(owner, spender, tokenId);
}
function setApprovalForAll(address operator, bool approved) external {
isApprovedForAll[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external {
safeTransferFrom(from, to, tokenId, '');
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory data
) public {
transferFrom(from, to, tokenId);
if (
to.code.length != 0 &&
IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, data) !=
IERC721Receiver(to).onERC721Received.selector
) revert TransferToNonERC721ReceiverImplementer();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
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
// 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
pragma solidity ^0.8.0;
// # ERC721M.sol
//
// _tokenData layout:
// 0x________/cccccbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
// a [ 0] (uint160): address #owner (owner of token id)
// b [160] (uint40): timestamp #lastTransfer (timestamp since the last transfer)
// c [200] (uint20): #ownerCount (number of total owners of token)
// f [220] (uint1): #staked flag (flag whether id has been staked) Note: this carries over when calling 'ownerOf'
// f [221] (uint1): #mintAndStake flag (flag whether to carry over stake flag when calling tokenDataOf; used for mintAndStake and boost)
// e [222] (uint1): #nextTokenDataSet flag (flag whether the data of next token id has already been set)
// _ [224] (uint32): arbitrary data
uint256 constant RESTRICTED_TOKEN_DATA = 0x00000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
// # MadMouse.sol
//
// _tokenData (metadata) layout:
// 0xefg00000________________________________________________________
// e [252] (uint4): #level (mouse level) [0...2] (must be 0-based)
// f [248] (uint4): #role (mouse role) [1...5] (must start at 1)
// g [244] (uint4): #rarity (mouse rarity) [0...3]
struct TokenData {
address owner;
uint256 lastTransfer;
uint256 ownerCount;
bool staked;
bool mintAndStake;
bool nextTokenDataSet;
uint256 level;
uint256 role;
uint256 rarity;
}
// # ERC721M.sol
//
// _userData layout:
// 0x________________________________ddccccccccccbbbbbbbbbbaaaaaaaaaa
// a [ 0] (uint32): #balance (owner ERC721 balance)
// b [ 40] (uint40): timestamp #stakeStart (timestamp when stake started)
// c [ 80] (uint40): timestamp #lastClaimed (timestamp when user last claimed rewards)
// d [120] (uint8): #numStaked (balance count of all staked tokens)
// _ [128] (uint128): arbitrary data
uint256 constant RESTRICTED_USER_DATA = 0x00000000000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
// # MadMouseStaking.sol
//
// _userData (boost) layout:
// 0xttttttttt/o/rriiffgghhaabbccddee________________________________
// a-e [128] (5x uint8): #roleBalances (balance of all staked roles)
// f-h [168] (3x uint8): #levelBalances (balance of all staked levels)
// i [192] (uint8): #specialGuestIndex (signals whether the user claims to hold a token of a certain collection)
// r [200] (uint10): #rarityPoints (counter of rare traits; 1 is rare, 2 is super-rare, 3 is ultra-rare)
// o [210] (uint8): #OGCount (counter of rare traits; 1 is rare, 2 is super-rare, 3 is ultra-rare)
// t [218] (uint38): timestamp #boostStart (timestamp of when the boost by burning tokens of affiliate collections started)
struct UserData {
uint256 balance;
uint256 stakeStart;
uint256 lastClaimed;
uint256 numStaked;
uint256[5] roleBalances;
uint256 uniqueRoleCount; // inferred
uint256[3] levelBalances;
uint256 specialGuestIndex;
uint256 rarityPoints;
uint256 OGCount;
uint256 boostStart;
}
function applySafeDataTransform(
uint256 userData,
uint256 tokenData,
uint256 userDataTransformed,
uint256 tokenDataTransformed
) pure returns (uint256, uint256) {
// mask transformed data in order to leave base data untouched in any case
userData = (userData & RESTRICTED_USER_DATA) | (userDataTransformed & ~RESTRICTED_USER_DATA);
tokenData = (tokenData & RESTRICTED_TOKEN_DATA) | (tokenDataTransformed & ~RESTRICTED_TOKEN_DATA);
return (userData, tokenData);
}
// @note: many of these are unchecked, because safemath wouldn't be able to guard
// overflows while updating bitmaps unless custom checks were to be implemented
library UserDataOps {
function getUserData(uint256 userData) internal pure returns (UserData memory) {
return
UserData({
balance: UserDataOps.balance(userData),
stakeStart: UserDataOps.stakeStart(userData),
lastClaimed: UserDataOps.lastClaimed(userData),
numStaked: UserDataOps.numStaked(userData),
roleBalances: UserDataOps.roleBalances(userData),
uniqueRoleCount: UserDataOps.uniqueRoleCount(userData),
levelBalances: UserDataOps.levelBalances(userData),
specialGuestIndex: UserDataOps.specialGuestIndex(userData),
rarityPoints: UserDataOps.rarityPoints(userData),
OGCount: UserDataOps.OGCount(userData),
boostStart: UserDataOps.boostStart(userData)
});
}
function balance(uint256 userData) internal pure returns (uint256) {
return userData & 0xFFFFF;
}
function increaseBalance(uint256 userData, uint256 amount) internal pure returns (uint256) {
unchecked {
return userData + amount;
}
}
function decreaseBalance(uint256 userData, uint256 amount) internal pure returns (uint256) {
unchecked {
return userData - amount;
}
}
function numMinted(uint256 userData) internal pure returns (uint256) {
return (userData >> 20) & 0xFFFFF;
}
function increaseNumMinted(uint256 userData, uint256 amount) internal pure returns (uint256) {
unchecked {
return userData + (amount << 20);
}
}
function stakeStart(uint256 userData) internal pure returns (uint256) {
return (userData >> 40) & 0xFFFFFFFFFF;
}
function setStakeStart(uint256 userData, uint256 timestamp) internal pure returns (uint256) {
return (userData & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000FFFFFFFFFF) | (timestamp << 40);
}
function lastClaimed(uint256 userData) internal pure returns (uint256) {
return (userData >> 80) & 0xFFFFFFFFFF;
}
function setLastClaimed(uint256 userData, uint256 timestamp) internal pure returns (uint256) {
return (userData & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000FFFFFFFFFFFFFFFFFFFF) | (timestamp << 80);
}
function numStaked(uint256 userData) internal pure returns (uint256) {
return (userData >> 120) & 0xFF;
}
function increaseNumStaked(uint256 userData, uint256 amount) internal pure returns (uint256) {
unchecked {
return userData + (amount << 120);
}
}
function decreaseNumStaked(uint256 userData, uint256 amount) internal pure returns (uint256) {
unchecked {
return userData - (amount << 120);
}
}
function roleBalances(uint256 userData) internal pure returns (uint256[5] memory balances) {
balances = [
(userData >> (128 + 0)) & 0xFF,
(userData >> (128 + 8)) & 0xFF,
(userData >> (128 + 16)) & 0xFF,
(userData >> (128 + 24)) & 0xFF,
(userData >> (128 + 32)) & 0xFF
];
}
// trait counts are set through hook in madmouse contract (MadMouse::_beforeStakeDataTransform)
function uniqueRoleCount(uint256 userData) internal pure returns (uint256) {
unchecked {
return (toUInt256((userData >> (128)) & 0xFF > 0) +
toUInt256((userData >> (128 + 8)) & 0xFF > 0) +
toUInt256((userData >> (128 + 16)) & 0xFF > 0) +
toUInt256((userData >> (128 + 24)) & 0xFF > 0) +
toUInt256((userData >> (128 + 32)) & 0xFF > 0));
}
}
function levelBalances(uint256 userData) internal pure returns (uint256[3] memory balances) {
unchecked {
balances = [
(userData >> (168 + 0)) & 0xFF,
(userData >> (168 + 8)) & 0xFF,
(userData >> (168 + 16)) & 0xFF
];
}
}
// depends on the levels of the staked tokens (also set in hook MadMouse::_beforeStakeDataTransform)
// counts the base reward, depending on the levels of staked ids
function baseReward(uint256 userData) internal pure returns (uint256) {
unchecked {
return (((userData >> (168)) & 0xFF) +
(((userData >> (168 + 8)) & 0xFF) << 1) +
(((userData >> (168 + 16)) & 0xFF) << 2));
}
}
function rarityPoints(uint256 userData) internal pure returns (uint256) {
return (userData >> 200) & 0x3FF;
}
function specialGuestIndex(uint256 userData) internal pure returns (uint256) {
return (userData >> 192) & 0xFF;
}
function setSpecialGuestIndex(uint256 userData, uint256 index) internal pure returns (uint256) {
return (userData & ~uint256(0xFF << 192)) | (index << 192);
}
function boostStart(uint256 userData) internal pure returns (uint256) {
return (userData >> 218) & 0xFFFFFFFFFF;
}
function setBoostStart(uint256 userData, uint256 timestamp) internal pure returns (uint256) {
return (userData & ~(uint256(0xFFFFFFFFFF) << 218)) | (timestamp << 218);
}
function OGCount(uint256 userData) internal pure returns (uint256) {
return (userData >> 210) & 0xFF;
}
// (should start at 128, 168; but role/level start at 1...)
function updateUserDataStake(uint256 userData, uint256 tokenData) internal pure returns (uint256) {
unchecked {
uint256 role = TokenDataOps.role(tokenData);
if (role > 0) {
userData += uint256(1) << (120 + (role << 3)); // roleBalances
userData += TokenDataOps.rarity(tokenData) << 200; // rarityPoints
}
if (TokenDataOps.mintAndStake(tokenData)) userData += uint256(1) << 210; // OGCount
userData += uint256(1) << (160 + (TokenDataOps.level(tokenData) << 3)); // levelBalances
return userData;
}
}
function updateUserDataUnstake(uint256 userData, uint256 tokenData) internal pure returns (uint256) {
unchecked {
uint256 role = TokenDataOps.role(tokenData);
if (role > 0) {
userData -= uint256(1) << (120 + (role << 3)); // roleBalances
userData -= TokenDataOps.rarity(tokenData) << 200; // rarityPoints
}
if (TokenDataOps.mintAndStake(tokenData)) userData -= uint256(1) << 210; // OG-count
userData -= uint256(1) << (160 + (TokenDataOps.level(tokenData) << 3)); // levelBalances
return userData;
}
}
function increaseLevelBalances(uint256 userData, uint256 tokenData) internal pure returns (uint256) {
unchecked {
return userData + (uint256(1) << (160 + (TokenDataOps.level(tokenData) << 3)));
}
}
function decreaseLevelBalances(uint256 userData, uint256 tokenData) internal pure returns (uint256) {
unchecked {
return userData - (uint256(1) << (160 + (TokenDataOps.level(tokenData) << 3)));
}
}
}
library TokenDataOps {
function getTokenData(uint256 tokenData) internal view returns (TokenData memory) {
return
TokenData({
owner: TokenDataOps.owner(tokenData),
lastTransfer: TokenDataOps.lastTransfer(tokenData),
ownerCount: TokenDataOps.ownerCount(tokenData),
staked: TokenDataOps.staked(tokenData),
mintAndStake: TokenDataOps.mintAndStake(tokenData),
nextTokenDataSet: TokenDataOps.nextTokenDataSet(tokenData),
level: TokenDataOps.level(tokenData),
role: TokenDataOps.role(tokenData),
rarity: TokenDataOps.rarity(tokenData)
});
}
function newTokenData(
address owner_,
uint256 lastTransfer_,
bool stake_
) internal pure returns (uint256) {
uint256 tokenData = (uint256(uint160(owner_)) | (lastTransfer_ << 160) | (uint256(1) << 200));
return stake_ ? setstaked(setMintAndStake(tokenData)) : tokenData;
}
function copy(uint256 tokenData) internal pure returns (uint256) {
// tokenData minus the token specific flags (4/2bits), i.e. only owner, lastTransfer, ownerCount
// stake flag (& mintAndStake flag) carries over if mintAndStake was called
return tokenData & (RESTRICTED_TOKEN_DATA >> (mintAndStake(tokenData) ? 2 : 4));
}
function owner(uint256 tokenData) internal view returns (address) {
if (staked(tokenData)) return address(this);
return trueOwner(tokenData);
}
function setOwner(uint256 tokenData, address owner_) internal pure returns (uint256) {
return (tokenData & 0xFFFFFFFFFFFFFFFFFFFFFFFF0000000000000000000000000000000000000000) | uint160(owner_);
}
function staked(uint256 tokenData) internal pure returns (bool) {
return ((tokenData >> 220) & uint256(1)) > 0; // Note: this can carry over when calling 'ownerOf'
}
function setstaked(uint256 tokenData) internal pure returns (uint256) {
return tokenData | (uint256(1) << 220);
}
function unsetstaked(uint256 tokenData) internal pure returns (uint256) {
return tokenData & ~(uint256(1) << 220);
}
function mintAndStake(uint256 tokenData) internal pure returns (bool) {
return ((tokenData >> 221) & uint256(1)) > 0;
}
function setMintAndStake(uint256 tokenData) internal pure returns (uint256) {
return tokenData | (uint256(1) << 221);
}
function unsetMintAndStake(uint256 tokenData) internal pure returns (uint256) {
return tokenData & ~(uint256(1) << 221);
}
function nextTokenDataSet(uint256 tokenData) internal pure returns (bool) {
return ((tokenData >> 222) & uint256(1)) > 0;
}
function flagNextTokenDataSet(uint256 tokenData) internal pure returns (uint256) {
return tokenData | (uint256(1) << 222); // nextTokenDatatSet flag (don't repeat the read/write)
}
function trueOwner(uint256 tokenData) internal pure returns (address) {
return address(uint160(tokenData));
}
function ownerCount(uint256 tokenData) internal pure returns (uint256) {
return (tokenData >> 200) & 0xFFFFF;
}
function incrementOwnerCount(uint256 tokenData) internal pure returns (uint256) {
uint256 newOwnerCount = min(ownerCount(tokenData) + 1, 0xFFFFF);
return (tokenData & ~(uint256(0xFFFFF) << 200)) | (newOwnerCount << 200);
}
function resetOwnerCount(uint256 tokenData) internal pure returns (uint256) {
uint256 count = min(ownerCount(tokenData), 2); // keep minter status
return (tokenData & ~(uint256(0xFFFFF) << 200)) | (count << 200);
}
function lastTransfer(uint256 tokenData) internal pure returns (uint256) {
return (tokenData >> 160) & 0xFFFFFFFFFF;
}
function setLastTransfer(uint256 tokenData, uint256 timestamp) internal pure returns (uint256) {
return (tokenData & 0xFFFFFFFFFFFFFF0000000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | (timestamp << 160);
}
// MadMouse
function level(uint256 tokenData) internal pure returns (uint256) {
unchecked {
return 1 + (tokenData >> 252);
}
}
function increaseLevel(uint256 tokenData) internal pure returns (uint256) {
unchecked {
return tokenData + (uint256(1) << 252);
}
}
function role(uint256 tokenData) internal pure returns (uint256) {
return (tokenData >> 248) & 0xF;
}
function rarity(uint256 tokenData) internal pure returns (uint256) {
return (tokenData >> 244) & 0xF;
}
// these slots should be are already 0
function setRoleAndRarity(uint256 tokenData, uint256 dna) internal pure returns (uint256) {
return ((tokenData & ~(uint256(0xFF) << 244)) | (DNAOps.toRole(dna) << 248) | (DNAOps.toRarity(dna) << 244));
}
}
library DNAOps {
function toRole(uint256 dna) internal pure returns (uint256) {
unchecked {
return 1 + ((dna & 0xFF) % 5);
}
}
function toRarity(uint256 dna) internal pure returns (uint256) {
uint256 dnaFur = (dna >> 8) & 0xFF;
if (dnaFur > 108) return 0;
if (dnaFur > 73) return 1;
if (dnaFur > 17) return 2;
return 3;
}
}
/* ------------- Helpers ------------- */
// more efficient https://github.com/ethereum/solidity/issues/659
function toUInt256(bool x) pure returns (uint256 r) {
assembly {
r := x
}
}
function min(uint256 a, uint256 b) pure returns (uint256) {
return a < b ? a : b;
}
function isValidString(string calldata str, uint256 maxLen) pure returns (bool) {
unchecked {
bytes memory b = bytes(str);
if (b.length < 1 || b.length > maxLen || b[0] == 0x20 || b[b.length - 1] == 0x20) return false;
bytes1 lastChar = b[0];
bytes1 char;
for (uint256 i; i < b.length; ++i) {
char = b[i];
if (
(char > 0x60 && char < 0x7B) || //a-z
(char > 0x40 && char < 0x5B) || //A-Z
(char == 0x20) || //space
(char > 0x2F && char < 0x3A) //9-0
) {
lastChar = char;
} else {
return false;
}
}
return true;
}
}
|
Special guest's staking interfaces
|
interface ISVSGraveyard {
function getBuriedCount(address burier) external view returns (uint256);
}
| 393,061
|
./partial_match/56/0x43f001914C7d347D152f296E8539086fE49F8bD6/sources/NorseFinance.sol
|
Determine the prior number of votes for an account as of a block number Block number must be a finalized block or else this function will revert to prevent misinformation. account The address of the account to check blockNumber The block number to get the vote balance at return The number of votes the account had as of the given block/ First check most recent balance Next check implicit zero balance
|
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "NFI::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
| 11,125,735
|
./full_match/3/0xb414D538Ca91d774845184a1DA39172b4FEA3dC4/sources/contracts/PrimeNft.sol
|
Initializer function./
|
function initialize() initializer public {
__ERC721_init("Valor Prime NonFungibles", "VPT");
}
| 8,214,277
|
./full_match/4/0x514fd962486337d597b43cbFC1F204Ca1EB8493B/sources/erc721a/ERC721A.sol
|
Directly sets the extra data for the ownership data `index`./ Cast `extraData` with assembly to avoid redundant masking.
|
function _setExtraDataAt(uint256 index, uint24 extraData) internal virtual {
uint256 packed = _packedOwnerships[index];
if (packed == 0) revert OwnershipNotInitializedForExtraData();
uint256 extraDataCasted;
assembly {
extraDataCasted := extraData
}
packed = (packed & _BITMASK_EXTRA_DATA_COMPLEMENT) | (extraDataCasted << _BITPOS_EXTRA_DATA);
_packedOwnerships[index] = packed;
}
| 730,070
|
pragma solidity 0.5.12;
import "./library/ReentrancyGuard.sol";
import "./library/Pausable.sol";
import "./library/ERC20SafeTransfer.sol";
import "./library/SafeMath.sol";
import "./interface/IDispatcher.sol";
import "./interface/IHandler.sol";
contract DToken is ReentrancyGuard, Pausable, ERC20SafeTransfer {
using SafeMath for uint256;
// --- Data ---
bool private initialized; // Flag of initialize data
struct DTokenData {
uint256 exchangeRate;
uint256 totalInterest;
}
DTokenData public data;
address public feeRecipient;
mapping(bytes4 => uint256) public originationFee; // Trade fee
address public dispatcher;
address public token;
address public swapModel;
uint256 constant BASE = 10**18;
// --- ERC20 Data ---
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
struct Balance {
uint256 value;
uint256 exchangeRate;
uint256 interest;
}
mapping(address => Balance) public balances;
mapping(address => mapping(address => uint256)) public allowance;
// --- User Triggered Event ---
event Approval(address indexed src, address indexed guy, uint256 wad);
event Transfer(address indexed src, address indexed dst, uint256 wad);
event Interest(
address indexed src,
uint256 interest,
uint256 increase,
uint256 totalInterest
);
event Mint(
address indexed account,
uint256 indexed pie,
uint256 wad,
uint256 totalSupply,
uint256 exchangeRate
);
event Redeem(
address indexed account,
uint256 indexed pie,
uint256 wad,
uint256 totalSupply,
uint256 exchangeRate
);
// --- Admin Triggered Event ---
event Rebalance(
address[] withdraw,
uint256[] withdrawAmount,
address[] supply,
uint256[] supplyAmount
);
event TransferFee(address token, address feeRecipient, uint256 amount);
event FeeRecipientSet(address oldFeeRecipient, address newFeeRecipient);
event NewDispatcher(address oldDispatcher, address Dispatcher);
event NewSwapModel(address _oldSwapModel, address _newSwapModel);
event NewOriginationFee(
bytes4 sig,
uint256 oldOriginationFeeMantissa,
uint256 newOriginationFeeMantissa
);
/**
* The constructor is used here to ensure that the implementation
* contract is initialized. An uncontrolled implementation
* contract might lead to misleading state
* for users who accidentally interact with it.
*/
constructor(
string memory _name,
string memory _symbol,
address _token,
address _dispatcher
) public {
initialize(_name, _symbol, _token, _dispatcher);
}
/************************/
/*** Admin Operations ***/
/************************/
// --- Init ---
function initialize(
string memory _name,
string memory _symbol,
address _token,
address _dispatcher
) public {
require(!initialized, "initialize: Already initialized!");
owner = msg.sender;
initReentrancyStatus();
feeRecipient = address(this);
name = _name;
symbol = _symbol;
token = _token;
dispatcher = _dispatcher;
decimals = IERC20(_token).decimals();
data.exchangeRate = BASE;
initialized = true;
emit NewDispatcher(address(0), _dispatcher);
}
/**
* @dev Authorized function to set a new dispatcher.
* @param _newDispatcher New dispatcher contract address.
*/
function updateDispatcher(address _newDispatcher) external auth {
address _oldDispatcher = dispatcher;
require(
_newDispatcher != address(0) && _newDispatcher != _oldDispatcher,
"updateDispatcher: dispatcher can be not set to 0 or the current one."
);
dispatcher = _newDispatcher;
emit NewDispatcher(_oldDispatcher, _newDispatcher);
}
/**
* @dev Authorized function to set a new model contract to swap.
* @param _newSwapModel New model contract address.
*/
function setSwapModel(address _newSwapModel) external auth {
address _oldSwapModel = swapModel;
require(
_newSwapModel != address(0) && _newSwapModel != _oldSwapModel,
"setSwapModel: swap model can be not set to 0 or the current one."
);
swapModel = _newSwapModel;
emit NewSwapModel(_oldSwapModel, _newSwapModel);
}
/**
* @dev Authorized function to set a new fee recipient.
* @param _newFeeRecipient The address allowed to collect fees.
*/
function setFeeRecipient(address _newFeeRecipient) external auth {
address _oldFeeRecipient = feeRecipient;
require(
_newFeeRecipient != address(0) &&
_newFeeRecipient != _oldFeeRecipient,
"setFeeRecipient: feeRecipient can be not set to 0 or the current one."
);
feeRecipient = _newFeeRecipient;
emit FeeRecipientSet(_oldFeeRecipient, feeRecipient);
}
/**
* @dev Authorized function to set a new origination fee.
* @param _sig function signature.
* @param _newOriginationFee New trading fee ratio, scaled by 1e18.
*/
function updateOriginationFee(bytes4 _sig, uint256 _newOriginationFee)
external
auth
{
require(
_newOriginationFee < BASE,
"updateOriginationFee: incorrect fee."
);
uint256 _oldOriginationFee = originationFee[_sig];
require(
_oldOriginationFee != _newOriginationFee,
"updateOriginationFee: fee has already set to this value."
);
originationFee[_sig] = _newOriginationFee;
emit NewOriginationFee(_sig, _oldOriginationFee, _newOriginationFee);
}
/**
* @dev Authorized function to swap airdrop tokens to increase yield.
* @param _token Airdrop token to swap from.
* @param _amount Amount to swap.
*/
function swap(address _token, uint256 _amount) external auth {
require(swapModel != address(0), "swap: no swap model available!");
(bool success, ) = swapModel.delegatecall(
abi.encodeWithSignature("swap(address,uint256)", _token, _amount)
);
require(success, "swap: swap to another token failed!");
}
/**
* @dev Authorized function to transfer token out.
* @param _token The underlying token.
* @param _amount Amount to transfer.
*/
function transferFee(address _token, uint256 _amount) external auth {
require(
feeRecipient != address(this),
"transferFee: Can not transfer fee back to this contract."
);
require(
doTransferOut(_token, feeRecipient, _amount),
"transferFee: Token transfer out of contract failed."
);
emit TransferFee(_token, feeRecipient, _amount);
}
/**
* @dev Authorized function to rebalance underlying token between handlers.
* @param _withdraw From which handlers to withdraw.
* @param _withdrawAmount Amounts to withdraw.
* @param _deposit To which handlers to deposit.
* @param _depositAmount Amounts to deposit.
*/
function rebalance(
address[] calldata _withdraw,
uint256[] calldata _withdrawAmount,
address[] calldata _deposit,
uint256[] calldata _depositAmount
) external auth {
require(
_withdraw.length == _withdrawAmount.length &&
_deposit.length == _depositAmount.length,
"rebalance: the length of addresses and amounts must match."
);
address _token = token;
address _defaultHandler = IDispatcher(dispatcher).defaultHandler();
// Start withdrawing
uint256[] memory _realWithdrawAmount = new uint256[](
_withdrawAmount.length
);
for (uint256 i = 0; i < _withdraw.length; i++) {
// No need to withdraw from default handler, all withdrown tokens go to it
if (_withdrawAmount[i] == 0 || _defaultHandler == _withdraw[i])
continue;
// Check whether we want to withdraw all
_realWithdrawAmount[i] = _withdrawAmount[i] == uint256(-1)
? IHandler(_withdraw[i]).getRealBalance(_token)
: _withdrawAmount[i];
// Ensure we get the exact amount we wanted
// Will fail if there is fee for withdraw
// For withdraw all (-1) we check agaist the real amount
require(
IHandler(_withdraw[i]).withdraw(_token, _withdrawAmount[i]) ==
_realWithdrawAmount[i],
"rebalance: actual withdrown amount does not match the wanted"
);
// Transfer to the default handler
require(
doTransferFrom(
_token,
_withdraw[i],
_defaultHandler,
_realWithdrawAmount[i]
),
"rebalance: transfer to default handler failed"
);
}
// Start depositing
for (uint256 i = 0; i < _deposit.length; i++) {
require(
IDispatcher(dispatcher).isHandlerActive(_deposit[i]) &&
IHandler(_deposit[i]).tokenIsEnabled(_token),
"rebalance: both handler and token must be enabled"
);
// No need to deposit into default handler, it has been there already.
if (_depositAmount[i] == 0 || _defaultHandler == _deposit[i])
continue;
// Transfer from default handler to the target one.
require(
doTransferFrom(
_token,
_defaultHandler,
_deposit[i],
_depositAmount[i]
),
"rebalance: transfer to target handler failed"
);
// Deposit into the target lending market
require(
IHandler(_deposit[i]).deposit(_token, _depositAmount[i]) ==
_depositAmount[i],
"rebalance: deposit to the target protocal failed"
);
}
emit Rebalance(_withdraw, _withdrawAmount, _deposit, _depositAmount);
}
/*************************************/
/*** Helpers only for internal use ***/
/*************************************/
function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x.mul(y) / BASE;
}
function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x.mul(BASE).div(y);
}
function rdivup(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x.mul(BASE).add(y.sub(1)).div(y);
}
/**
* @dev Current newest exchange rate, scaled by 1e18.
*/
function getCurrentExchangeRate() internal returns (uint256) {
address[] memory _handlers = getHandlers();
return getCurrentExchangeRateByHandler(_handlers, token);
}
/**
* @dev Calculate the exchange rate according to handlers and their token balance.
* @param _handlers The list of handlers.
* @param _token The underlying token.
* @return Current exchange rate between token and dToken.
*/
function getCurrentExchangeRateByHandler(
address[] memory _handlers,
address _token
) internal returns (uint256) {
uint256 _totalToken = 0;
// Get the total underlying token amount from handlers
for (uint256 i = 0; i < _handlers.length; i++)
_totalToken = _totalToken.add(
IHandler(_handlers[i]).getRealBalance(_token)
);
// Reset exchange rate to 1 when there is no dToken left
uint256 _exchangeRate = (totalSupply == 0)
? BASE
: rdiv(_totalToken, totalSupply);
require(_exchangeRate > 0, "Exchange rate should not be 0!");
return _exchangeRate;
}
/**
* @dev Update global and user's accrued interest.
* @param _account User account.
* @param _exchangeRate Current exchange rate.
*/
function updateInterest(address _account, uint256 _exchangeRate) internal {
Balance storage _balance = balances[_account];
// There have been some interest since last time
if (
_balance.exchangeRate > 0 && _exchangeRate > _balance.exchangeRate
) {
uint256 _interestIncrease = rmul(
_exchangeRate.sub(_balance.exchangeRate),
_balance.value
);
// Update user's accrued interst
_balance.interest = _balance.interest.add(_interestIncrease);
// Update global accrued interst
data.totalInterest = data.totalInterest.add(_interestIncrease);
emit Interest(
_account,
_balance.interest,
_interestIncrease,
data.totalInterest
);
}
// Update the exchange rate accordingly
_balance.exchangeRate = _exchangeRate;
data.exchangeRate = _exchangeRate;
}
/**
* @dev Internal function to withdraw specific amount underlying token from handlers,
* all tokens withdrown will be put into default handler.
* @param _defaultHandler default handler acting as temporary pool.
* @param _handlers list of handlers to withdraw.
* @param _amounts list of amounts to withdraw.
* @return The actual withdrown amount.
*/
function withdrawFromHandlers(
address _defaultHandler,
address[] memory _handlers,
uint256[] memory _amounts
) internal returns (uint256 _totalWithdrown) {
address _token = token;
uint256 _withdrown;
for (uint256 i = 0; i < _handlers.length; i++) {
if (_amounts[i] == 0) continue;
// The handler withdraw underlying token from the market.
_withdrown = IHandler(_handlers[i]).withdraw(_token, _amounts[i]);
require(
_withdrown > 0,
"withdrawFromHandlers: handler withdraw failed"
);
// Transfer token from other handlers to default handler
// Default handler acts as a temporary pool here
if (_defaultHandler != _handlers[i]) {
require(
doTransferFrom(
_token,
_handlers[i],
_defaultHandler,
_withdrown
),
"withdrawFromHandlers: transfer to default handler failed"
);
}
_totalWithdrown = _totalWithdrown.add(_withdrown);
}
}
/***********************/
/*** User Operations ***/
/***********************/
struct MintLocalVars {
address token;
address[] handlers;
uint256[] amounts;
uint256 exchangeRate;
uint256 originationFee;
uint256 fee;
uint256 netDepositAmount;
uint256 mintAmount;
uint256 wad;
}
/**
* @dev Deposit token to earn savings, but only when the contract is not paused.
* @param _dst Account who will get dToken.
* @param _pie Amount to deposit, scaled by 1e18.
*/
function mint(address _dst, uint256 _pie)
external
nonReentrant
whenNotPaused
{
MintLocalVars memory _mintLocal;
_mintLocal.token = token;
// Charge the fee first
_mintLocal.originationFee = originationFee[msg.sig];
_mintLocal.fee = rmul(_pie, _mintLocal.originationFee);
if (_mintLocal.fee > 0)
require(
doTransferFrom(
_mintLocal.token,
msg.sender,
feeRecipient,
_mintLocal.fee
),
"mint: transferFrom fee failed"
);
_mintLocal.netDepositAmount = _pie.sub(_mintLocal.fee);
// Get deposit strategy base on the deposit amount.
(_mintLocal.handlers, _mintLocal.amounts) = IDispatcher(dispatcher)
.getDepositStrategy(_mintLocal.netDepositAmount);
require(
_mintLocal.handlers.length > 0,
"mint: no deposit strategy available, possibly due to a paused handler"
);
// Get current exchange rate.
_mintLocal.exchangeRate = getCurrentExchangeRateByHandler(
_mintLocal.handlers,
_mintLocal.token
);
for (uint256 i = 0; i < _mintLocal.handlers.length; i++) {
// If deposit amount is 0 for this handler, then pass.
if (_mintLocal.amounts[i] == 0) continue;
// Transfer the calculated token amount from `msg.sender` to the `handler`.
require(
doTransferFrom(
_mintLocal.token,
msg.sender,
_mintLocal.handlers[i],
_mintLocal.amounts[i]
),
"mint: transfer token to handler failed."
);
// The `handler` deposit obtained token to corresponding market to earn savings.
// Add the returned amount to the acutal mint amount, there could be fee when deposit
_mintLocal.mintAmount = _mintLocal.mintAmount.add(
IHandler(_mintLocal.handlers[i]).deposit(
_mintLocal.token,
_mintLocal.amounts[i]
)
);
}
require(
_mintLocal.mintAmount <= _mintLocal.netDepositAmount,
"mint: deposited more than intended"
);
// Calculate amount of the dToken based on current exchange rate.
_mintLocal.wad = rdiv(_mintLocal.mintAmount, _mintLocal.exchangeRate);
require(
_mintLocal.wad > 0,
"mint: can not mint the smallest unit with the given amount"
);
updateInterest(_dst, _mintLocal.exchangeRate);
Balance storage _balance = balances[_dst];
_balance.value = _balance.value.add(_mintLocal.wad);
totalSupply = totalSupply.add(_mintLocal.wad);
emit Transfer(address(0), _dst, _mintLocal.wad);
emit Mint(
_dst,
_pie,
_mintLocal.wad,
totalSupply,
_mintLocal.exchangeRate
);
}
struct RedeemLocalVars {
address token;
address defaultHandler;
address[] handlers;
uint256[] amounts;
uint256 exchangeRate;
uint256 originationFee;
uint256 fee;
uint256 grossAmount;
uint256 redeemTotalAmount;
uint256 userAmount;
}
/**
* @dev Redeem token according to input dToken amount,
* but only when the contract is not paused.
* @param _src Account who will spend dToken.
* @param _wad Amount to burn dToken, scaled by 1e18.
*/
function redeem(address _src, uint256 _wad)
external
nonReentrant
whenNotPaused
{
// Check the balance and allowance
Balance storage _balance = balances[_src];
require(_balance.value >= _wad, "redeem: insufficient balance");
if (_src != msg.sender && allowance[_src][msg.sender] != uint256(-1)) {
require(
allowance[_src][msg.sender] >= _wad,
"redeem: insufficient allowance"
);
allowance[_src][msg.sender] = allowance[_src][msg.sender].sub(_wad);
}
RedeemLocalVars memory _redeemLocal;
_redeemLocal.token = token;
// Get current exchange rate.
_redeemLocal.exchangeRate = getCurrentExchangeRate();
_redeemLocal.grossAmount = rmul(_wad, _redeemLocal.exchangeRate);
_redeemLocal.defaultHandler = IDispatcher(dispatcher).defaultHandler();
require(
_redeemLocal.defaultHandler != address(0) &&
IDispatcher(dispatcher).isHandlerActive(
_redeemLocal.defaultHandler
),
"redeem: default handler is inactive"
);
// Get `_token` best withdraw strategy base on the withdraw amount `_pie`.
(_redeemLocal.handlers, _redeemLocal.amounts) = IDispatcher(dispatcher)
.getWithdrawStrategy(_redeemLocal.token, _redeemLocal.grossAmount);
require(
_redeemLocal.handlers.length > 0,
"redeem: no withdraw strategy available, possibly due to a paused handler"
);
_redeemLocal.redeemTotalAmount = withdrawFromHandlers(
_redeemLocal.defaultHandler,
_redeemLocal.handlers,
_redeemLocal.amounts
);
// Market may charge some fee in withdraw, so the actual withdrown total amount
// could be less than what was intended
// Use the redeemTotalAmount as the baseline for further calculation
require(
_redeemLocal.redeemTotalAmount <= _redeemLocal.grossAmount,
"redeem: redeemed more than intended"
);
updateInterest(_src, _redeemLocal.exchangeRate);
// Update the balance and totalSupply
_balance.value = _balance.value.sub(_wad);
totalSupply = totalSupply.sub(_wad);
// Calculate fee
_redeemLocal.originationFee = originationFee[msg.sig];
_redeemLocal.fee = rmul(
_redeemLocal.redeemTotalAmount,
_redeemLocal.originationFee
);
// Transfer fee from the default handler(the temporary pool) to dToken.
if (_redeemLocal.fee > 0)
require(
doTransferFrom(
_redeemLocal.token,
_redeemLocal.defaultHandler,
feeRecipient,
_redeemLocal.fee
),
"redeem: transfer fee from default handler failed"
);
// Subtracting the fee
_redeemLocal.userAmount = _redeemLocal.redeemTotalAmount.sub(
_redeemLocal.fee
);
// Transfer the remaining amount from the default handler to msg.sender.
if (_redeemLocal.userAmount > 0)
require(
doTransferFrom(
_redeemLocal.token,
_redeemLocal.defaultHandler,
msg.sender,
_redeemLocal.userAmount
),
"redeem: transfer from default handler to user failed"
);
emit Transfer(_src, address(0), _wad);
emit Redeem(
_src,
_redeemLocal.redeemTotalAmount,
_wad,
totalSupply,
_redeemLocal.exchangeRate
);
}
struct RedeemUnderlyingLocalVars {
address token;
address defaultHandler;
address[] handlers;
uint256[] amounts;
uint256 exchangeRate;
uint256 originationFee;
uint256 fee;
uint256 consumeAmountWithFee;
uint256 redeemTotalAmount;
uint256 wad;
}
/**
* @dev Redeem specific amount of underlying token, but only when the contract is not paused.
* @param _src Account who will spend dToken.
* @param _pie Amount to redeem, scaled by 1e18.
*/
function redeemUnderlying(address _src, uint256 _pie)
external
nonReentrant
whenNotPaused
{
RedeemUnderlyingLocalVars memory _redeemLocal;
_redeemLocal.token = token;
// Here use the signature of redeem(), both functions should use the same fee rate
_redeemLocal.originationFee = originationFee[DToken(this)
.redeem
.selector];
_redeemLocal.consumeAmountWithFee = rdivup(
_pie,
BASE.sub(_redeemLocal.originationFee)
);
_redeemLocal.defaultHandler = IDispatcher(dispatcher).defaultHandler();
require(
_redeemLocal.defaultHandler != address(0) &&
IDispatcher(dispatcher).isHandlerActive(
_redeemLocal.defaultHandler
),
"redeemUnderlying: default handler is inactive"
);
// Get `_token` best withdraw strategy base on the redeem amount including fee.
(_redeemLocal.handlers, _redeemLocal.amounts) = IDispatcher(dispatcher)
.getWithdrawStrategy(
_redeemLocal.token,
_redeemLocal.consumeAmountWithFee
);
require(
_redeemLocal.handlers.length > 0,
"redeemUnderlying: no withdraw strategy available, possibly due to a paused handler"
);
// !!!DO NOT move up, we need the handlers to current exchange rate.
_redeemLocal.exchangeRate = getCurrentExchangeRateByHandler(
_redeemLocal.handlers,
_redeemLocal.token
);
_redeemLocal.redeemTotalAmount = withdrawFromHandlers(
_redeemLocal.defaultHandler,
_redeemLocal.handlers,
_redeemLocal.amounts
);
// Make sure enough token has been withdrown
// If the market charge fee in withdraw, there are 2 cases:
// 1) redeemed < intended, unlike redeem(), it should fail as user has demanded the specific amount;
// 2) redeemed == intended, it is okay, as fee was covered by consuming more underlying token
require(
_redeemLocal.redeemTotalAmount == _redeemLocal.consumeAmountWithFee,
"redeemUnderlying: withdrown more than intended"
);
// Calculate amount of the dToken based on current exchange rate.
_redeemLocal.wad = rdivup(
_redeemLocal.redeemTotalAmount,
_redeemLocal.exchangeRate
);
updateInterest(_src, _redeemLocal.exchangeRate);
// Check the balance and allowance
Balance storage _balance = balances[_src];
require(
_balance.value >= _redeemLocal.wad,
"redeemUnderlying: insufficient balance"
);
if (_src != msg.sender && allowance[_src][msg.sender] != uint256(-1)) {
require(
allowance[_src][msg.sender] >= _redeemLocal.wad,
"redeemUnderlying: insufficient allowance"
);
allowance[_src][msg.sender] = allowance[_src][msg.sender].sub(
_redeemLocal.wad
);
}
// Update the balance and totalSupply
_balance.value = _balance.value.sub(_redeemLocal.wad);
totalSupply = totalSupply.sub(_redeemLocal.wad);
// The calculated amount contains exchange token fee, if it exists.
_redeemLocal.fee = _redeemLocal.redeemTotalAmount.sub(_pie);
// Transfer fee from the default handler(the temporary pool) to dToken.
if (_redeemLocal.fee > 0)
require(
doTransferFrom(
_redeemLocal.token,
_redeemLocal.defaultHandler,
feeRecipient,
_redeemLocal.fee
),
"redeemUnderlying: transfer fee from default handler failed"
);
// Transfer original amount _pie from the default handler to msg.sender.
require(
doTransferFrom(
_redeemLocal.token,
_redeemLocal.defaultHandler,
msg.sender,
_pie
),
"redeemUnderlying: transfer to user failed"
);
emit Transfer(_src, address(0), _redeemLocal.wad);
emit Redeem(
_src,
_redeemLocal.redeemTotalAmount,
_redeemLocal.wad,
totalSupply,
_redeemLocal.exchangeRate
);
}
// --- ERC20 Standard Interfaces ---
function transfer(address _dst, uint256 _wad) external returns (bool) {
return transferFrom(msg.sender, _dst, _wad);
}
function transferFrom(
address _src,
address _dst,
uint256 _wad
) public nonReentrant whenNotPaused returns (bool) {
Balance storage _srcBalance = balances[_src];
// Check balance and allowance
require(
_srcBalance.value >= _wad,
"transferFrom: insufficient balance"
);
if (_src != msg.sender && allowance[_src][msg.sender] != uint256(-1)) {
require(
allowance[_src][msg.sender] >= _wad,
"transferFrom: insufficient allowance"
);
allowance[_src][msg.sender] = allowance[_src][msg.sender].sub(_wad);
}
// Update the accured interest for both
uint256 _exchangeRate = getCurrentExchangeRate();
updateInterest(_src, _exchangeRate);
updateInterest(_dst, _exchangeRate);
// Finally update the balance
Balance storage _dstBalance = balances[_dst];
_srcBalance.value = _srcBalance.value.sub(_wad);
_dstBalance.value = _dstBalance.value.add(_wad);
emit Transfer(_src, _dst, _wad);
return true;
}
function approve(address _spender, uint256 _wad)
public
whenNotPaused
returns (bool)
{
allowance[msg.sender][_spender] = _wad;
emit Approval(msg.sender, _spender, _wad);
return true;
}
function increaseAllowance(address spender, uint256 addedValue)
external
returns (bool)
{
return approve(spender, allowance[msg.sender][spender].add(addedValue));
}
function decreaseAllowance(address spender, uint256 subtractedValue)
external
returns (bool)
{
return
approve(
spender,
allowance[msg.sender][spender].sub(subtractedValue)
);
}
function balanceOf(address account) external view returns (uint256) {
return balances[account].value;
}
/**
* @dev According to the current exchange rate, get user's corresponding token balance
* based on the dToken amount, which has substracted dToken fee.
* @param _account Account to query token balance.
* @return Actual token balance based on dToken amount.
*/
function getTokenBalance(address _account) external view returns (uint256) {
return rmul(balances[_account].value, getExchangeRate());
}
/**
* @dev According to the current exchange rate, get user's accrued interest until now,
it is an estimation, since it use the exchange rate in view instead of
the realtime one.
* @param _account Account to query token balance.
* @return Estimation of accrued interest till now.
*/
function getCurrentInterest(address _account)
external
view
returns (uint256)
{
return
balances[_account].interest.add(
rmul(
getExchangeRate().sub(balances[_account].exchangeRate),
balances[_account].value
)
);
}
/**
* @dev Get the current list of the handlers.
*/
function getHandlers() public view returns (address[] memory) {
(address[] memory _handlers, ) = IDispatcher(dispatcher).getHandlers();
return _handlers;
}
/**
* @dev Get all deposit token amount including interest.
*/
function getTotalBalance() external view returns (uint256) {
address[] memory _handlers = getHandlers();
uint256 _tokenTotalBalance = 0;
for (uint256 i = 0; i < _handlers.length; i++)
_tokenTotalBalance = _tokenTotalBalance.add(
IHandler(_handlers[i]).getBalance(token)
);
return _tokenTotalBalance;
}
/**
* @dev Get maximum valid token amount in the whole market.
*/
function getLiquidity() external view returns (uint256) {
address[] memory _handlers = getHandlers();
uint256 _liquidity = 0;
for (uint256 i = 0; i < _handlers.length; i++)
_liquidity = _liquidity.add(
IHandler(_handlers[i]).getLiquidity(token)
);
return _liquidity;
}
/**
* @dev Current exchange rate, scaled by 1e18.
*/
function getExchangeRate() public view returns (uint256) {
address[] memory _handlers = getHandlers();
address _token = token;
uint256 _totalToken = 0;
for (uint256 i = 0; i < _handlers.length; i++)
_totalToken = _totalToken.add(
IHandler(_handlers[i]).getBalance(_token)
);
return totalSupply == 0 ? BASE : rdiv(_totalToken, totalSupply);
}
function currentExchangeRate() external returns (uint256) {
return getCurrentExchangeRate();
}
function totalUnderlying() external returns (uint256) {
address[] memory _handlers = getHandlers();
uint256 _tokenTotalBalance = 0;
for (uint256 i = 0; i < _handlers.length; i++)
_tokenTotalBalance = _tokenTotalBalance.add(
IHandler(_handlers[i]).getRealBalance(token)
);
return _tokenTotalBalance;
}
function getRealLiquidity() external returns (uint256) {
address[] memory _handlers = getHandlers();
uint256 _liquidity = 0;
for (uint256 i = 0; i < _handlers.length; i++)
_liquidity = _liquidity.add(
IHandler(_handlers[i]).getRealLiquidity(token)
);
return _liquidity;
}
function balanceOfUnderlying(address _account) external returns (uint256) {
uint256 _underlying = rmul(
balances[_account].value,
getCurrentExchangeRate()
);
return
_underlying.sub(
rmul(_underlying, originationFee[this.redeem.selector])
);
}
function getBaseData()
external
returns (
uint256,
uint256,
uint256,
uint256,
uint256
)
{
address[] memory _handlers = getHandlers();
uint256 _tokenTotalBalance = 0;
for (uint256 i = 0; i < _handlers.length; i++)
_tokenTotalBalance = _tokenTotalBalance.add(
IHandler(_handlers[i]).getRealBalance(token)
);
return (
decimals,
getCurrentExchangeRate(),
originationFee[DToken(this).mint.selector],
originationFee[DToken(this).redeem.selector],
_tokenTotalBalance
);
}
function getHandlerInfo()
external
returns (
address[] memory,
uint256[] memory,
uint256[] memory
)
{
address[] memory _handlers = getHandlers();
uint256[] memory _balances = new uint256[](_handlers.length);
uint256[] memory _liquidities = new uint256[](_handlers.length);
for (uint256 i = 0; i < _handlers.length; i++) {
_balances[i] = IHandler(_handlers[i]).getRealBalance(token);
_liquidities[i] = IHandler(_handlers[i]).getRealLiquidity(token);
}
return (_handlers, _balances, _liquidities);
}
}
|
Authorized function to set a new fee recipient. _newFeeRecipient The address allowed to collect fees./
|
function setFeeRecipient(address _newFeeRecipient) external auth {
address _oldFeeRecipient = feeRecipient;
require(
_newFeeRecipient != address(0) &&
_newFeeRecipient != _oldFeeRecipient,
"setFeeRecipient: feeRecipient can be not set to 0 or the current one."
);
feeRecipient = _newFeeRecipient;
emit FeeRecipientSet(_oldFeeRecipient, feeRecipient);
}
| 12,948,834
|
./full_match/11155111/0xDf01A4040493B514605392620B3a0a05Eb8Cd295/sources/contracts/ExquisiteGraphics.sol
|
Draw an SVG from the provided data. No validation data Binary data in the .xqst format. return string the <svg>
|
function drawUnsafe(bytes memory data) public pure returns (string memory) {
return _draw(data, DrawType.SVG, false);
}
| 3,797,317
|
./partial_match/80001/0xf150b30099655721c6463d7579B6FaC52857dA90/sources/contracts/factory/NftTokenCrowdsale.sol
|
----------------------------------------- Crowdsale external interface ----------------------------------------- _spender Address performing the token purchase _typeId of the token being sold _quantity of the token being sold/
|
function buyTokens(
address _spender,
uint256 _typeId,
uint256 _quantity
)
public
payable
nonReentrant
isValidTokenType(_typeId)
isValidAddress(_spender)
isValidQuantity(_quantity)
{
uint256 _wei = msg.value;
_preValidatePurchase(_spender, _wei, _typeId, _quantity);
_forwardFunds();
for (uint256 i = 0; i < _quantity; i++) {
_processPurchase(_spender, _typeId, tokenBox);
}
_postValidatePurchase(_spender, _typeId, _wei);
}
| 8,806,209
|
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "./interfaces/polygon/IRootChainManager.sol";
import "./interfaces/hop/IL1_Bridge.sol";
import "./helpers/errors.sol";
/// @author rimatik
/// @title HydraBridge middleware
contract HydraBridge is Ownable, Pausable {
using SafeERC20 for IERC20;
/// Address of polygon bridge root chain manager contract
address public _polygonRootChainManager;
/// Address of polygon bridge erc20Predicate contract
address public _erc20Predicate;
/// Address of hop bridge contract
address public _hopBridgeEth;
/// Address of hop bridge contract
address public _hopBridgeErc20;
event MoveCompleted(address, uint256);
constructor(address polygonRootChainManager, address erc20Predicate, address hopBridgeEth, address hopBridgeErc20) {
_polygonRootChainManager = polygonRootChainManager;
_erc20Predicate = erc20Predicate;
_hopBridgeEth = hopBridgeEth;
_hopBridgeErc20 = hopBridgeErc20;
}
/// Send funds to polygon bridge
/// @param recipient address for receiving tokens
/// @param rootToken address of token to bridge
/// @param amount of tokens to bridge
/// @dev transfer tokens to HydraBridge contract and bridge them to polygon
function sendToPolygon(address recipient, address rootToken, uint256 amount) external whenNotPaused{
_checkBeforeTransfer(amount, recipient);
_transferERC20(amount, rootToken, _erc20Predicate, recipient);
bytes memory depositData = bytes(abi.encode(amount));
IRootChainManager(_polygonRootChainManager).depositFor(recipient,rootToken,depositData);
emit MoveCompleted(recipient,amount);
}
/// Send eth to polygon bridge
/// @param recipient address for receiving tokens
function sendEthToPolygon(address recipient) payable external whenNotPaused {
_checkBeforeTransfer(msg.value, recipient);
IRootChainManager(_polygonRootChainManager).depositEtherFor{value: msg.value}(recipient);
emit MoveCompleted(recipient,msg.value);
}
/// Send funds to polygon bridge through hop protocol
/// @param rootToken address of token to bridge
/// @param recipient address for receiving tokens
/// @param chainId number of chain to transfer
/// @param amount of tokens to bridge
/// @param amountOutMin minimum tokens received
/// @param deadline for transfer
/// @param relayer address of relayer
/// @param relayerFee fee tha relayer gets
/// @dev transfer tokens to HydraBridge contract and bridge them to polygon through hop
function sendToL2Hop(address rootToken, address recipient, uint256 chainId,uint256 amount,uint256 amountOutMin,uint256 deadline,address relayer,uint256 relayerFee) external whenNotPaused {
_checkBeforeTransfer(amount, recipient);
_transferERC20(amount, rootToken, _hopBridgeErc20, recipient);
IL1_Bridge(_hopBridgeErc20).sendToL2(chainId,recipient,amount,amountOutMin,deadline,relayer,relayerFee);
emit MoveCompleted(recipient,amount);
}
/// Send eth to polygon bridge through hop protocol
/// @param recipient address for receiving tokens
/// @param chainId number of chain to transfer
/// @param amountOutMin minimum tokens received
/// @param deadline for transfer
/// @param relayer address of relayer
/// @param relayerFee fee tha relayer gets
function sendEthToL2Hop(address recipient, uint256 chainId,uint256 amountOutMin,uint256 deadline,address relayer,uint256 relayerFee) payable external whenNotPaused {
_checkBeforeTransfer(msg.value, recipient);
IL1_Bridge(_hopBridgeEth).sendToL2{value:msg.value}(chainId,recipient,msg.value,amountOutMin,deadline,relayer,relayerFee);
emit MoveCompleted(recipient,msg.value);
}
/// Check for amount and receiving address before transfer
/// @param amount to transfer
/// @param to address to transfer
function _checkBeforeTransfer(uint256 amount, address to) internal pure {
require(amount > 0, HydraBridgeErrors.INVALID_AMT);
require(to != address(0), HydraBridgeErrors.ADDRESS_0_PROVIDED);
}
/// Check for amount and receiving address before transfer
/// @param amount to transfer
/// @param rootToken address of token to transfer
/// @param allowanceTarget address for increasing allowance
/// @param from address from where transfer is made
function _transferERC20(uint256 amount, address rootToken, address allowanceTarget, address from) internal {
IERC20(rootToken).safeIncreaseAllowance(allowanceTarget,amount);
IERC20(rootToken).transferFrom(from,address(this),amount);
}
/// Set polygon root chain manager
/// @param polygonRootChainManager address of root chain manager
function setRootManager(address polygonRootChainManager) external onlyOwner{
_polygonRootChainManager = polygonRootChainManager;
}
/// Set hop bridge l1 eth address address
/// @param hopBridgeEth address
function setHopBridgeEth(address hopBridgeEth) external onlyOwner{
_hopBridgeEth = hopBridgeEth;
}
/// Set hop bridge l1 erc20 address address
/// @param hopBridgeErc20 address
function setHopBridgeErc20(address hopBridgeErc20) external onlyOwner{
_hopBridgeErc20 = hopBridgeErc20;
}
/// Set erc20 predicate
/// @param erc20Predicate address
function setErc20Predicate(address erc20Predicate) external onlyOwner{
_erc20Predicate = erc20Predicate;
}
/// Disable contract
function pause() external onlyOwner whenNotPaused {
_pause();
}
/// Enable contract
function unpause() external onlyOwner whenPaused {
_unpause();
}
/// Rescue funds in case they are stuck in contract
/// @param token to transfer
/// @param userAddress address of receiver
/// @param amount to transfer
function rescueFunds(
address token,
address userAddress,
uint256 amount
) external onlyOwner {
IERC20(token).safeTransfer(userAddress, amount);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: 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 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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: GPL-3.0
pragma solidity 0.8.4;
interface IRootChainManager {
function depositEtherFor(address user) external payable;
function depositFor(
address user,
address rootToken,
bytes calldata depositData
) external;
function exit(bytes calldata inputData) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.4;
interface IL1_Bridge {
function sendToL2(
uint256 chainId,
address recipient,
uint256 amount,
uint256 amountOutMin,
uint256 deadline,
address relayer,
uint256 relayerFee
)
external
payable;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.4;
library HydraBridgeErrors {
string internal constant ADDRESS_0_PROVIDED = "ADDRESS_0_PROVIDED";
string internal constant INVALID_AMT = "INVALID_AMT";
}
// SPDX-License-Identifier: MIT
// 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);
}
}
}
}
// 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;
}
}
|
Rescue funds in case they are stuck in contract token to transfer userAddress address of receiver amount to transfer
|
function rescueFunds(
address token,
address userAddress,
uint256 amount
) external onlyOwner {
IERC20(token).safeTransfer(userAddress, amount);
}
| 498,423
|
/************************************************************************
~~~ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\ ~~~~
~~~ @@@@@@ ░█████╗░██████╗░░█████╗░██╗░░██╗███████╗██████╗░ @@@@@@ | ~~~
~~~ @@@@@ ██╔══██╗██╔══██╗██╔══██╗██║░░██║██╔════╝██╔══██╗ @@@@@ | ~~~
~~~ @@@@@ ███████║██████╔╝██║░░╚═╝███████║█████╗░░██████╔╝ @@@@@@ | ~~~
~~~ @@@@@ ██╔══██║██╔══██╗██║░░██╗██╔══██║██╔══╝░░██╔══██╗ @@@@@ | ~~~
~~~ @@@@@ ██║░░██║██║░░██║╚█████╔╝██║░░██║███████╗██║░░██║ @@@@@ | ~~~
~~~ @@@@@ ╚═╝░░╚═╝╚═╝░░╚═╝░╚════╝░╚═╝░░╚═╝╚══════╝╚═╝░░╚═╝ @@@@@ | ~~~
~~~ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ | ~~~
~~~ \_____________________________________________________________\| ~~~
************************************************************************/
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./lib/SafeMath.sol";
/**
* @title ArchToken
* @dev The governance token for Archer DAO
* ERC-20 with supply controls + add-ons to allow for offchain signing
* See EIP-712, EIP-2612, and EIP-3009 for details
*/
contract ArchToken {
using SafeMath for uint256;
/// @notice EIP-20 token name for this token
string public name = "Archer DAO Governance Token";
/// @notice EIP-20 token symbol for this token
string public symbol = "ARCH";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint256 public totalSupply = 100_000_000e18; // 100 million
/// @notice Address which may mint/burn tokens
address public supplyManager;
/// @notice Address which may change token metadata
address public metadataManager;
/// @notice The timestamp after which a supply change may occur
uint256 public supplyChangeAllowedAfter;
/// @notice The initial minimum time between changing the token supply
uint32 public supplyChangeWaitingPeriod = 1 days * 365;
/// @notice Hard cap on the minimum time between changing the token supply
uint32 public constant supplyChangeWaitingPeriodMinimum = 1 days * 90;
/// @notice Cap on the total amount that can be minted at each mint (measured in bips: 10,000 bips = 1% of current totalSupply)
uint16 public mintCap = 20_000;
/// @dev Allowance amounts on behalf of others
mapping (address => mapping (address => uint256)) internal allowances;
/// @dev Official record of token balances for each account
mapping (address => uint256) internal balances;
/// @notice The EIP-712 typehash for the contract's domain
/// keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")
bytes32 public constant DOMAIN_TYPEHASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;
/// @notice The EIP-712 version hash
/// keccak256("1");
bytes32 public constant VERSION_HASH = 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6;
/// @notice The EIP-712 typehash for permit (EIP-2612)
/// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
/// @notice The EIP-712 typehash for transferWithAuthorization (EIP-3009)
/// keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)");
bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267;
/// @notice The EIP-712 typehash for receiveWithAuthorization (EIP-3009)
/// keccak256("ReceiveWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)")
bytes32 public constant RECEIVE_WITH_AUTHORIZATION_TYPEHASH = 0xd099cc98ef71107a616c4f0f941f04c322d8e254fe26b3c6668db87aae413de8;
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @dev authorizer address > nonce > state (true = used / false = unused)
mapping (address => mapping (bytes32 => bool)) public authorizationState;
/// @notice An event that's emitted when the mintCap is changed
event MintCapChanged(uint16 indexed oldMintCap, uint16 indexed newMintCap);
/// @notice An event that's emitted when the supplyManager address is changed
event SupplyManagerChanged(address indexed oldManager, address indexed newManager);
/// @notice An event that's emitted when the supplyChangeWaitingPeriod is changed
event SupplyChangeWaitingPeriodChanged(uint32 indexed oldWaitingPeriod, uint32 indexed newWaitingPeriod);
/// @notice An event that's emitted when the metadataManager address is changed
event MetadataManagerChanged(address indexed oldManager, address indexed newManager);
/// @notice An event that's emitted when the token name and symbol are changed
event TokenMetaUpdated(string indexed name, string indexed symbol);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 value);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 value);
/// @notice An event that's emitted whenever an authorized transfer occurs
event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce);
/**
* @notice Construct a new Arch token
* @param _metadataManager The account with the ability to change token metadata
* @param _supplyManager The address with minting ability
* @param _firstSupplyChangeAllowed The timestamp after which the first supply change may occur
*/
constructor(address _metadataManager, address _supplyManager, uint256 _firstSupplyChangeAllowed) {
require(_firstSupplyChangeAllowed >= block.timestamp, "Arch::constructor: minting can only begin after deployment");
balances[msg.sender] = totalSupply;
emit Transfer(address(0), msg.sender, totalSupply);
supplyChangeAllowedAfter = _firstSupplyChangeAllowed;
supplyManager = _supplyManager;
emit SupplyManagerChanged(address(0), _supplyManager);
metadataManager = _metadataManager;
emit MetadataManagerChanged(address(0), metadataManager);
}
/**
* @notice Change the supplyManager address
* @param newSupplyManager The address of the new supply manager
* @return true if successful
*/
function setSupplyManager(address newSupplyManager) external returns (bool) {
require(msg.sender == supplyManager, "Arch::setSupplyManager: only SM can change SM");
emit SupplyManagerChanged(supplyManager, newSupplyManager);
supplyManager = newSupplyManager;
return true;
}
/**
* @notice Change the metadataManager address
* @param newMetadataManager The address of the new metadata manager
* @return true if successful
*/
function setMetadataManager(address newMetadataManager) external returns (bool) {
require(msg.sender == metadataManager, "Arch::setMetadataManager: only MM can change MM");
emit MetadataManagerChanged(metadataManager, newMetadataManager);
metadataManager = newMetadataManager;
return true;
}
/**
* @notice Mint new tokens
* @param dst The address of the destination account
* @param amount The number of tokens to be minted
* @return Boolean indicating success of mint
*/
function mint(address dst, uint256 amount) external returns (bool) {
require(msg.sender == supplyManager, "Arch::mint: only the supplyManager can mint");
require(dst != address(0), "Arch::mint: cannot transfer to the zero address");
require(amount <= totalSupply.mul(mintCap).div(1000000), "Arch::mint: exceeded mint cap");
require(block.timestamp >= supplyChangeAllowedAfter, "Arch::mint: minting not allowed yet");
// update the next supply change allowed timestamp
supplyChangeAllowedAfter = block.timestamp.add(supplyChangeWaitingPeriod);
// mint the amount
_mint(dst, amount);
return true;
}
/**
* @notice Burn tokens
* @param src The account that will burn tokens
* @param amount The number of tokens to be burned
* @return Boolean indicating success of burn
*/
function burn(address src, uint256 amount) external returns (bool) {
address spender = msg.sender;
require(spender == supplyManager, "Arch::burn: only the supplyManager can burn");
require(src != address(0), "Arch::burn: cannot transfer from the zero address");
require(block.timestamp >= supplyChangeAllowedAfter, "Arch::burn: burning not allowed yet");
uint256 spenderAllowance = allowances[src][spender];
// check allowance and reduce by amount
if (spender != src && spenderAllowance != uint256(-1)) {
uint256 newAllowance = spenderAllowance.sub(
amount,
"Arch::burn: burn amount exceeds allowance"
);
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
// update the next supply change allowed timestamp
supplyChangeAllowedAfter = block.timestamp.add(supplyChangeWaitingPeriod);
// burn the amount
_burn(src, amount);
return true;
}
/**
* @notice Set the maximum amount of tokens that can be minted at once
* @param newCap The new mint cap in bips (10,000 bips = 1% of totalSupply)
* @return true if successful
*/
function setMintCap(uint16 newCap) external returns (bool) {
require(msg.sender == supplyManager, "Arch::setMintCap: only SM can change mint cap");
emit MintCapChanged(mintCap, newCap);
mintCap = newCap;
return true;
}
/**
* @notice Set the minimum time between supply changes
* @param period The new supply change waiting period
* @return true if succssful
*/
function setSupplyChangeWaitingPeriod(uint32 period) external returns (bool) {
require(msg.sender == supplyManager, "Arch::setSupplyChangeWaitingPeriod: only SM can change waiting period");
require(period >= supplyChangeWaitingPeriodMinimum, "Arch::setSupplyChangeWaitingPeriod: waiting period must be > minimum");
emit SupplyChangeWaitingPeriodChanged(supplyChangeWaitingPeriod, period);
supplyChangeWaitingPeriod = period;
return true;
}
/**
* @notice Update the token name and symbol
* @param tokenName The new name for the token
* @param tokenSymbol The new symbol for the token
* @return true if successful
*/
function updateTokenMetadata(string memory tokenName, string memory tokenSymbol) external returns (bool) {
require(msg.sender == metadataManager, "Arch::updateTokenMeta: only MM can update token metadata");
name = tokenName;
symbol = tokenSymbol;
emit TokenMetaUpdated(name, symbol);
return true;
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* It is recommended to use increaseAllowance and decreaseAllowance instead
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
/**
* @notice Increase the allowance by a given amount
* @param spender Spender's address
* @param addedValue Amount of increase in allowance
* @return True if successful
*/
function increaseAllowance(address spender, uint256 addedValue)
external
returns (bool)
{
_increaseAllowance(msg.sender, spender, addedValue);
return true;
}
/**
* @notice Decrease the allowance by a given amount
* @param spender Spender's address
* @param subtractedValue Amount of decrease in allowance
* @return True if successful
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
external
returns (bool)
{
_decreaseAllowance(msg.sender, spender, subtractedValue);
return true;
}
/**
* @notice Triggers an approval from owner to spender
* @param owner The address to approve from
* @param spender The address to be approved
* @param value The number of tokens that are approved (2^256-1 means infinite)
* @param deadline The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external {
require(deadline >= block.timestamp, "Arch::permit: signature expired");
bytes32 encodeData = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline));
_validateSignedData(owner, encodeData, v, r, s);
_approve(owner, spender, value);
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external returns (bool) {
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external returns (bool) {
address spender = msg.sender;
uint256 spenderAllowance = allowances[src][spender];
if (spender != src && spenderAllowance != uint256(-1)) {
uint256 newAllowance = spenderAllowance.sub(
amount,
"Arch::transferFrom: transfer amount exceeds allowance"
);
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Transfer tokens with a signed authorization
* @param from Payer's address (Authorizer)
* @param to Payee's address
* @param value Amount to be transferred
* @param validAfter The time after which this is valid (unix time)
* @param validBefore The time before which this is valid (unix time)
* @param nonce Unique nonce
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function transferWithAuthorization(
address from,
address to,
uint256 value,
uint256 validAfter,
uint256 validBefore,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
require(block.timestamp > validAfter, "Arch::transferWithAuth: auth not yet valid");
require(block.timestamp < validBefore, "Arch::transferWithAuth: auth expired");
require(!authorizationState[from][nonce], "Arch::transferWithAuth: auth already used");
bytes32 encodeData = keccak256(abi.encode(TRANSFER_WITH_AUTHORIZATION_TYPEHASH, from, to, value, validAfter, validBefore, nonce));
_validateSignedData(from, encodeData, v, r, s);
authorizationState[from][nonce] = true;
emit AuthorizationUsed(from, nonce);
_transferTokens(from, to, value);
}
/**
* @notice Receive a transfer with a signed authorization from the payer
* @dev This has an additional check to ensure that the payee's address matches
* the caller of this function to prevent front-running attacks.
* @param from Payer's address (Authorizer)
* @param to Payee's address
* @param value Amount to be transferred
* @param validAfter The time after which this is valid (unix time)
* @param validBefore The time before which this is valid (unix time)
* @param nonce Unique nonce
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
*/
function receiveWithAuthorization(
address from,
address to,
uint256 value,
uint256 validAfter,
uint256 validBefore,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
) external {
require(to == msg.sender, "Arch::receiveWithAuth: caller must be the payee");
require(block.timestamp > validAfter, "Arch::receiveWithAuth: auth not yet valid");
require(block.timestamp < validBefore, "Arch::receiveWithAuth: auth expired");
require(!authorizationState[from][nonce], "Arch::receiveWithAuth: auth already used");
bytes32 encodeData = keccak256(abi.encode(RECEIVE_WITH_AUTHORIZATION_TYPEHASH, from, to, value, validAfter, validBefore, nonce));
_validateSignedData(from, encodeData, v, r, s);
authorizationState[from][nonce] = true;
emit AuthorizationUsed(from, nonce);
_transferTokens(from, to, value);
}
/**
* @notice EIP-712 Domain separator
* @return Separator
*/
function getDomainSeparator() public view returns (bytes32) {
return keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name)),
VERSION_HASH,
_getChainId(),
address(this)
)
);
}
/**
* @notice Recovers address from signed data and validates the signature
* @param signer Address that signed the data
* @param encodeData Data signed by the address
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function _validateSignedData(address signer, bytes32 encodeData, uint8 v, bytes32 r, bytes32 s) internal view {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
getDomainSeparator(),
encodeData
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
// Explicitly disallow authorizations for address(0) as ecrecover returns address(0) on malformed messages
require(recoveredAddress != address(0) && recoveredAddress == signer, "Arch::validateSig: invalid signature");
}
/**
* @notice Approval implementation
* @param owner The address of the account which owns tokens
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (2^256-1 means infinite)
*/
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "Arch::_approve: approve from the zero address");
require(spender != address(0), "Arch::_approve: approve to the zero address");
allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _increaseAllowance(
address owner,
address spender,
uint256 addedValue
) internal {
_approve(owner, spender, allowances[owner][spender].add(addedValue));
}
function _decreaseAllowance(
address owner,
address spender,
uint256 subtractedValue
) internal {
_approve(
owner,
spender,
allowances[owner][spender].sub(
subtractedValue,
"Arch::_decreaseAllowance: decreased allowance below zero"
)
);
}
/**
* @notice Transfer implementation
* @param from The address of the account which owns tokens
* @param to The address of the account which is receiving tokens
* @param value The number of tokens that are being transferred
*/
function _transferTokens(address from, address to, uint256 value) internal {
require(to != address(0), "Arch::_transferTokens: cannot transfer to the zero address");
balances[from] = balances[from].sub(
value,
"Arch::_transferTokens: transfer exceeds from balance"
);
balances[to] = balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @notice Mint implementation
* @param to The address of the account which is receiving tokens
* @param value The number of tokens that are being minted
*/
function _mint(address to, uint256 value) internal {
totalSupply = totalSupply.add(value);
balances[to] = balances[to].add(value);
emit Transfer(address(0), to, value);
}
/**
* @notice Burn implementation
* @param from The address of the account which owns tokens
* @param value The number of tokens that are being burned
*/
function _burn(address from, uint256 value) internal {
balances[from] = balances[from].sub(
value,
"Arch::_burn: burn amount exceeds from balance"
);
totalSupply = totalSupply.sub(
value,
"Arch::_burn: burn amount exceeds total supply"
);
emit Transfer(from, address(0), value);
}
/**
* @notice Current id of the chain where this contract is deployed
* @return Chain id
*/
function _getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
|
Update the token name and symbol tokenName The new name for the token tokenSymbol The new symbol for the token return true if successful/
|
function updateTokenMetadata(string memory tokenName, string memory tokenSymbol) external returns (bool) {
require(msg.sender == metadataManager, "Arch::updateTokenMeta: only MM can update token metadata");
name = tokenName;
symbol = tokenSymbol;
emit TokenMetaUpdated(name, symbol);
return true;
}
| 12,711,517
|
contract IOU {
address owner;
/* Public variables of the token */
string public name;
string public symbol;
uint8 public decimals;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
function IOU(string tokenName, string tokenSymbol, uint8 decimalUnits) {
owner = msg.sender; // sets main RipplePay contract as owner
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
}
/* update balances so they display in ethereum-wallet */
function transfer(address _from, address _to, uint256 _value) {
if(msg.sender != owner) throw; // can only be invoked by main RipplePay contract
balanceOf[_from] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
}
}
contract RipplePayMain {
mapping(string => address) currencies;
function newCurrency(string currencyName, string currencySymbol, uint8 decimalUnits){
currencies[currencySymbol] = new IOU(currencyName, currencySymbol, decimalUnits);
}
function issueIOU(string _currency, uint256 _amount, address _to){
// update creditLines in main contract, then update balances in IOU contract to display in ethereum-wallet
IOU(currencies[_currency]).transfer(msg.sender, _to, _amount);
}
}
|
update balances so they display in ethereum-wallet /
|
function transfer(address _from, address _to, uint256 _value) {
}
| 6,387,796
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {AccessControlEnumerableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {TokensHelper} from "./lib/TokensHelper.sol";
import {UpgradeableBeacon} from "@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol";
import {BeaconProxy} from "@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol";
contract ParadiseBridge is Initializable, AccessControlEnumerableUpgradeable, ReentrancyGuardUpgradeable {
/**
* @dev Token bridging configuration
*/
struct BridgeableTokensConfig {
// Whether to allow this token into the bridge.
bool enabled;
// When the token enters the bridge, choose to `burn` (true) or `transfer to the bridge` (false).
bool burn;
// After deducting fee, the bridge amount needs to be greater than the minimum value.
uint256 minBridgeAmount;
// Maximum amount to bridge.
uint256 maxBridgeAmount;
// Bridge fee, set by administrator.
uint256 bridgeFee;
}
/**
* @dev Rules for Approving Token Bridging
*/
struct BridgeApprovalConfig {
// whether to allow this token to be approved for bridging.
bool enabled;
// When bridging, the target token will be `transferred` (true) or `mint by the contract` (false).
bool transfer;
}
/**
* @dev The token contract is on the specified chain
*/
struct TokensOnChain {
// Token contract address
address token;
// Specified chain ID
uint256 chainId;
}
/**
* @dev Submit a bridge request on source chain
* @param token The token address on the source chain.
* @param sender The bridge request sender.
* @param recipient The token recipients on the target chain.
* @param amount The amount (after deduction of fee) of tokens the receiver should receive.
* @param fees The fee charged by the bridge.
* @param sourceChain Bridging from chain ID.
* @param targetChain Bridging to chain ID.
*/
event BridgeToSubmitted(
address indexed token,
address indexed sender,
address indexed recipient,
uint256 amount,
uint256 fees,
uint256 sourceChain,
uint256 targetChain
);
/**
* @dev Emit on target chain after bridging is complete
* @param txhash The transaction hash of the bridge request submitted on the source chain.
* @param targetToken The token address on the target chain.
* @param recipient The token recipients on the target chain.
* @param amount The amount of tokens the receiver should receive.
* @param sourceChain Bridging from chain ID.
* @param targetChain Bridging to chain ID.
*/
event BridgeToApproved(
bytes32 indexed txhash,
address indexed targetToken,
address indexed recipient,
uint256 amount,
uint256 sourceChain,
uint256 targetChain
);
/**
* @dev Emit when the native token is deposited on the bridge
* @param amount Deposit amount.
*/
event TokensDeposit(address indexed from, uint256 amount);
/**
* @dev Emit when fee recipient changes
*/
event FeeRecipientChanged(address indexed newRecipient);
/**
* @dev Emit when bridge running status changes
*/
event BridgeRunningStatusChanged(bool indexed newRunningStatus);
/**
* @dev Emit when token bridge fee updated
*/
event BridgeFeeUpdated(address indexed token, uint256 newFee);
/**
* @dev Emit when admin migrates bridge assets
*/
event BridgeAssetsMigrated(address indexed operator, address indexed token, uint256 amount);
/**
* @dev Emit when bridgeable token updated
*/
event BridgeableTokenUpdated(
address indexed token,
uint256 indexed targetChain,
bool enable,
bool burn,
uint256 minBridgeAmount,
uint256 maxBridgeAmount,
uint256 bridgeFee
);
/**
* @dev Emit when bridge approval config updated
*/
event BridgeApprovalConfigUpdated(address indexed token, bool enabled, bool transfer);
bytes32 public constant BRIDGE_APPROVER_ROLE = keccak256("BRIDGE_APPROVER_ROLE");
mapping(bytes32 => BridgeableTokensConfig) private _bridgeableTokens;
mapping(address => BridgeApprovalConfig) public bridgeApprovalConfig;
/**
* @dev The address of the fee recipient
*/
address public feeRecipient;
/**
* @notice Is bridge currently available
*/
bool public bridgeIsRunning;
/**
* @notice Whether bridge currently charges fee (global setting)
*/
bool public globalFeeStatus;
modifier checkTokenAddress(address token) {
require(Address.isContract(token), "invalid token address");
_;
}
modifier needBridgeIsRunning() {
require(bridgeIsRunning, "bridge is not running");
_;
}
modifier checkBridgeApprovalStatus(address token) {
require(bridgeApprovalConfig[token].enabled, "token is not approved");
_;
}
modifier checkArrayLength(uint256 lenA, uint256 lenB) {
require(lenA == lenB, "arrays should equal in length");
_;
}
function initialize(
bool _bridgeRunningStatus,
bool _globalFeeStatus,
address _feeRecipient
) external nonReentrant initializer {
__Context_init_unchained();
__ReentrancyGuard_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__AccessControlEnumerable_init_unchained();
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setRoleAdmin(BRIDGE_APPROVER_ROLE, DEFAULT_ADMIN_ROLE);
_setBridgeRunningStatus(_bridgeRunningStatus);
globalFeeStatus = _globalFeeStatus;
_setFeeRecipient(_feeRecipient);
}
/**
* @dev Encode token address with chainId
*/
function _encodeTokenWithChainId(address _token, uint256 _chainId) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_token, _chainId));
}
/**
* @notice Get the current chain ID
*/
function chainId() public view returns (uint256 id) {
// solhint-disable-next-line no-inline-assembly
assembly {
id := chainid()
}
}
/**
* @notice Get the tokens bridge config
* @param token The token address (zero is native token)
* @param targetChainId The id of target chain
*/
function bridgeableTokens(address token, uint256 targetChainId)
public
view
returns (BridgeableTokensConfig memory config)
{
BridgeableTokensConfig memory _tokenConfig = _bridgeableTokens[_encodeTokenWithChainId(token, targetChainId)];
if (!globalFeeStatus) {
_tokenConfig.bridgeFee = 0;
}
return _tokenConfig;
}
function _setBridgeRunningStatus(bool newRunningStatus) internal {
bridgeIsRunning = newRunningStatus;
emit BridgeRunningStatusChanged(newRunningStatus);
}
/**
* @dev Check token address
* zero address is native token
*/
function _checkTokenAddress(address token) internal view {
require(token == address(0) || Address.isContract(token), "invalid token address");
}
function _setFeeRecipient(address newRecipient) internal {
require(newRecipient != address(0) && newRecipient != address(this), "invalid fees recipient");
feeRecipient = newRecipient;
emit FeeRecipientChanged(newRecipient);
}
function _setBridgeFee(
address _token,
uint256 _chainId,
uint256 newFee
) internal {
BridgeableTokensConfig storage _tokenConfig = _bridgeableTokens[_encodeTokenWithChainId(_token, _chainId)];
if (_tokenConfig.bridgeFee == newFee) return;
require(
(newFee < _tokenConfig.maxBridgeAmount) &&
((_tokenConfig.maxBridgeAmount - newFee) >= _tokenConfig.minBridgeAmount),
"invalid fee config"
);
_tokenConfig.bridgeFee = newFee;
emit BridgeFeeUpdated(_token, newFee);
}
/**
* @notice Bridging the ERC20 token to the target chain
* @param token The ERC20 token address on the current chain.
* @param recipient The recipient address on the target chain.
* @param amount The bridge ERC20 tokens amount.
* @param targetChainId The target chain ID (can be found here: https://chainlist.org/).
*/
function bridgeTokensTo(
address token,
address recipient,
uint256 amount,
uint256 targetChainId
) external nonReentrant needBridgeIsRunning checkTokenAddress(token) {
require(recipient != address(0), "invalid recipient");
BridgeableTokensConfig storage _tokenConfig = _bridgeableTokens[_encodeTokenWithChainId(token, targetChainId)];
require(_tokenConfig.enabled, "token is not bridgeable");
require(amount > _tokenConfig.bridgeFee, "bridge amount should be greater than fees");
if (globalFeeStatus && _tokenConfig.bridgeFee > 0) {
TokensHelper.safeTransferFrom(token, msg.sender, feeRecipient, _tokenConfig.bridgeFee);
amount -= _tokenConfig.bridgeFee;
}
require(
(amount >= _tokenConfig.minBridgeAmount) && (amount <= _tokenConfig.maxBridgeAmount),
"invalid bridge amount range"
);
if (_tokenConfig.burn) {
TokensHelper.safeBurnFrom(token, msg.sender, amount);
} else {
TokensHelper.safeTransferFrom(token, msg.sender, address(this), amount);
}
emit BridgeToSubmitted(token, msg.sender, recipient, amount, _tokenConfig.bridgeFee, chainId(), targetChainId);
}
/**
* @notice Bridging the native token to the target chain
* @param recipient The recipient address on the target chain.
* @param targetChainId The target chain ID (can be found here: https://chainlist.org/).
*/
function bridgeNativeTokensTo(address recipient, uint256 targetChainId)
external
payable
nonReentrant
needBridgeIsRunning
{
require(recipient != address(0), "invalid recipient");
uint256 amount = msg.value;
BridgeableTokensConfig storage _tokenConfig = _bridgeableTokens[
_encodeTokenWithChainId(address(0), targetChainId)
];
require(_tokenConfig.enabled, "token is not bridgeable");
require(amount > _tokenConfig.bridgeFee, "bridge amount should be greater than fees");
if (globalFeeStatus && _tokenConfig.bridgeFee > 0) {
TokensHelper.safeTransferNativeTokens(feeRecipient, _tokenConfig.bridgeFee);
amount -= _tokenConfig.bridgeFee;
}
require(
(amount >= _tokenConfig.minBridgeAmount) && (amount <= _tokenConfig.maxBridgeAmount),
"invalid bridge amount range"
);
emit BridgeToSubmitted(
address(0),
msg.sender,
recipient,
amount,
_tokenConfig.bridgeFee,
chainId(),
targetChainId
);
}
/**
* @dev Approvers process bridge requests (to ERC20)
* @param txHash The transaction hash of the bridge request from source chain.
* @param sourceChainId The chain id that made the bridge request.
* @param targetToken The address of the target token.
* @param recipient The recipient of tokens.
* @param amount The amount of tokens.
*/
function approveBridgeTo(
bytes32 txHash,
uint256 sourceChainId,
address targetToken,
address recipient,
uint256 amount
)
external
nonReentrant
onlyRole(BRIDGE_APPROVER_ROLE)
needBridgeIsRunning
checkTokenAddress(targetToken)
checkBridgeApprovalStatus(targetToken)
{
if (bridgeApprovalConfig[targetToken].transfer) {
TokensHelper.safeTransfer(targetToken, recipient, amount);
} else {
TokensHelper.safeMint(targetToken, recipient, amount);
}
emit BridgeToApproved(txHash, targetToken, recipient, amount, sourceChainId, chainId());
}
/**
* @dev Approvers process bridge requests (to native tokens)
* @param txHash The transaction hash of the bridge request from source chain.
* @param sourceChainId The chain id that made the bridge request.
* @param recipient The recipient of tokens.
* @param amount The amount of tokens.
*/
function approveBridgeToNative(
bytes32 txHash,
uint256 sourceChainId,
address recipient,
uint256 amount
) external nonReentrant onlyRole(BRIDGE_APPROVER_ROLE) needBridgeIsRunning checkBridgeApprovalStatus(address(0)) {
TokensHelper.safeTransferNativeTokens(recipient, amount);
emit BridgeToApproved(txHash, address(0), recipient, amount, sourceChainId, chainId());
}
/**
* @dev Configure bridgeable tokens
*/
function addBridgeableTokens(TokensOnChain[] memory tokensOnChain, BridgeableTokensConfig[] memory configs)
external
onlyRole(DEFAULT_ADMIN_ROLE)
checkArrayLength(tokensOnChain.length, configs.length)
{
for (uint256 i; i < tokensOnChain.length; i++) {
_checkTokenAddress(tokensOnChain[i].token);
if (configs[i].maxBridgeAmount == 0) {
configs[i].maxBridgeAmount = type(uint256).max;
}
require(configs[i].maxBridgeAmount > configs[i].minBridgeAmount, "invalid bridge amount limit");
_bridgeableTokens[_encodeTokenWithChainId(tokensOnChain[i].token, tokensOnChain[i].chainId)] = configs[i];
emit BridgeableTokenUpdated(
tokensOnChain[i].token,
tokensOnChain[i].chainId,
configs[i].enabled,
configs[i].burn,
configs[i].minBridgeAmount,
configs[i].maxBridgeAmount,
configs[i].bridgeFee
);
}
}
/**
* @dev Configure bridgeable tokens fees
*/
function setBridgeFees(TokensOnChain[] memory tokensOnChain, uint256[] memory fees)
external
onlyRole(DEFAULT_ADMIN_ROLE)
checkArrayLength(tokensOnChain.length, fees.length)
{
for (uint256 i; i < tokensOnChain.length; i++) {
_checkTokenAddress(tokensOnChain[i].token);
_setBridgeFee(tokensOnChain[i].token, tokensOnChain[i].chainId, fees[i]);
}
}
/**
* @dev Configure approval of bridgeable tokens
*/
function addBridgeApprovalConfig(address[] memory tokenAddresses, BridgeApprovalConfig[] memory configs)
external
onlyRole(DEFAULT_ADMIN_ROLE)
checkArrayLength(tokenAddresses.length, configs.length)
{
for (uint256 i; i < tokenAddresses.length; i++) {
_checkTokenAddress(tokenAddresses[i]);
bridgeApprovalConfig[tokenAddresses[i]] = configs[i];
emit BridgeApprovalConfigUpdated(tokenAddresses[i], configs[i].enabled, configs[i].transfer);
}
}
/**
* @dev Set bridge global status
* @param bridgeRunningStatus The new bridge running status.
*/
function setBridgeRunningStatus(bool bridgeRunningStatus) external onlyRole(DEFAULT_ADMIN_ROLE) {
_setBridgeRunningStatus(bridgeRunningStatus);
}
/**
* @dev Deposit native tokens to bridge
*/
function depositNativeTokens() external payable {
emit TokensDeposit(msg.sender, msg.value);
}
/**
* @dev Set a new fee recipient
* @param newRecipient The new recipient address.
*/
function setFeeRecipient(address newRecipient) external onlyRole(DEFAULT_ADMIN_ROLE) {
_setFeeRecipient(newRecipient);
}
/**
* @dev Set a new global fee status
* @param newFeeStatus The new fee status.
*/
function setGlobalFeeStatus(bool newFeeStatus) external onlyRole(DEFAULT_ADMIN_ROLE) {
globalFeeStatus = newFeeStatus;
}
/**
* @dev Allow administrators to migrate bridge assets (Native tokens)
*/
function migrateAssets(uint256 amount) external nonReentrant onlyRole(DEFAULT_ADMIN_ROLE) {
TokensHelper.safeTransferNativeTokens(msg.sender, amount);
emit BridgeAssetsMigrated(msg.sender, address(0), amount);
}
/**
* @dev Allow administrators to migrate bridge assets (ERC20)
*/
function migrateAssets(address token, uint256 amount) external nonReentrant onlyRole(DEFAULT_ADMIN_ROLE) {
TokensHelper.safeTransfer(token, msg.sender, amount);
emit BridgeAssetsMigrated(msg.sender, token, amount);
}
/**
* @dev Allow administrators to batch migrate bridge assets (ERC20)
*/
function migrateAssets(address[] memory tokens, uint256 amount) external nonReentrant onlyRole(DEFAULT_ADMIN_ROLE) {
for (uint256 i; i < tokens.length; i++) {
TokensHelper.safeTransfer(tokens[i], msg.sender, amount);
emit BridgeAssetsMigrated(msg.sender, tokens[i], amount);
}
}
}
|
Bridging the ERC20 token to the target chain token The ERC20 token address on the current chain. recipient The recipient address on the target chain. amount The bridge ERC20 tokens amount./
|
function bridgeTokensTo(
address token,
address recipient,
uint256 amount,
uint256 targetChainId
) external nonReentrant needBridgeIsRunning checkTokenAddress(token) {
require(recipient != address(0), "invalid recipient");
BridgeableTokensConfig storage _tokenConfig = _bridgeableTokens[_encodeTokenWithChainId(token, targetChainId)];
require(_tokenConfig.enabled, "token is not bridgeable");
require(amount > _tokenConfig.bridgeFee, "bridge amount should be greater than fees");
if (globalFeeStatus && _tokenConfig.bridgeFee > 0) {
TokensHelper.safeTransferFrom(token, msg.sender, feeRecipient, _tokenConfig.bridgeFee);
amount -= _tokenConfig.bridgeFee;
}
require(
(amount >= _tokenConfig.minBridgeAmount) && (amount <= _tokenConfig.maxBridgeAmount),
"invalid bridge amount range"
);
if (_tokenConfig.burn) {
TokensHelper.safeBurnFrom(token, msg.sender, amount);
TokensHelper.safeTransferFrom(token, msg.sender, address(this), amount);
}
emit BridgeToSubmitted(token, msg.sender, recipient, amount, _tokenConfig.bridgeFee, chainId(), targetChainId);
}
| 2,477,619
|
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ============================ CurveAMO_V2 ===========================
// ====================================================================
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Travis Moore: https://github.com/FortisFortuna
// Jason Huan: https://github.com/jasonhuan
// Reviewer(s) / Contributor(s)
// Sam Kazemian: https://github.com/samkazemian
// github.com/denett
// NOTE: You can get boosted rewards on your FRAX3CRV liquidity
// https://resources.curve.fi/guides/boosting-your-crv-rewards
// This requires a veCRV / voting logic, which is beyond the scope of this AMO
// Voting logic is also constantly changing, and having fixed code for it is not desireable
// Therefore, CRV rewards and FRAX3CRV will be 'loaned' to the voter contract (can be the timelock in the future)
// which has delegateCall and universal function-calling
// in this manner, the LP-boosted CRV rewards can be captured, rather than non-boosted LP CRV rewards
import "./IStableSwap3Pool.sol";
import "./IMetaImplementationUSD.sol";
import "./ILiquidityGauge.sol";
import "./IMinter.sol";
import "../ERC20/ERC20.sol";
import "../Frax/Frax.sol";
import "../FXS/FXS.sol";
import "../Math/SafeMath.sol";
import "../Proxy/Initializable.sol";
contract CurveAMO_V2 is AccessControl {
using SafeMath for uint256;
/* ========== STATE VARIABLES ========== */
IMetaImplementationUSD private frax3crv_metapool;
IStableSwap3Pool private three_pool;
ILiquidityGauge private gauge_frax3crv;
ERC20 private three_pool_erc20;
FRAXStablecoin private FRAX;
FraxPool private pool;
ERC20 private collateral_token;
address private three_pool_address;
address private three_pool_token_address;
address private fxs_contract_address;
address private collateral_token_address;
address private crv_address;
address public frax3crv_metapool_address;
address public gauge_frax3crv_address;
address public timelock_address;
address public owner_address;
address public custodian_address;
address public pool_address;
address public voter_contract_address; // FRAX3CRV and CRV will be sent here for veCRV voting, locked LP boosts, etc
// Tracks FRAX
uint256 public minted_frax_historical;
uint256 public burned_frax_historical;
// Max amount of FRAX outstanding the contract can mint from the FraxPool
uint256 public max_frax_outstanding;
// Tracks collateral
uint256 public borrowed_collat_historical;
uint256 public returned_collat_historical;
// Max amount of collateral the contract can borrow from the FraxPool
uint256 public collat_borrow_cap;
// Minimum collateral ratio needed for new FRAX minting
uint256 public min_cr;
// Number of decimals under 18, for collateral token
uint256 private missing_decimals;
// Precision related
uint256 private PRICE_PRECISION;
// Min ratio of collat <-> 3crv conversions via add_liquidity / remove_liquidity; 1e6
uint256 public liq_slippage_3crv;
// Min ratio of (FRAX + 3CRV) <-> FRAX3CRV-f-2 metapool conversions via add_liquidity / remove_liquidity; 1e6
uint256 public add_liq_slippage_metapool;
uint256 public rem_liq_slippage_metapool;
// Convergence window
uint256 public convergence_window; // 1 cent
// Default will use global_collateral_ratio()
bool public custom_floor;
uint256 public frax_floor;
// Discount
bool public set_discount;
uint256 public discount_rate;
// Collateral balance related
bool public override_collat_balance;
uint256 public override_collat_balance_amount;
/* ========== CONSTRUCTOR ========== */
constructor(
address _frax_contract_address,
address _fxs_contract_address,
address _collateral_address,
address _creator_address,
address _custodian_address,
address _timelock_address,
address _frax3crv_metapool_address,
address _three_pool_address,
address _three_pool_token_address,
address _pool_address,
address _gauge_frax3crv_address
) public {
FRAX = FRAXStablecoin(_frax_contract_address);
fxs_contract_address = _fxs_contract_address;
collateral_token_address = _collateral_address;
collateral_token = ERC20(_collateral_address);
crv_address = 0xD533a949740bb3306d119CC777fa900bA034cd52;
missing_decimals = uint(18).sub(collateral_token.decimals());
timelock_address = _timelock_address;
owner_address = _creator_address;
custodian_address = _custodian_address;
voter_contract_address = _custodian_address; // Default to the custodian
frax3crv_metapool_address = _frax3crv_metapool_address;
frax3crv_metapool = IMetaImplementationUSD(_frax3crv_metapool_address);
three_pool_address = _three_pool_address;
three_pool = IStableSwap3Pool(_three_pool_address);
three_pool_token_address = _three_pool_token_address;
three_pool_erc20 = ERC20(_three_pool_token_address);
pool_address = _pool_address;
pool = FraxPool(_pool_address);
gauge_frax3crv_address = _gauge_frax3crv_address;
gauge_frax3crv = ILiquidityGauge(_gauge_frax3crv_address);
// Other variable initializations
minted_frax_historical = 0;
burned_frax_historical = 0;
max_frax_outstanding = uint256(2000000e18);
borrowed_collat_historical = 0;
returned_collat_historical = 0;
collat_borrow_cap = uint256(1000000e6);
min_cr = 850000;
PRICE_PRECISION = 1e6;
liq_slippage_3crv = 800000;
add_liq_slippage_metapool = 950000;
rem_liq_slippage_metapool = 950000;
convergence_window = 1e16;
custom_floor = false;
set_discount = false;
override_collat_balance = false;
}
/* ========== MODIFIERS ========== */
modifier onlyByOwnerOrGovernance() {
require(msg.sender == timelock_address || msg.sender == owner_address, "Must be owner or timelock");
_;
}
modifier onlyCustodian() {
require(msg.sender == custodian_address, "Must be rewards custodian");
_;
}
modifier onlyCustodianOrVoter() {
require(msg.sender == custodian_address || msg.sender == voter_contract_address, "Must be rewards custodian or the voter contract");
_;
}
// modifier onlyVoter() {
// require(msg.sender == voter_contract_address, "Must be voter contract");
// _;
// }
/* ========== VIEWS ========== */
function showAllocations() public view returns (uint256[12] memory return_arr) {
// ------------LP Balance------------
// Lent to the voter contract
uint256 lp_lent_to_voter = lentFRAX3CRV();
// Free LP
uint256 lp_owned = (frax3crv_metapool.balanceOf(address(this))).add(lp_lent_to_voter);
// Staked in the gauge
uint256 lp_in_gauge = gauge_frax3crv.balanceOf(address(this));
lp_owned = lp_owned.add(lp_in_gauge);
// ------------3pool Withdrawable------------
// Uses iterate() to get metapool withdrawable amounts at FRAX floor price (global_collateral_ratio)
uint256 frax3crv_supply = frax3crv_metapool.totalSupply();
uint256 frax_withdrawable;
uint256 _3pool_withdrawable;
(frax_withdrawable, _3pool_withdrawable, ) = iterate();
if (frax3crv_supply > 0) {
_3pool_withdrawable = _3pool_withdrawable.mul(lp_owned).div(frax3crv_supply);
frax_withdrawable = frax_withdrawable.mul(lp_owned).div(frax3crv_supply);
}
else _3pool_withdrawable = 0;
// ------------Frax Balance------------
// Frax sums
uint256 frax_in_contract = FRAX.balanceOf(address(this));
// ------------Collateral Balance------------
// Free Collateral
uint256 usdc_in_contract = collateral_token.balanceOf(address(this));
// Returns the dollar value withdrawable of USDC if the contract redeemed its 3CRV from the metapool; assume 1 USDC = $1
uint256 usdc_withdrawable = _3pool_withdrawable.mul(three_pool.get_virtual_price()).div(1e18).div(10 ** missing_decimals);
// USDC subtotal assuming FRAX drops to the CR and all reserves are arbed
uint256 usdc_subtotal = usdc_in_contract.add(usdc_withdrawable);
return [
frax_in_contract, // [0]
frax_withdrawable, // [1]
frax_withdrawable.add(frax_in_contract), // [2]
usdc_in_contract, // [3]
usdc_withdrawable, // [4]
usdc_subtotal, // [5]
usdc_subtotal + (frax_in_contract.add(frax_withdrawable)).mul(fraxDiscountRate()).div(1e6 * (10 ** missing_decimals)), // [6] USDC Total
lp_owned, // [7]
frax3crv_supply, // [8]
_3pool_withdrawable, // [9]
lp_in_gauge, // [10]
lp_lent_to_voter // [11]
];
}
function collatDollarBalance() public view returns (uint256) {
if(override_collat_balance){
return override_collat_balance_amount;
}
return (showAllocations()[6] * (10 ** missing_decimals));
}
// function get_D() public view returns (uint256) {
// // Setting up constants
// uint256 A_PRECISION = 100;
// uint256[2] memory _xp = [three_pool_erc20.balanceOf(frax3crv_metapool_address), FRAX.balanceOf(frax3crv_metapool_address)];
// uint256 N_COINS = 2;
// uint256 S;
// for(uint i = 0; i < N_COINS; i++){
// S += _xp[i];
// }
// if(S == 0){
// return 0;
// }
// uint256 D = S;
// uint256 Ann = N_COINS * frax3crv_metapool.A_precise();
// uint256 Dprev = 0;
// uint256 D_P;
// // Iteratively converge upon D
// for(uint i = 0; i < 256; i++){
// D_P = D;
// for(uint j = 0; j < N_COINS; j++){
// D_P = D * D / (_xp[j] * N_COINS);
// }
// Dprev = D;
// D = (Ann * S / A_PRECISION + D_P * N_COINS) * D / ((Ann - A_PRECISION) * D / A_PRECISION + (N_COINS + 1) * D_P);
// // Check if iteration has converged
// if(D > Dprev){
// if(D - Dprev <= 1){
// return D;
// }
// } else {
// if(Dprev - D <= 1){
// return D;
// }
// }
// }
// // Placeholder, in case it does not converge (should do so within <= 4 rounds)
// revert("Convergence not reached");
// }
// Returns hypothetical reserves of metapool if the FRAX price went to the CR,
// assuming no removal of liquidity from the metapool.
function iterate() public view returns (uint256, uint256, uint256) {
uint256 frax_balance = FRAX.balanceOf(frax3crv_metapool_address);
uint256 crv3_balance = three_pool_erc20.balanceOf(frax3crv_metapool_address);
uint256 floor_price_frax = uint(1e18).mul(fraxFloor()).div(1e6);
uint256 crv3_received;
uint256 dollar_value; // 3crv is usually slightly above $1 due to collecting 3pool swap fees
uint256 virtual_price = three_pool.get_virtual_price();
for(uint i = 0; i < 256; i++){
crv3_received = frax3crv_metapool.get_dy(0, 1, 1e18, [frax_balance, crv3_balance]);
dollar_value = crv3_received.mul(1e18).div(virtual_price);
if(dollar_value <= floor_price_frax.add(convergence_window)){
return (frax_balance, crv3_balance, i);
}
uint256 frax_to_swap = frax_balance.div(10);
crv3_balance = crv3_balance.sub(frax3crv_metapool.get_dy(0, 1, frax_to_swap, [frax_balance, crv3_balance]));
frax_balance = frax_balance.add(frax_to_swap);
}
revert("No hypothetical point"); // in 256 rounds
}
function fraxFloor() public view returns (uint256) {
if(custom_floor){
return frax_floor;
} else {
return FRAX.global_collateral_ratio();
}
}
function fraxDiscountRate() public view returns (uint256) {
if(set_discount){
return discount_rate;
} else {
return FRAX.global_collateral_ratio();
}
}
// In FRAX
function fraxBalance() public view returns (uint256) {
if (minted_frax_historical >= burned_frax_historical) return minted_frax_historical.sub(burned_frax_historical);
else return 0;
}
// In collateral
function collateralBalance() public view returns (uint256) {
if (borrowed_collat_historical >= returned_collat_historical) return borrowed_collat_historical.sub(returned_collat_historical);
else return 0;
}
// FRAX3CRV lent to the voter contract
function lentFRAX3CRV() public view returns (uint256) {
return frax3crv_metapool.balanceOf(voter_contract_address);
}
// REMOVED FOR CONTRACT SIZE CONSIDERATIONS
// // Amount of FRAX3CRV deposited in the gauge contract
// function metapoolLPInGauge() public view returns (uint256){
// return gauge_frax3crv.balanceOf(address(this));
// }
// REMOVED FOR CONTRACT SIZE CONSIDERATIONS
// // This function is problematic because it can be either a view or non-view
// // The self._checkpoint(addr) call inside of it is mutative...
// // Amount of CRV rewards mintable / claimable
// function claimableCRV() public view returns (uint256){
// // Have to manually replicate the formula inside of LiquidityGaugeV2.vy
// // otherwise, it would just be this: return gauge_frax3crv.claimable_tokens(address(this));
// uint256 integrate_fraction = gauge_frax3crv.integrate_fraction(address(this));
// uint256 other_side = IMinter(gauge_frax3crv.minter()).minted(address(this), gauge_frax3crv_address);
// return integrate_fraction.sub(other_side);
// }
/* ========== RESTRICTED FUNCTIONS ========== */
// This is basically a workaround to transfer USDC from the FraxPool to this investor contract
// This contract is essentially marked as a 'pool' so it can call OnlyPools functions like pool_mint and pool_burn_from
// on the main FRAX contract
// It mints FRAX from nothing, and redeems it on the target pool for collateral and FXS
// The burn can be called separately later on
function mintRedeemPart1(uint256 frax_amount) external onlyByOwnerOrGovernance {
//require(allow_yearn || allow_aave || allow_compound, 'All strategies are currently off');
uint256 redemption_fee = pool.redemption_fee();
uint256 col_price_usd = pool.getCollateralPrice();
uint256 global_collateral_ratio = FRAX.global_collateral_ratio();
uint256 redeem_amount_E6 = (frax_amount.mul(uint256(1e6).sub(redemption_fee))).div(1e6).div(10 ** missing_decimals);
uint256 expected_collat_amount = redeem_amount_E6.mul(global_collateral_ratio).div(1e6);
expected_collat_amount = expected_collat_amount.mul(1e6).div(col_price_usd);
require(collateralBalance().add(expected_collat_amount) <= collat_borrow_cap, "Borrow cap");
borrowed_collat_historical = borrowed_collat_historical.add(expected_collat_amount);
// Mint the frax
FRAX.pool_mint(address(this), frax_amount);
// Redeem the frax
FRAX.approve(address(pool), frax_amount);
pool.redeemFractionalFRAX(frax_amount, 0, 0);
}
function mintRedeemPart2() external onlyByOwnerOrGovernance {
pool.collectRedemption();
}
// Give USDC profits back
function giveCollatBack(uint256 amount) external onlyByOwnerOrGovernance {
collateral_token.transfer(address(pool), amount);
returned_collat_historical = returned_collat_historical.add(amount);
}
// Burn unneeded or excess FRAX
function burnFRAX(uint256 frax_amount) public onlyByOwnerOrGovernance {
FRAX.burn(frax_amount);
burned_frax_historical = burned_frax_historical.add(frax_amount);
}
function burnFXS(uint256 amount) public onlyByOwnerOrGovernance {
FRAXShares(fxs_contract_address).approve(address(this), amount);
FRAXShares(fxs_contract_address).pool_burn_from(address(this), amount);
}
function metapoolDeposit(uint256 _frax_amount, uint256 _collateral_amount) external onlyByOwnerOrGovernance returns (uint256 metapool_LP_received) {
// Mint the FRAX component
FRAX.pool_mint(address(this), _frax_amount);
minted_frax_historical = minted_frax_historical.add(_frax_amount);
require(fraxBalance() <= max_frax_outstanding, "max_frax_outstanding reached");
uint256 threeCRV_received = 0;
if (_collateral_amount > 0) {
// Approve the collateral to be added to 3pool
collateral_token.approve(address(three_pool), _collateral_amount);
// Convert collateral into 3pool
uint256[3] memory three_pool_collaterals;
three_pool_collaterals[1] = _collateral_amount;
{
uint256 min_3pool_out = (_collateral_amount * (10 ** missing_decimals)).mul(liq_slippage_3crv).div(PRICE_PRECISION);
three_pool.add_liquidity(three_pool_collaterals, min_3pool_out);
}
// Approve the 3pool for the metapool
threeCRV_received = three_pool_erc20.balanceOf(address(this));
// WEIRD ISSUE: NEED TO DO three_pool_erc20.approve(address(three_pool), 0); first before every time
// May be related to https://github.com/vyperlang/vyper/blob/3e1ff1eb327e9017c5758e24db4bdf66bbfae371/examples/tokens/ERC20.vy#L85
three_pool_erc20.approve(frax3crv_metapool_address, 0);
three_pool_erc20.approve(frax3crv_metapool_address, threeCRV_received);
}
// Approve the FRAX for the metapool
FRAX.approve(frax3crv_metapool_address, _frax_amount);
{
// Add the FRAX and the collateral to the metapool
uint256 min_lp_out = (_frax_amount.add(threeCRV_received)).mul(add_liq_slippage_metapool).div(PRICE_PRECISION);
metapool_LP_received = frax3crv_metapool.add_liquidity([_frax_amount, threeCRV_received], min_lp_out);
}
// Make sure the collateral ratio did not fall too much
uint256 current_collateral_E18 = (FRAX.globalCollateralValue()).mul(10 ** missing_decimals);
uint256 cur_frax_supply = FRAX.totalSupply();
uint256 new_cr = (current_collateral_E18.mul(PRICE_PRECISION)).div(cur_frax_supply);
require (new_cr >= min_cr, "CR would be too low");
return metapool_LP_received;
}
function metapoolWithdrawAtCurRatio(uint256 _metapool_lp_in, bool burn_the_frax, uint256 min_frax, uint256 min_3pool) external onlyByOwnerOrGovernance returns (uint256 frax_received) {
// Approve the metapool LP tokens for the metapool contract
frax3crv_metapool.approve(address(this), _metapool_lp_in);
// Withdraw FRAX and 3pool from the metapool at the current balance
uint256 three_pool_received;
{
uint256[2] memory result_arr = frax3crv_metapool.remove_liquidity(_metapool_lp_in, [min_frax, min_3pool]);
frax_received = result_arr[0];
three_pool_received = result_arr[1];
}
// Convert the 3pool into the collateral
three_pool_erc20.approve(address(three_pool), 0);
three_pool_erc20.approve(address(three_pool), three_pool_received);
{
// Add the FRAX and the collateral to the metapool
uint256 min_collat_out = three_pool_received.mul(liq_slippage_3crv).div(PRICE_PRECISION * (10 ** missing_decimals));
three_pool.remove_liquidity_one_coin(three_pool_received, 1, min_collat_out);
}
// Optionally burn the FRAX
if (burn_the_frax){
burnFRAX(frax_received);
}
}
function metapoolWithdrawFrax(uint256 _metapool_lp_in, bool burn_the_frax) external onlyByOwnerOrGovernance returns (uint256 frax_received) {
// Withdraw FRAX from the metapool
uint256 min_frax_out = _metapool_lp_in.mul(rem_liq_slippage_metapool).div(PRICE_PRECISION);
frax_received = frax3crv_metapool.remove_liquidity_one_coin(_metapool_lp_in, 0, min_frax_out);
// Optionally burn the FRAX
if (burn_the_frax){
burnFRAX(frax_received);
}
}
function metapoolWithdraw3pool(uint256 _metapool_lp_in) public onlyByOwnerOrGovernance {
// Withdraw 3pool from the metapool
uint256 min_3pool_out = _metapool_lp_in.mul(rem_liq_slippage_metapool).div(PRICE_PRECISION);
frax3crv_metapool.remove_liquidity_one_coin(_metapool_lp_in, 1, min_3pool_out);
}
function three_pool_to_collateral(uint256 _3pool_in) public onlyByOwnerOrGovernance {
// Convert the 3pool into the collateral
// WEIRD ISSUE: NEED TO DO three_pool_erc20.approve(address(three_pool), 0); first before every time
// May be related to https://github.com/vyperlang/vyper/blob/3e1ff1eb327e9017c5758e24db4bdf66bbfae371/examples/tokens/ERC20.vy#L85
three_pool_erc20.approve(address(three_pool), 0);
three_pool_erc20.approve(address(three_pool), _3pool_in);
uint256 min_collat_out = _3pool_in.mul(liq_slippage_3crv).div(PRICE_PRECISION * (10 ** missing_decimals));
three_pool.remove_liquidity_one_coin(_3pool_in, 1, min_collat_out);
}
function metapoolWithdrawAndConvert3pool(uint256 _metapool_lp_in) external onlyByOwnerOrGovernance {
metapoolWithdraw3pool(_metapool_lp_in);
three_pool_to_collateral(three_pool_erc20.balanceOf(address(this)));
}
// Deposit Metapool LP tokens into the Curve DAO for gauge rewards, if any
function depositToGauge(uint256 _metapool_lp_in) external onlyByOwnerOrGovernance {
// Approve the metapool LP tokens for the gauge contract
frax3crv_metapool.approve(address(gauge_frax3crv), _metapool_lp_in);
// Deposit the metapool LP into the gauge contract
gauge_frax3crv.deposit(_metapool_lp_in);
}
// Withdraw Metapool LP from Curve DAO back to this contract
function withdrawFromGauge(uint256 _metapool_lp_out) external onlyByOwnerOrGovernance {
gauge_frax3crv.withdraw(_metapool_lp_out);
}
// Checkpoint the Gauge for this address
function checkpointGauge() external onlyByOwnerOrGovernance {
gauge_frax3crv.user_checkpoint(address(this));
}
// Retrieve CRV gauge rewards, if any
function collectCRVFromGauge() external onlyByOwnerOrGovernance {
gauge_frax3crv.claim_rewards(address(this));
IMinter(gauge_frax3crv.minter()).mint(gauge_frax3crv_address);
}
// Loan / transfer FRAX3CRV to the voter contract
function loanFRAX3CRV_To_Voter(uint256 loan_amount) external onlyByOwnerOrGovernance {
frax3crv_metapool.transfer(voter_contract_address, loan_amount);
}
// /* ========== Voter ========== */
// // Repay FRAX3CRV loan (called by the voter contract)
// function repayFRAX3CRV(uint256 repay_amount) external onlyVoter {
// // Remember to approve() first
// frax3crv_metapool.transferFrom(voter_contract_address, address(this), repay_amount);
// }
/* ========== Custodian / Voter========== */
// NOTE: The custodian_address or voter_contract_addresse can be set to the governance contract to be used as
// a mega-voter or sorts. The CRV here can then be converted to veCRV and then used to vote
function withdrawCRVRewards() external onlyCustodianOrVoter {
ERC20(crv_address).transfer(msg.sender, ERC20(crv_address).balanceOf(address(this)));
}
/* ========== RESTRICTED GOVERNANCE FUNCTIONS ========== */
function setTimelock(address new_timelock) external onlyByOwnerOrGovernance {
timelock_address = new_timelock;
}
function setOwner(address _owner_address) external onlyByOwnerOrGovernance {
owner_address = _owner_address;
}
function setMiscRewardsCustodian(address _custodian_address) external onlyByOwnerOrGovernance {
custodian_address = _custodian_address;
}
function setVoterContract(address _voter_contract_address) external onlyByOwnerOrGovernance {
voter_contract_address = _voter_contract_address;
}
function setPool(address _pool_address) external onlyByOwnerOrGovernance {
pool_address = _pool_address;
pool = FraxPool(_pool_address);
}
function setThreePool(address _three_pool_address, address _three_pool_token_address) external onlyByOwnerOrGovernance {
three_pool_address = _three_pool_address;
three_pool = IStableSwap3Pool(_three_pool_address);
three_pool_token_address = _three_pool_token_address;
three_pool_erc20 = ERC20(_three_pool_token_address);
}
function setMetapool(address _metapool_address) external onlyByOwnerOrGovernance {
frax3crv_metapool_address = _metapool_address;
frax3crv_metapool = IMetaImplementationUSD(_metapool_address);
}
function setGauge(address _gauge_frax3crv_address) external onlyByOwnerOrGovernance {
gauge_frax3crv_address = _gauge_frax3crv_address;
gauge_frax3crv = ILiquidityGauge(_gauge_frax3crv_address);
}
function setCollatBorrowCap(uint256 _collat_borrow_cap) external onlyByOwnerOrGovernance {
collat_borrow_cap = _collat_borrow_cap;
}
function setMaxFraxOutstanding(uint256 _max_frax_outstanding) external onlyByOwnerOrGovernance {
max_frax_outstanding = _max_frax_outstanding;
}
function setMinimumCollateralRatio(uint256 _min_cr) external onlyByOwnerOrGovernance {
min_cr = _min_cr;
}
function setConvergenceWindow(uint256 _window) external onlyByOwnerOrGovernance {
convergence_window = _window;
}
function setOverrideCollatBalance(bool _state, uint256 _balance) external onlyByOwnerOrGovernance {
override_collat_balance = _state;
override_collat_balance_amount = _balance;
}
// in terms of 1e6 (overriding global_collateral_ratio)
function setCustomFloor(bool _state, uint256 _floor_price) external onlyByOwnerOrGovernance {
custom_floor = _state;
frax_floor = _floor_price;
}
// in terms of 1e6 (overriding global_collateral_ratio)
function setDiscountRate(bool _state, uint256 _discount_rate) external onlyByOwnerOrGovernance {
set_discount = _state;
discount_rate = _discount_rate;
}
function setSlippages(uint256 _liq_slippage_3crv, uint256 _add_liq_slippage_metapool, uint256 _rem_liq_slippage_metapool) external onlyByOwnerOrGovernance {
liq_slippage_3crv = _liq_slippage_3crv;
add_liq_slippage_metapool = _add_liq_slippage_metapool;
rem_liq_slippage_metapool = _rem_liq_slippage_metapool;
}
function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnerOrGovernance {
// Can only be triggered by owner or governance, not custodian
// Tokens are sent to the custodian, as a sort of safeguard
ERC20(tokenAddress).transfer(custodian_address, tokenAmount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
interface IStableSwap3Pool {
// Deployment
function __init__(address _owner, address[3] memory _coins, address _pool_token, uint256 _A, uint256 _fee, uint256 _admin_fee) external;
// ERC20 Standard
function decimals() external view returns (uint);
function transfer(address _to, uint _value) external returns (uint256);
function transferFrom(address _from, address _to, uint _value) external returns (bool);
function approve(address _spender, uint _value) external returns (bool);
function totalSupply() external view returns (uint);
function mint(address _to, uint256 _value) external returns (bool);
function burnFrom(address _to, uint256 _value) external returns (bool);
function balanceOf(address _owner) external view returns (uint256);
// 3Pool
function A() external view returns (uint);
function get_virtual_price() external view returns (uint);
function calc_token_amount(uint[3] memory amounts, bool deposit) external view returns (uint);
function add_liquidity(uint256[3] memory amounts, uint256 min_mint_amount) external;
function get_dy(int128 i, int128 j, uint256 dx) external view returns (uint256);
function get_dy_underlying(int128 i, int128 j, uint256 dx) external view returns (uint256);
function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy) external;
function remove_liquidity(uint256 _amount, uint256[3] memory min_amounts) external;
function remove_liquidity_imbalance(uint256[3] memory amounts, uint256 max_burn_amount) external;
function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external view returns (uint256);
function remove_liquidity_one_coin(uint256 _token_amount, int128 i, uint256 min_amount) external;
// Admin functions
function ramp_A(uint256 _future_A, uint256 _future_time) external;
function stop_ramp_A() external;
function commit_new_fee(uint256 new_fee, uint256 new_admin_fee) external;
function apply_new_fee() external;
function commit_transfer_ownership(address _owner) external;
function apply_transfer_ownership() external;
function revert_transfer_ownership() external;
function admin_balances(uint256 i) external returns (uint256);
function withdraw_admin_fees() external;
function donate_admin_fees() external;
function kill_me() external;
function unkill_me() external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
interface IMetaImplementationUSD {
// Deployment
function __init__() external;
function initialize(string memory _name, string memory _symbol, address _coin, uint _decimals, uint _A, uint _fee, address _admin) external;
// ERC20 Standard
function decimals() external view returns (uint);
function transfer(address _to, uint _value) external returns (uint256);
function transferFrom(address _from, address _to, uint _value) external returns (bool);
function approve(address _spender, uint _value) external returns (bool);
function balanceOf(address _owner) external view returns (uint256);
function totalSupply() external view returns (uint256);
// StableSwap Functionality
function get_previous_balances() external view returns (uint[2] memory);
function get_twap_balances(uint[2] memory _first_balances, uint[2] memory _last_balances, uint _time_elapsed) external view returns (uint[2] memory);
function get_price_cumulative_last() external view returns (uint[2] memory);
function admin_fee() external view returns (uint);
function A() external view returns (uint);
function A_precise() external view returns (uint);
function get_virtual_price() external view returns (uint);
function calc_token_amount(uint[2] memory _amounts, bool _is_deposit) external view returns (uint);
function calc_token_amount(uint[2] memory _amounts, bool _is_deposit, bool _previous) external view returns (uint);
function add_liquidity(uint[2] memory _amounts, uint _min_mint_amount) external returns (uint);
function add_liquidity(uint[2] memory _amounts, uint _min_mint_amount, address _receiver) external returns (uint);
function get_dy(int128 i, int128 j, uint256 dx) external view returns (uint256);
function get_dy(int128 i, int128 j, uint256 dx, uint256[2] memory _balances) external view returns (uint256);
function get_dy_underlying(int128 i, int128 j, uint256 dx) external view returns (uint256);
function get_dy_underlying(int128 i, int128 j, uint256 dx, uint256[2] memory _balances) external view returns (uint256);
function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy) external returns (uint256);
function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy, address _receiver) external returns (uint256);
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy) external returns (uint256);
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address _receiver) external returns (uint256);
function remove_liquidity(uint256 _burn_amount, uint256[2] memory _min_amounts) external returns (uint256[2] memory);
function remove_liquidity(uint256 _burn_amount, uint256[2] memory _min_amounts, address _receiver) external returns (uint256[2] memory);
function remove_liquidity_imbalance(uint256[2] memory _amounts, uint256 _max_burn_amount) external returns (uint256);
function remove_liquidity_imbalance(uint256[2] memory _amounts, uint256 _max_burn_amount, address _receiver) external returns (uint256);
function calc_withdraw_one_coin(uint256 _burn_amount, int128 i) external view returns (uint256);
function calc_withdraw_one_coin(uint256 _burn_amount, int128 i, bool _previous) external view returns (uint256);
function remove_liquidity_one_coin(uint256 _burn_amount, int128 i, uint256 _min_received) external returns (uint256);
function remove_liquidity_one_coin(uint256 _burn_amount, int128 i, uint256 _min_received, address _receiver) external returns (uint256);
function ramp_A(uint256 _future_A, uint256 _future_time) external;
function stop_ramp_A() external;
function admin_balances(uint256 i) external view returns (uint256);
function withdraw_admin_fees() external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
// https://github.com/swervefi/swerve/blob/master/packages/swerve-contracts/interfaces/ILiquidityGauge.sol
interface ILiquidityGauge {
// Public variables
function minter() external view returns (address);
function crv_token() external view returns (address);
function lp_token() external view returns (address);
function controller() external view returns (address);
function voting_escrow() external view returns (address);
function balanceOf(address) external view returns (uint256);
function totalSupply() external view returns (uint256);
function future_epoch_time() external view returns (uint256);
function approved_to_deposit(address, address) external view returns (bool);
function working_balances(address) external view returns (uint256);
function working_supply() external view returns (uint256);
function period() external view returns (int128);
function period_timestamp(uint256) external view returns (uint256);
function integrate_inv_supply(uint256) external view returns (uint256);
function integrate_inv_supply_of(address) external view returns (uint256);
function integrate_checkpoint_of(address) external view returns (uint256);
function integrate_fraction(address) external view returns (uint256);
function inflation_rate() external view returns (uint256);
// Getter functions
function integrate_checkpoint() external view returns (uint256);
// External functions
function user_checkpoint(address) external returns (bool);
function claim_rewards(address) external;
function claimable_tokens(address) external view returns (uint256); // function can be manually changed to "view" in the ABI
function kick(address) external;
function set_approve_deposit(address, bool) external;
function deposit(uint256) external;
function deposit(uint256, address) external;
function withdraw(uint256) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
// https://github.com/swervefi/swerve/blob/master/packages/swerve-contracts/interfaces/IMinter.sol
interface IMinter {
// Public variables
function minter() external view returns (address);
function controller() external view returns (address);
function minted(address, address) external view returns (uint256);
function allowed_to_mint_for(address, address) external view returns (bool);
// External functions
function mint(address) external;
function mint_many(address[] memory) external;
function mint_for(address, address) external;
function toggle_approve_mint(address) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "../Common/Context.sol";
import "./IERC20.sol";
import "../Math/SafeMath.sol";
import "../Utils/Address.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.approve(address spender, uint256 amount)
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for `accounts`'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal virtual {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of `from`'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of `from`'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:using-hooks.adoc[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ======================= FRAXStablecoin (FRAX) ======================
// ====================================================================
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Travis Moore: https://github.com/FortisFortuna
// Jason Huan: https://github.com/jasonhuan
// Sam Kazemian: https://github.com/samkazemian
// Reviewer(s) / Contributor(s)
// Sam Sun: https://github.com/samczsun
import "../Common/Context.sol";
import "../ERC20/IERC20.sol";
import "../ERC20/ERC20Custom.sol";
import "../ERC20/ERC20.sol";
import "../Math/SafeMath.sol";
import "../FXS/FXS.sol";
import "./Pools/FraxPool.sol";
import "../Oracle/UniswapPairOracle.sol";
import "../Oracle/ChainlinkETHUSDPriceConsumer.sol";
import "../Governance/AccessControl.sol";
contract FRAXStablecoin is ERC20Custom, AccessControl {
using SafeMath for uint256;
/* ========== STATE VARIABLES ========== */
enum PriceChoice { FRAX, FXS }
ChainlinkETHUSDPriceConsumer private eth_usd_pricer;
uint8 private eth_usd_pricer_decimals;
UniswapPairOracle private fraxEthOracle;
UniswapPairOracle private fxsEthOracle;
string public symbol;
string public name;
uint8 public constant decimals = 18;
address public owner_address;
address public creator_address;
address public timelock_address; // Governance timelock address
address public controller_address; // Controller contract to dynamically adjust system parameters automatically
address public fxs_address;
address public frax_eth_oracle_address;
address public fxs_eth_oracle_address;
address public weth_address;
address public eth_usd_consumer_address;
uint256 public constant genesis_supply = 2000000e18; // 2M FRAX (only for testing, genesis supply will be 5k on Mainnet). This is to help with establishing the Uniswap pools, as they need liquidity
// The addresses in this array are added by the oracle and these contracts are able to mint frax
address[] public frax_pools_array;
// Mapping is also used for faster verification
mapping(address => bool) public frax_pools;
// Constants for various precisions
uint256 private constant PRICE_PRECISION = 1e6;
uint256 public global_collateral_ratio; // 6 decimals of precision, e.g. 924102 = 0.924102
uint256 public redemption_fee; // 6 decimals of precision, divide by 1000000 in calculations for fee
uint256 public minting_fee; // 6 decimals of precision, divide by 1000000 in calculations for fee
uint256 public frax_step; // Amount to change the collateralization ratio by upon refreshCollateralRatio()
uint256 public refresh_cooldown; // Seconds to wait before being able to run refreshCollateralRatio() again
uint256 public price_target; // The price of FRAX at which the collateral ratio will respond to; this value is only used for the collateral ratio mechanism and not for minting and redeeming which are hardcoded at $1
uint256 public price_band; // The bound above and below the price target at which the refreshCollateralRatio() will not change the collateral ratio
address public DEFAULT_ADMIN_ADDRESS;
bytes32 public constant COLLATERAL_RATIO_PAUSER = keccak256("COLLATERAL_RATIO_PAUSER");
bool public collateral_ratio_paused = false;
/* ========== MODIFIERS ========== */
modifier onlyCollateralRatioPauser() {
require(hasRole(COLLATERAL_RATIO_PAUSER, msg.sender));
_;
}
modifier onlyPools() {
require(frax_pools[msg.sender] == true, "Only frax pools can call this function");
_;
}
modifier onlyByOwnerOrGovernance() {
require(msg.sender == owner_address || msg.sender == timelock_address || msg.sender == controller_address, "You are not the owner, controller, or the governance timelock");
_;
}
modifier onlyByOwnerGovernanceOrPool() {
require(
msg.sender == owner_address
|| msg.sender == timelock_address
|| frax_pools[msg.sender] == true,
"You are not the owner, the governance timelock, or a pool");
_;
}
/* ========== CONSTRUCTOR ========== */
constructor(
string memory _name,
string memory _symbol,
address _creator_address,
address _timelock_address
) public {
name = _name;
symbol = _symbol;
creator_address = _creator_address;
timelock_address = _timelock_address;
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
DEFAULT_ADMIN_ADDRESS = _msgSender();
owner_address = _creator_address;
_mint(creator_address, genesis_supply);
grantRole(COLLATERAL_RATIO_PAUSER, creator_address);
grantRole(COLLATERAL_RATIO_PAUSER, timelock_address);
frax_step = 2500; // 6 decimals of precision, equal to 0.25%
global_collateral_ratio = 1000000; // Frax system starts off fully collateralized (6 decimals of precision)
refresh_cooldown = 3600; // Refresh cooldown period is set to 1 hour (3600 seconds) at genesis
price_target = 1000000; // Collateral ratio will adjust according to the $1 price target at genesis
price_band = 5000; // Collateral ratio will not adjust if between $0.995 and $1.005 at genesis
}
/* ========== VIEWS ========== */
// Choice = 'FRAX' or 'FXS' for now
function oracle_price(PriceChoice choice) internal view returns (uint256) {
// Get the ETH / USD price first, and cut it down to 1e6 precision
uint256 eth_usd_price = uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals);
uint256 price_vs_eth;
if (choice == PriceChoice.FRAX) {
price_vs_eth = uint256(fraxEthOracle.consult(weth_address, PRICE_PRECISION)); // How much FRAX if you put in PRICE_PRECISION WETH
}
else if (choice == PriceChoice.FXS) {
price_vs_eth = uint256(fxsEthOracle.consult(weth_address, PRICE_PRECISION)); // How much FXS if you put in PRICE_PRECISION WETH
}
else revert("INVALID PRICE CHOICE. Needs to be either 0 (FRAX) or 1 (FXS)");
// Will be in 1e6 format
return eth_usd_price.mul(PRICE_PRECISION).div(price_vs_eth);
}
// Returns X FRAX = 1 USD
function frax_price() public view returns (uint256) {
return oracle_price(PriceChoice.FRAX);
}
// Returns X FXS = 1 USD
function fxs_price() public view returns (uint256) {
return oracle_price(PriceChoice.FXS);
}
function eth_usd_price() public view returns (uint256) {
return uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals);
}
// This is needed to avoid costly repeat calls to different getter functions
// It is cheaper gas-wise to just dump everything and only use some of the info
function frax_info() public view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256) {
return (
oracle_price(PriceChoice.FRAX), // frax_price()
oracle_price(PriceChoice.FXS), // fxs_price()
totalSupply(), // totalSupply()
global_collateral_ratio, // global_collateral_ratio()
globalCollateralValue(), // globalCollateralValue
minting_fee, // minting_fee()
redemption_fee, // redemption_fee()
uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals) //eth_usd_price
);
}
// Iterate through all frax pools and calculate all value of collateral in all pools globally
function globalCollateralValue() public view returns (uint256) {
uint256 total_collateral_value_d18 = 0;
for (uint i = 0; i < frax_pools_array.length; i++){
// Exclude null addresses
if (frax_pools_array[i] != address(0)){
total_collateral_value_d18 = total_collateral_value_d18.add(FraxPool(frax_pools_array[i]).collatDollarBalance());
}
}
return total_collateral_value_d18;
}
/* ========== PUBLIC FUNCTIONS ========== */
// There needs to be a time interval that this can be called. Otherwise it can be called multiple times per expansion.
uint256 public last_call_time; // Last time the refreshCollateralRatio function was called
function refreshCollateralRatio() public {
require(collateral_ratio_paused == false, "Collateral Ratio has been paused");
uint256 frax_price_cur = frax_price();
require(block.timestamp - last_call_time >= refresh_cooldown, "Must wait for the refresh cooldown since last refresh");
// Step increments are 0.25% (upon genesis, changable by setFraxStep())
if (frax_price_cur > price_target.add(price_band)) { //decrease collateral ratio
if(global_collateral_ratio <= frax_step){ //if within a step of 0, go to 0
global_collateral_ratio = 0;
} else {
global_collateral_ratio = global_collateral_ratio.sub(frax_step);
}
} else if (frax_price_cur < price_target.sub(price_band)) { //increase collateral ratio
if(global_collateral_ratio.add(frax_step) >= 1000000){
global_collateral_ratio = 1000000; // cap collateral ratio at 1.000000
} else {
global_collateral_ratio = global_collateral_ratio.add(frax_step);
}
}
last_call_time = block.timestamp; // Set the time of the last expansion
}
/* ========== RESTRICTED FUNCTIONS ========== */
// Used by pools when user redeems
function pool_burn_from(address b_address, uint256 b_amount) public onlyPools {
super._burnFrom(b_address, b_amount);
emit FRAXBurned(b_address, msg.sender, b_amount);
}
// This function is what other frax pools will call to mint new FRAX
function pool_mint(address m_address, uint256 m_amount) public onlyPools {
super._mint(m_address, m_amount);
emit FRAXMinted(msg.sender, m_address, m_amount);
}
// Adds collateral addresses supported, such as tether and busd, must be ERC20
function addPool(address pool_address) public onlyByOwnerOrGovernance {
require(frax_pools[pool_address] == false, "address already exists");
frax_pools[pool_address] = true;
frax_pools_array.push(pool_address);
}
// Remove a pool
function removePool(address pool_address) public onlyByOwnerOrGovernance {
require(frax_pools[pool_address] == true, "address doesn't exist already");
// Delete from the mapping
delete frax_pools[pool_address];
// 'Delete' from the array by setting the address to 0x0
for (uint i = 0; i < frax_pools_array.length; i++){
if (frax_pools_array[i] == pool_address) {
frax_pools_array[i] = address(0); // This will leave a null in the array and keep the indices the same
break;
}
}
}
function setOwner(address _owner_address) external onlyByOwnerOrGovernance {
owner_address = _owner_address;
}
function setRedemptionFee(uint256 red_fee) public onlyByOwnerOrGovernance {
redemption_fee = red_fee;
}
function setMintingFee(uint256 min_fee) public onlyByOwnerOrGovernance {
minting_fee = min_fee;
}
function setFraxStep(uint256 _new_step) public onlyByOwnerOrGovernance {
frax_step = _new_step;
}
function setPriceTarget (uint256 _new_price_target) public onlyByOwnerOrGovernance {
price_target = _new_price_target;
}
function setRefreshCooldown(uint256 _new_cooldown) public onlyByOwnerOrGovernance {
refresh_cooldown = _new_cooldown;
}
function setFXSAddress(address _fxs_address) public onlyByOwnerOrGovernance {
fxs_address = _fxs_address;
}
function setETHUSDOracle(address _eth_usd_consumer_address) public onlyByOwnerOrGovernance {
eth_usd_consumer_address = _eth_usd_consumer_address;
eth_usd_pricer = ChainlinkETHUSDPriceConsumer(eth_usd_consumer_address);
eth_usd_pricer_decimals = eth_usd_pricer.getDecimals();
}
function setTimelock(address new_timelock) external onlyByOwnerOrGovernance {
timelock_address = new_timelock;
}
function setController(address _controller_address) external onlyByOwnerOrGovernance {
controller_address = _controller_address;
}
function setPriceBand(uint256 _price_band) external onlyByOwnerOrGovernance {
price_band = _price_band;
}
// Sets the FRAX_ETH Uniswap oracle address
function setFRAXEthOracle(address _frax_oracle_addr, address _weth_address) public onlyByOwnerOrGovernance {
frax_eth_oracle_address = _frax_oracle_addr;
fraxEthOracle = UniswapPairOracle(_frax_oracle_addr);
weth_address = _weth_address;
}
// Sets the FXS_ETH Uniswap oracle address
function setFXSEthOracle(address _fxs_oracle_addr, address _weth_address) public onlyByOwnerOrGovernance {
fxs_eth_oracle_address = _fxs_oracle_addr;
fxsEthOracle = UniswapPairOracle(_fxs_oracle_addr);
weth_address = _weth_address;
}
function toggleCollateralRatio() public onlyCollateralRatioPauser {
collateral_ratio_paused = !collateral_ratio_paused;
}
/* ========== EVENTS ========== */
// Track FRAX burned
event FRAXBurned(address indexed from, address indexed to, uint256 amount);
// Track FRAX minted
event FRAXMinted(address indexed from, address indexed to, uint256 amount);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ========================= FRAXShares (FXS) =========================
// ====================================================================
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Travis Moore: https://github.com/FortisFortuna
// Jason Huan: https://github.com/jasonhuan
// Sam Kazemian: https://github.com/samkazemian
// Reviewer(s) / Contributor(s)
// Sam Sun: https://github.com/samczsun
import "../Common/Context.sol";
import "../ERC20/ERC20Custom.sol";
import "../ERC20/IERC20.sol";
import "../Frax/Frax.sol";
import "../Math/SafeMath.sol";
import "../Governance/AccessControl.sol";
contract FRAXShares is ERC20Custom, AccessControl {
using SafeMath for uint256;
/* ========== STATE VARIABLES ========== */
string public symbol;
string public name;
uint8 public constant decimals = 18;
address public FRAXStablecoinAdd;
uint256 public constant genesis_supply = 100000000e18; // 100M is printed upon genesis
uint256 public FXS_DAO_min; // Minimum FXS required to join DAO groups
address public owner_address;
address public oracle_address;
address public timelock_address; // Governance timelock address
FRAXStablecoin private FRAX;
bool public trackingVotes = true; // Tracking votes (only change if need to disable votes)
// A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
// A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
// The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/* ========== MODIFIERS ========== */
modifier onlyPools() {
require(FRAX.frax_pools(msg.sender) == true, "Only frax pools can mint new FRAX");
_;
}
modifier onlyByOwnerOrGovernance() {
require(msg.sender == owner_address || msg.sender == timelock_address, "You are not an owner or the governance timelock");
_;
}
/* ========== CONSTRUCTOR ========== */
constructor(
string memory _name,
string memory _symbol,
address _oracle_address,
address _owner_address,
address _timelock_address
) public {
name = _name;
symbol = _symbol;
owner_address = _owner_address;
oracle_address = _oracle_address;
timelock_address = _timelock_address;
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_mint(owner_address, genesis_supply);
// Do a checkpoint for the owner
_writeCheckpoint(owner_address, 0, 0, uint96(genesis_supply));
}
/* ========== RESTRICTED FUNCTIONS ========== */
function setOracle(address new_oracle) external onlyByOwnerOrGovernance {
oracle_address = new_oracle;
}
function setTimelock(address new_timelock) external onlyByOwnerOrGovernance {
timelock_address = new_timelock;
}
function setFRAXAddress(address frax_contract_address) external onlyByOwnerOrGovernance {
FRAX = FRAXStablecoin(frax_contract_address);
}
function setFXSMinDAO(uint256 min_FXS) external onlyByOwnerOrGovernance {
FXS_DAO_min = min_FXS;
}
function setOwner(address _owner_address) external onlyByOwnerOrGovernance {
owner_address = _owner_address;
}
function mint(address to, uint256 amount) public onlyPools {
_mint(to, amount);
}
// This function is what other frax pools will call to mint new FXS (similar to the FRAX mint)
function pool_mint(address m_address, uint256 m_amount) external onlyPools {
if(trackingVotes){
uint32 srcRepNum = numCheckpoints[address(this)];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[address(this)][srcRepNum - 1].votes : 0;
uint96 srcRepNew = add96(srcRepOld, uint96(m_amount), "pool_mint new votes overflows");
_writeCheckpoint(address(this), srcRepNum, srcRepOld, srcRepNew); // mint new votes
trackVotes(address(this), m_address, uint96(m_amount));
}
super._mint(m_address, m_amount);
emit FXSMinted(address(this), m_address, m_amount);
}
// This function is what other frax pools will call to burn FXS
function pool_burn_from(address b_address, uint256 b_amount) external onlyPools {
if(trackingVotes){
trackVotes(b_address, address(this), uint96(b_amount));
uint32 srcRepNum = numCheckpoints[address(this)];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[address(this)][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, uint96(b_amount), "pool_burn_from new votes underflows");
_writeCheckpoint(address(this), srcRepNum, srcRepOld, srcRepNew); // burn votes
}
super._burnFrom(b_address, b_amount);
emit FXSBurned(b_address, address(this), b_amount);
}
function toggleVotes() external onlyByOwnerOrGovernance {
trackingVotes = !trackingVotes;
}
/* ========== OVERRIDDEN PUBLIC FUNCTIONS ========== */
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
if(trackingVotes){
// Transfer votes
trackVotes(_msgSender(), recipient, uint96(amount));
}
_transfer(_msgSender(), recipient, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
if(trackingVotes){
// Transfer votes
trackVotes(sender, recipient, uint96(amount));
}
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/* ========== PUBLIC FUNCTIONS ========== */
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "FXS::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
/* ========== INTERNAL FUNCTIONS ========== */
// From compound's _moveDelegates
// Keep track of votes. "Delegates" is a misnomer here
function trackVotes(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "FXS::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "FXS::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address voter, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "FXS::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[voter][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[voter][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[voter][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[voter] = nCheckpoints + 1;
}
emit VoterVotesChanged(voter, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
/* ========== EVENTS ========== */
/// @notice An event thats emitted when a voters account's vote balance changes
event VoterVotesChanged(address indexed voter, uint previousBalance, uint newBalance);
// Track FXS burned
event FXSBurned(address indexed from, address indexed to, uint256 amount);
// Track FXS minted
event FXSMinted(address indexed from, address indexed to, uint256 amount);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
/**
* @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;
}
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.6.0 <0.9.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.6.11;
/*
* @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 { }
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.11;
import "../Common/Context.sol";
import "../Math/SafeMath.sol";
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.11 <0.9.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.11;
import "../Common/Context.sol";
import "./IERC20.sol";
import "../Math/SafeMath.sol";
import "../Utils/Address.sol";
// Due to compiling issues, _name, _symbol, and _decimals were removed
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Custom is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) internal _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.approve(address spender, uint256 amount)
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for `accounts`'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal virtual {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of `from`'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of `from`'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:using-hooks.adoc[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ============================= FraxPool =============================
// ====================================================================
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Travis Moore: https://github.com/FortisFortuna
// Jason Huan: https://github.com/jasonhuan
// Sam Kazemian: https://github.com/samkazemian
// Reviewer(s) / Contributor(s)
// Sam Sun: https://github.com/samczsun
import "../../Math/SafeMath.sol";
import "../../FXS/FXS.sol";
import "../../Frax/Frax.sol";
import "../../ERC20/ERC20.sol";
import "../../Oracle/UniswapPairOracle.sol";
import "../../Governance/AccessControl.sol";
import "./FraxPoolLibrary.sol";
contract FraxPool is AccessControl {
using SafeMath for uint256;
/* ========== STATE VARIABLES ========== */
ERC20 private collateral_token;
address private collateral_address;
address private owner_address;
address private frax_contract_address;
address private fxs_contract_address;
address private timelock_address;
FRAXShares private FXS;
FRAXStablecoin private FRAX;
UniswapPairOracle private collatEthOracle;
address public collat_eth_oracle_address;
address private weth_address;
uint256 public minting_fee;
uint256 public redemption_fee;
uint256 public buyback_fee;
uint256 public recollat_fee;
mapping (address => uint256) public redeemFXSBalances;
mapping (address => uint256) public redeemCollateralBalances;
uint256 public unclaimedPoolCollateral;
uint256 public unclaimedPoolFXS;
mapping (address => uint256) public lastRedeemed;
// Constants for various precisions
uint256 private constant PRICE_PRECISION = 1e6;
uint256 private constant COLLATERAL_RATIO_PRECISION = 1e6;
uint256 private constant COLLATERAL_RATIO_MAX = 1e6;
// Number of decimals needed to get to 18
uint256 private immutable missing_decimals;
// Pool_ceiling is the total units of collateral that a pool contract can hold
uint256 public pool_ceiling = 0;
// Stores price of the collateral, if price is paused
uint256 public pausedPrice = 0;
// Bonus rate on FXS minted during recollateralizeFRAX(); 6 decimals of precision, set to 0.75% on genesis
uint256 public bonus_rate = 7500;
// Number of blocks to wait before being able to collectRedemption()
uint256 public redemption_delay = 1;
// AccessControl Roles
bytes32 private constant MINT_PAUSER = keccak256("MINT_PAUSER");
bytes32 private constant REDEEM_PAUSER = keccak256("REDEEM_PAUSER");
bytes32 private constant BUYBACK_PAUSER = keccak256("BUYBACK_PAUSER");
bytes32 private constant RECOLLATERALIZE_PAUSER = keccak256("RECOLLATERALIZE_PAUSER");
bytes32 private constant COLLATERAL_PRICE_PAUSER = keccak256("COLLATERAL_PRICE_PAUSER");
// AccessControl state variables
bool public mintPaused = false;
bool public redeemPaused = false;
bool public recollateralizePaused = false;
bool public buyBackPaused = false;
bool public collateralPricePaused = false;
/* ========== MODIFIERS ========== */
modifier onlyByOwnerOrGovernance() {
require(msg.sender == timelock_address || msg.sender == owner_address, "You are not the owner or the governance timelock");
_;
}
modifier notRedeemPaused() {
require(redeemPaused == false, "Redeeming is paused");
_;
}
modifier notMintPaused() {
require(mintPaused == false, "Minting is paused");
_;
}
/* ========== CONSTRUCTOR ========== */
constructor(
address _frax_contract_address,
address _fxs_contract_address,
address _collateral_address,
address _creator_address,
address _timelock_address,
uint256 _pool_ceiling
) public {
FRAX = FRAXStablecoin(_frax_contract_address);
FXS = FRAXShares(_fxs_contract_address);
frax_contract_address = _frax_contract_address;
fxs_contract_address = _fxs_contract_address;
collateral_address = _collateral_address;
timelock_address = _timelock_address;
owner_address = _creator_address;
collateral_token = ERC20(_collateral_address);
pool_ceiling = _pool_ceiling;
missing_decimals = uint(18).sub(collateral_token.decimals());
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
grantRole(MINT_PAUSER, timelock_address);
grantRole(REDEEM_PAUSER, timelock_address);
grantRole(RECOLLATERALIZE_PAUSER, timelock_address);
grantRole(BUYBACK_PAUSER, timelock_address);
grantRole(COLLATERAL_PRICE_PAUSER, timelock_address);
}
/* ========== VIEWS ========== */
// Returns dollar value of collateral held in this Frax pool
function collatDollarBalance() public view returns (uint256) {
if(collateralPricePaused == true){
return (collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral)).mul(10 ** missing_decimals).mul(pausedPrice).div(PRICE_PRECISION);
} else {
uint256 eth_usd_price = FRAX.eth_usd_price();
uint256 eth_collat_price = collatEthOracle.consult(weth_address, (PRICE_PRECISION * (10 ** missing_decimals)));
uint256 collat_usd_price = eth_usd_price.mul(PRICE_PRECISION).div(eth_collat_price);
return (collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral)).mul(10 ** missing_decimals).mul(collat_usd_price).div(PRICE_PRECISION); //.mul(getCollateralPrice()).div(1e6);
}
}
// Returns the value of excess collateral held in this Frax pool, compared to what is needed to maintain the global collateral ratio
function availableExcessCollatDV() public view returns (uint256) {
uint256 total_supply = FRAX.totalSupply();
uint256 global_collateral_ratio = FRAX.global_collateral_ratio();
uint256 global_collat_value = FRAX.globalCollateralValue();
if (global_collateral_ratio > COLLATERAL_RATIO_PRECISION) global_collateral_ratio = COLLATERAL_RATIO_PRECISION; // Handles an overcollateralized contract with CR > 1
uint256 required_collat_dollar_value_d18 = (total_supply.mul(global_collateral_ratio)).div(COLLATERAL_RATIO_PRECISION); // Calculates collateral needed to back each 1 FRAX with $1 of collateral at current collat ratio
if (global_collat_value > required_collat_dollar_value_d18) return global_collat_value.sub(required_collat_dollar_value_d18);
else return 0;
}
/* ========== PUBLIC FUNCTIONS ========== */
// Returns the price of the pool collateral in USD
function getCollateralPrice() public view returns (uint256) {
if(collateralPricePaused == true){
return pausedPrice;
} else {
uint256 eth_usd_price = FRAX.eth_usd_price();
return eth_usd_price.mul(PRICE_PRECISION).div(collatEthOracle.consult(weth_address, PRICE_PRECISION * (10 ** missing_decimals)));
}
}
function setCollatETHOracle(address _collateral_weth_oracle_address, address _weth_address) external onlyByOwnerOrGovernance {
collat_eth_oracle_address = _collateral_weth_oracle_address;
collatEthOracle = UniswapPairOracle(_collateral_weth_oracle_address);
weth_address = _weth_address;
}
// We separate out the 1t1, fractional and algorithmic minting functions for gas efficiency
function mint1t1FRAX(uint256 collateral_amount, uint256 FRAX_out_min) external notMintPaused {
uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals);
require(FRAX.global_collateral_ratio() >= COLLATERAL_RATIO_MAX, "Collateral ratio must be >= 1");
require((collateral_token.balanceOf(address(this))).sub(unclaimedPoolCollateral).add(collateral_amount) <= pool_ceiling, "[Pool's Closed]: Ceiling reached");
(uint256 frax_amount_d18) = FraxPoolLibrary.calcMint1t1FRAX(
getCollateralPrice(),
collateral_amount_d18
); //1 FRAX for each $1 worth of collateral
frax_amount_d18 = (frax_amount_d18.mul(uint(1e6).sub(minting_fee))).div(1e6); //remove precision at the end
require(FRAX_out_min <= frax_amount_d18, "Slippage limit reached");
collateral_token.transferFrom(msg.sender, address(this), collateral_amount);
FRAX.pool_mint(msg.sender, frax_amount_d18);
}
// 0% collateral-backed
function mintAlgorithmicFRAX(uint256 fxs_amount_d18, uint256 FRAX_out_min) external notMintPaused {
uint256 fxs_price = FRAX.fxs_price();
require(FRAX.global_collateral_ratio() == 0, "Collateral ratio must be 0");
(uint256 frax_amount_d18) = FraxPoolLibrary.calcMintAlgorithmicFRAX(
fxs_price, // X FXS / 1 USD
fxs_amount_d18
);
frax_amount_d18 = (frax_amount_d18.mul(uint(1e6).sub(minting_fee))).div(1e6);
require(FRAX_out_min <= frax_amount_d18, "Slippage limit reached");
FXS.pool_burn_from(msg.sender, fxs_amount_d18);
FRAX.pool_mint(msg.sender, frax_amount_d18);
}
// Will fail if fully collateralized or fully algorithmic
// > 0% and < 100% collateral-backed
function mintFractionalFRAX(uint256 collateral_amount, uint256 fxs_amount, uint256 FRAX_out_min) external notMintPaused {
uint256 fxs_price = FRAX.fxs_price();
uint256 global_collateral_ratio = FRAX.global_collateral_ratio();
require(global_collateral_ratio < COLLATERAL_RATIO_MAX && global_collateral_ratio > 0, "Collateral ratio needs to be between .000001 and .999999");
require(collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral).add(collateral_amount) <= pool_ceiling, "Pool ceiling reached, no more FRAX can be minted with this collateral");
uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals);
FraxPoolLibrary.MintFF_Params memory input_params = FraxPoolLibrary.MintFF_Params(
fxs_price,
getCollateralPrice(),
fxs_amount,
collateral_amount_d18,
global_collateral_ratio
);
(uint256 mint_amount, uint256 fxs_needed) = FraxPoolLibrary.calcMintFractionalFRAX(input_params);
mint_amount = (mint_amount.mul(uint(1e6).sub(minting_fee))).div(1e6);
require(FRAX_out_min <= mint_amount, "Slippage limit reached");
require(fxs_needed <= fxs_amount, "Not enough FXS inputted");
FXS.pool_burn_from(msg.sender, fxs_needed);
collateral_token.transferFrom(msg.sender, address(this), collateral_amount);
FRAX.pool_mint(msg.sender, mint_amount);
}
// Redeem collateral. 100% collateral-backed
function redeem1t1FRAX(uint256 FRAX_amount, uint256 COLLATERAL_out_min) external notRedeemPaused {
require(FRAX.global_collateral_ratio() == COLLATERAL_RATIO_MAX, "Collateral ratio must be == 1");
// Need to adjust for decimals of collateral
uint256 FRAX_amount_precision = FRAX_amount.div(10 ** missing_decimals);
(uint256 collateral_needed) = FraxPoolLibrary.calcRedeem1t1FRAX(
getCollateralPrice(),
FRAX_amount_precision
);
collateral_needed = (collateral_needed.mul(uint(1e6).sub(redemption_fee))).div(1e6);
require(collateral_needed <= collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral), "Not enough collateral in pool");
require(COLLATERAL_out_min <= collateral_needed, "Slippage limit reached");
redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender].add(collateral_needed);
unclaimedPoolCollateral = unclaimedPoolCollateral.add(collateral_needed);
lastRedeemed[msg.sender] = block.number;
// Move all external functions to the end
FRAX.pool_burn_from(msg.sender, FRAX_amount);
}
// Will fail if fully collateralized or algorithmic
// Redeem FRAX for collateral and FXS. > 0% and < 100% collateral-backed
function redeemFractionalFRAX(uint256 FRAX_amount, uint256 FXS_out_min, uint256 COLLATERAL_out_min) external notRedeemPaused {
uint256 fxs_price = FRAX.fxs_price();
uint256 global_collateral_ratio = FRAX.global_collateral_ratio();
require(global_collateral_ratio < COLLATERAL_RATIO_MAX && global_collateral_ratio > 0, "Collateral ratio needs to be between .000001 and .999999");
uint256 col_price_usd = getCollateralPrice();
uint256 FRAX_amount_post_fee = (FRAX_amount.mul(uint(1e6).sub(redemption_fee))).div(PRICE_PRECISION);
uint256 fxs_dollar_value_d18 = FRAX_amount_post_fee.sub(FRAX_amount_post_fee.mul(global_collateral_ratio).div(PRICE_PRECISION));
uint256 fxs_amount = fxs_dollar_value_d18.mul(PRICE_PRECISION).div(fxs_price);
// Need to adjust for decimals of collateral
uint256 FRAX_amount_precision = FRAX_amount_post_fee.div(10 ** missing_decimals);
uint256 collateral_dollar_value = FRAX_amount_precision.mul(global_collateral_ratio).div(PRICE_PRECISION);
uint256 collateral_amount = collateral_dollar_value.mul(PRICE_PRECISION).div(col_price_usd);
require(collateral_amount <= collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral), "Not enough collateral in pool");
require(COLLATERAL_out_min <= collateral_amount, "Slippage limit reached [collateral]");
require(FXS_out_min <= fxs_amount, "Slippage limit reached [FXS]");
redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender].add(collateral_amount);
unclaimedPoolCollateral = unclaimedPoolCollateral.add(collateral_amount);
redeemFXSBalances[msg.sender] = redeemFXSBalances[msg.sender].add(fxs_amount);
unclaimedPoolFXS = unclaimedPoolFXS.add(fxs_amount);
lastRedeemed[msg.sender] = block.number;
// Move all external functions to the end
FRAX.pool_burn_from(msg.sender, FRAX_amount);
FXS.pool_mint(address(this), fxs_amount);
}
// Redeem FRAX for FXS. 0% collateral-backed
function redeemAlgorithmicFRAX(uint256 FRAX_amount, uint256 FXS_out_min) external notRedeemPaused {
uint256 fxs_price = FRAX.fxs_price();
uint256 global_collateral_ratio = FRAX.global_collateral_ratio();
require(global_collateral_ratio == 0, "Collateral ratio must be 0");
uint256 fxs_dollar_value_d18 = FRAX_amount;
fxs_dollar_value_d18 = (fxs_dollar_value_d18.mul(uint(1e6).sub(redemption_fee))).div(PRICE_PRECISION); //apply fees
uint256 fxs_amount = fxs_dollar_value_d18.mul(PRICE_PRECISION).div(fxs_price);
redeemFXSBalances[msg.sender] = redeemFXSBalances[msg.sender].add(fxs_amount);
unclaimedPoolFXS = unclaimedPoolFXS.add(fxs_amount);
lastRedeemed[msg.sender] = block.number;
require(FXS_out_min <= fxs_amount, "Slippage limit reached");
// Move all external functions to the end
FRAX.pool_burn_from(msg.sender, FRAX_amount);
FXS.pool_mint(address(this), fxs_amount);
}
// After a redemption happens, transfer the newly minted FXS and owed collateral from this pool
// contract to the user. Redemption is split into two functions to prevent flash loans from being able
// to take out FRAX/collateral from the system, use an AMM to trade the new price, and then mint back into the system.
function collectRedemption() external {
require((lastRedeemed[msg.sender].add(redemption_delay)) <= block.number, "Must wait for redemption_delay blocks before collecting redemption");
bool sendFXS = false;
bool sendCollateral = false;
uint FXSAmount;
uint CollateralAmount;
// Use Checks-Effects-Interactions pattern
if(redeemFXSBalances[msg.sender] > 0){
FXSAmount = redeemFXSBalances[msg.sender];
redeemFXSBalances[msg.sender] = 0;
unclaimedPoolFXS = unclaimedPoolFXS.sub(FXSAmount);
sendFXS = true;
}
if(redeemCollateralBalances[msg.sender] > 0){
CollateralAmount = redeemCollateralBalances[msg.sender];
redeemCollateralBalances[msg.sender] = 0;
unclaimedPoolCollateral = unclaimedPoolCollateral.sub(CollateralAmount);
sendCollateral = true;
}
if(sendFXS == true){
FXS.transfer(msg.sender, FXSAmount);
}
if(sendCollateral == true){
collateral_token.transfer(msg.sender, CollateralAmount);
}
}
// When the protocol is recollateralizing, we need to give a discount of FXS to hit the new CR target
// Thus, if the target collateral ratio is higher than the actual value of collateral, minters get FXS for adding collateral
// This function simply rewards anyone that sends collateral to a pool with the same amount of FXS + the bonus rate
// Anyone can call this function to recollateralize the protocol and take the extra FXS value from the bonus rate as an arb opportunity
function recollateralizeFRAX(uint256 collateral_amount, uint256 FXS_out_min) external {
require(recollateralizePaused == false, "Recollateralize is paused");
uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals);
uint256 fxs_price = FRAX.fxs_price();
uint256 frax_total_supply = FRAX.totalSupply();
uint256 global_collateral_ratio = FRAX.global_collateral_ratio();
uint256 global_collat_value = FRAX.globalCollateralValue();
(uint256 collateral_units, uint256 amount_to_recollat) = FraxPoolLibrary.calcRecollateralizeFRAXInner(
collateral_amount_d18,
getCollateralPrice(),
global_collat_value,
frax_total_supply,
global_collateral_ratio
);
uint256 collateral_units_precision = collateral_units.div(10 ** missing_decimals);
uint256 fxs_paid_back = amount_to_recollat.mul(uint(1e6).add(bonus_rate).sub(recollat_fee)).div(fxs_price);
require(FXS_out_min <= fxs_paid_back, "Slippage limit reached");
collateral_token.transferFrom(msg.sender, address(this), collateral_units_precision);
FXS.pool_mint(msg.sender, fxs_paid_back);
}
// Function can be called by an FXS holder to have the protocol buy back FXS with excess collateral value from a desired collateral pool
// This can also happen if the collateral ratio > 1
function buyBackFXS(uint256 FXS_amount, uint256 COLLATERAL_out_min) external {
require(buyBackPaused == false, "Buyback is paused");
uint256 fxs_price = FRAX.fxs_price();
FraxPoolLibrary.BuybackFXS_Params memory input_params = FraxPoolLibrary.BuybackFXS_Params(
availableExcessCollatDV(),
fxs_price,
getCollateralPrice(),
FXS_amount
);
(uint256 collateral_equivalent_d18) = (FraxPoolLibrary.calcBuyBackFXS(input_params)).mul(uint(1e6).sub(buyback_fee)).div(1e6);
uint256 collateral_precision = collateral_equivalent_d18.div(10 ** missing_decimals);
require(COLLATERAL_out_min <= collateral_precision, "Slippage limit reached");
// Give the sender their desired collateral and burn the FXS
FXS.pool_burn_from(msg.sender, FXS_amount);
collateral_token.transfer(msg.sender, collateral_precision);
}
/* ========== RESTRICTED FUNCTIONS ========== */
function toggleMinting() external {
require(hasRole(MINT_PAUSER, msg.sender));
mintPaused = !mintPaused;
}
function toggleRedeeming() external {
require(hasRole(REDEEM_PAUSER, msg.sender));
redeemPaused = !redeemPaused;
}
function toggleRecollateralize() external {
require(hasRole(RECOLLATERALIZE_PAUSER, msg.sender));
recollateralizePaused = !recollateralizePaused;
}
function toggleBuyBack() external {
require(hasRole(BUYBACK_PAUSER, msg.sender));
buyBackPaused = !buyBackPaused;
}
function toggleCollateralPrice(uint256 _new_price) external {
require(hasRole(COLLATERAL_PRICE_PAUSER, msg.sender));
// If pausing, set paused price; else if unpausing, clear pausedPrice
if(collateralPricePaused == false){
pausedPrice = _new_price;
} else {
pausedPrice = 0;
}
collateralPricePaused = !collateralPricePaused;
}
// Combined into one function due to 24KiB contract memory limit
function setPoolParameters(uint256 new_ceiling, uint256 new_bonus_rate, uint256 new_redemption_delay, uint256 new_mint_fee, uint256 new_redeem_fee, uint256 new_buyback_fee, uint256 new_recollat_fee) external onlyByOwnerOrGovernance {
pool_ceiling = new_ceiling;
bonus_rate = new_bonus_rate;
redemption_delay = new_redemption_delay;
minting_fee = new_mint_fee;
redemption_fee = new_redeem_fee;
buyback_fee = new_buyback_fee;
recollat_fee = new_recollat_fee;
}
function setTimelock(address new_timelock) external onlyByOwnerOrGovernance {
timelock_address = new_timelock;
}
function setOwner(address _owner_address) external onlyByOwnerOrGovernance {
owner_address = _owner_address;
}
/* ========== EVENTS ========== */
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import '../Uniswap/Interfaces/IUniswapV2Factory.sol';
import '../Uniswap/Interfaces/IUniswapV2Pair.sol';
import '../Math/FixedPoint.sol';
import '../Uniswap/UniswapV2OracleLibrary.sol';
import '../Uniswap/UniswapV2Library.sol';
// Fixed window oracle that recomputes the average price for the entire period once every period
// Note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period
contract UniswapPairOracle {
using FixedPoint for *;
address owner_address;
address timelock_address;
uint public PERIOD = 3600; // 1 hour TWAP (time-weighted average price)
uint public CONSULT_LENIENCY = 120; // Used for being able to consult past the period end
bool public ALLOW_STALE_CONSULTS = false; // If false, consult() will fail if the TWAP is stale
IUniswapV2Pair public immutable pair;
address public immutable token0;
address public immutable token1;
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint32 public blockTimestampLast;
FixedPoint.uq112x112 public price0Average;
FixedPoint.uq112x112 public price1Average;
modifier onlyByOwnerOrGovernance() {
require(msg.sender == owner_address || msg.sender == timelock_address, "You are not an owner or the governance timelock");
_;
}
constructor(address factory, address tokenA, address tokenB, address _owner_address, address _timelock_address) public {
IUniswapV2Pair _pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, tokenA, tokenB));
pair = _pair;
token0 = _pair.token0();
token1 = _pair.token1();
price0CumulativeLast = _pair.price0CumulativeLast(); // Fetch the current accumulated price value (1 / 0)
price1CumulativeLast = _pair.price1CumulativeLast(); // Fetch the current accumulated price value (0 / 1)
uint112 reserve0;
uint112 reserve1;
(reserve0, reserve1, blockTimestampLast) = _pair.getReserves();
require(reserve0 != 0 && reserve1 != 0, 'UniswapPairOracle: NO_RESERVES'); // Ensure that there's liquidity in the pair
owner_address = _owner_address;
timelock_address = _timelock_address;
}
function setOwner(address _owner_address) external onlyByOwnerOrGovernance {
owner_address = _owner_address;
}
function setTimelock(address _timelock_address) external onlyByOwnerOrGovernance {
timelock_address = _timelock_address;
}
function setPeriod(uint _period) external onlyByOwnerOrGovernance {
PERIOD = _period;
}
function setConsultLeniency(uint _consult_leniency) external onlyByOwnerOrGovernance {
CONSULT_LENIENCY = _consult_leniency;
}
function setAllowStaleConsults(bool _allow_stale_consults) external onlyByOwnerOrGovernance {
ALLOW_STALE_CONSULTS = _allow_stale_consults;
}
// Check if update() can be called instead of wasting gas calling it
function canUpdate() public view returns (bool) {
uint32 blockTimestamp = UniswapV2OracleLibrary.currentBlockTimestamp();
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired
return (timeElapsed >= PERIOD);
}
function update() external {
(uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) =
UniswapV2OracleLibrary.currentCumulativePrices(address(pair));
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired
// Ensure that at least one full period has passed since the last update
require(timeElapsed >= PERIOD, 'UniswapPairOracle: PERIOD_NOT_ELAPSED');
// Overflow is desired, casting never truncates
// Cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed
price0Average = FixedPoint.uq112x112(uint224((price0Cumulative - price0CumulativeLast) / timeElapsed));
price1Average = FixedPoint.uq112x112(uint224((price1Cumulative - price1CumulativeLast) / timeElapsed));
price0CumulativeLast = price0Cumulative;
price1CumulativeLast = price1Cumulative;
blockTimestampLast = blockTimestamp;
}
// Note this will always return 0 before update has been called successfully for the first time.
function consult(address token, uint amountIn) external view returns (uint amountOut) {
uint32 blockTimestamp = UniswapV2OracleLibrary.currentBlockTimestamp();
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired
// Ensure that the price is not stale
require((timeElapsed < (PERIOD + CONSULT_LENIENCY)) || ALLOW_STALE_CONSULTS, 'UniswapPairOracle: PRICE_IS_STALE_NEED_TO_CALL_UPDATE');
if (token == token0) {
amountOut = price0Average.mul(amountIn).decode144();
} else {
require(token == token1, 'UniswapPairOracle: INVALID_TOKEN');
amountOut = price1Average.mul(amountIn).decode144();
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "./AggregatorV3Interface.sol";
contract ChainlinkETHUSDPriceConsumer {
AggregatorV3Interface internal priceFeed;
constructor() public {
priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);
}
/**
* Returns the latest price
*/
function getLatestPrice() public view returns (int) {
(
,
int price,
,
,
) = priceFeed.latestRoundData();
return price;
}
function getDecimals() public view returns (uint8) {
return priceFeed.decimals();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../Utils/EnumerableSet.sol";
import "../Utils/Address.sol";
import "../Common/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; //bytes32(uint256(0x4B437D01b575618140442A4975db38850e3f8f5f) << 96);
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../Math/SafeMath.sol";
library FraxPoolLibrary {
using SafeMath for uint256;
// Constants for various precisions
uint256 private constant PRICE_PRECISION = 1e6;
// ================ Structs ================
// Needed to lower stack size
struct MintFF_Params {
uint256 fxs_price_usd;
uint256 col_price_usd;
uint256 fxs_amount;
uint256 collateral_amount;
uint256 col_ratio;
}
struct BuybackFXS_Params {
uint256 excess_collateral_dollar_value_d18;
uint256 fxs_price_usd;
uint256 col_price_usd;
uint256 FXS_amount;
}
// ================ Functions ================
function calcMint1t1FRAX(uint256 col_price, uint256 collateral_amount_d18) public pure returns (uint256) {
return (collateral_amount_d18.mul(col_price)).div(1e6);
}
function calcMintAlgorithmicFRAX(uint256 fxs_price_usd, uint256 fxs_amount_d18) public pure returns (uint256) {
return fxs_amount_d18.mul(fxs_price_usd).div(1e6);
}
// Must be internal because of the struct
function calcMintFractionalFRAX(MintFF_Params memory params) internal pure returns (uint256, uint256) {
// Since solidity truncates division, every division operation must be the last operation in the equation to ensure minimum error
// The contract must check the proper ratio was sent to mint FRAX. We do this by seeing the minimum mintable FRAX based on each amount
uint256 fxs_dollar_value_d18;
uint256 c_dollar_value_d18;
// Scoping for stack concerns
{
// USD amounts of the collateral and the FXS
fxs_dollar_value_d18 = params.fxs_amount.mul(params.fxs_price_usd).div(1e6);
c_dollar_value_d18 = params.collateral_amount.mul(params.col_price_usd).div(1e6);
}
uint calculated_fxs_dollar_value_d18 =
(c_dollar_value_d18.mul(1e6).div(params.col_ratio))
.sub(c_dollar_value_d18);
uint calculated_fxs_needed = calculated_fxs_dollar_value_d18.mul(1e6).div(params.fxs_price_usd);
return (
c_dollar_value_d18.add(calculated_fxs_dollar_value_d18),
calculated_fxs_needed
);
}
function calcRedeem1t1FRAX(uint256 col_price_usd, uint256 FRAX_amount) public pure returns (uint256) {
return FRAX_amount.mul(1e6).div(col_price_usd);
}
// Must be internal because of the struct
function calcBuyBackFXS(BuybackFXS_Params memory params) internal pure returns (uint256) {
// If the total collateral value is higher than the amount required at the current collateral ratio then buy back up to the possible FXS with the desired collateral
require(params.excess_collateral_dollar_value_d18 > 0, "No excess collateral to buy back!");
// Make sure not to take more than is available
uint256 fxs_dollar_value_d18 = params.FXS_amount.mul(params.fxs_price_usd).div(1e6);
require(fxs_dollar_value_d18 <= params.excess_collateral_dollar_value_d18, "You are trying to buy back more than the excess!");
// Get the equivalent amount of collateral based on the market value of FXS provided
uint256 collateral_equivalent_d18 = fxs_dollar_value_d18.mul(1e6).div(params.col_price_usd);
//collateral_equivalent_d18 = collateral_equivalent_d18.sub((collateral_equivalent_d18.mul(params.buyback_fee)).div(1e6));
return (
collateral_equivalent_d18
);
}
// Returns value of collateral that must increase to reach recollateralization target (if 0 means no recollateralization)
function recollateralizeAmount(uint256 total_supply, uint256 global_collateral_ratio, uint256 global_collat_value) public pure returns (uint256) {
uint256 target_collat_value = total_supply.mul(global_collateral_ratio).div(1e6); // We want 18 decimals of precision so divide by 1e6; total_supply is 1e18 and global_collateral_ratio is 1e6
// Subtract the current value of collateral from the target value needed, if higher than 0 then system needs to recollateralize
return target_collat_value.sub(global_collat_value); // If recollateralization is not needed, throws a subtraction underflow
// return(recollateralization_left);
}
function calcRecollateralizeFRAXInner(
uint256 collateral_amount,
uint256 col_price,
uint256 global_collat_value,
uint256 frax_total_supply,
uint256 global_collateral_ratio
) public pure returns (uint256, uint256) {
uint256 collat_value_attempted = collateral_amount.mul(col_price).div(1e6);
uint256 effective_collateral_ratio = global_collat_value.mul(1e6).div(frax_total_supply); //returns it in 1e6
uint256 recollat_possible = (global_collateral_ratio.mul(frax_total_supply).sub(frax_total_supply.mul(effective_collateral_ratio))).div(1e6);
uint256 amount_to_recollat;
if(collat_value_attempted <= recollat_possible){
amount_to_recollat = collat_value_attempted;
} else {
amount_to_recollat = recollat_possible;
}
return (amount_to_recollat.mul(1e6).div(col_price), amount_to_recollat);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.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.0.0, only sets of type `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];
}
// 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(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(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(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(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.6.11;
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;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
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;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import './Babylonian.sol';
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
library FixedPoint {
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
struct uq112x112 {
uint224 _x;
}
// range: [0, 2**144 - 1]
// resolution: 1 / 2**112
struct uq144x112 {
uint _x;
}
uint8 private constant RESOLUTION = 112;
uint private constant Q112 = uint(1) << RESOLUTION;
uint private constant Q224 = Q112 << RESOLUTION;
// encode a uint112 as a UQ112x112
function encode(uint112 x) internal pure returns (uq112x112 memory) {
return uq112x112(uint224(x) << RESOLUTION);
}
// encodes a uint144 as a UQ144x112
function encode144(uint144 x) internal pure returns (uq144x112 memory) {
return uq144x112(uint256(x) << RESOLUTION);
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) {
require(x != 0, 'FixedPoint: DIV_BY_ZERO');
return uq112x112(self._x / uint224(x));
}
// multiply a UQ112x112 by a uint, returning a UQ144x112
// reverts on overflow
function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) {
uint z;
require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW");
return uq144x112(z);
}
// returns a UQ112x112 which represents the ratio of the numerator to the denominator
// equivalent to encode(numerator).div(denominator)
function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, "FixedPoint: DIV_BY_ZERO");
return uq112x112((uint224(numerator) << RESOLUTION) / denominator);
}
// decode a UQ112x112 into a uint112 by truncating after the radix point
function decode(uq112x112 memory self) internal pure returns (uint112) {
return uint112(self._x >> RESOLUTION);
}
// decode a UQ144x112 into a uint144 by truncating after the radix point
function decode144(uq144x112 memory self) internal pure returns (uint144) {
return uint144(self._x >> RESOLUTION);
}
// take the reciprocal of a UQ112x112
function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) {
require(self._x != 0, 'FixedPoint: ZERO_RECIPROCAL');
return uq112x112(uint224(Q224 / self._x));
}
// square root of a UQ112x112
function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) {
return uq112x112(uint224(Babylonian.sqrt(uint256(self._x)) << 56));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import '../Uniswap/Interfaces/IUniswapV2Pair.sol';
import '../Math/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: MIT
pragma solidity 0.6.11;
import './Interfaces/IUniswapV2Pair.sol';
import './Interfaces/IUniswapV2Factory.sol';
import "../Math/SafeMath.sol";
library UniswapV2Library {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}
// Less efficient than the CREATE2 method below
function pairFor(address factory, address tokenA, address tokenB) internal view returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = IUniswapV2Factory(factory).getPair(token0, token1);
}
// calculates the CREATE2 address for a pair without making any external calls
function pairForCreate2(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
)))); // this matches the CREATE2 in UniswapV2Factory.createPair
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
// computes square roots using the babylonian method
// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
library Babylonian {
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
// else z = 0
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
|
Retrieve CRV gauge rewards, if any
|
function collectCRVFromGauge() external onlyByOwnerOrGovernance {
gauge_frax3crv.claim_rewards(address(this));
IMinter(gauge_frax3crv.minter()).mint(gauge_frax3crv_address);
}
| 14,527,872
|
// COPIED FROM https://github.com/compound-finance/compound-protocol/blob/master/contracts/Comptroller.sol
//Copyright 2020 Compound Labs, Inc.
//Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
//3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./ComptrollerStorage.sol";
import "./IComptroller.sol";
import "../libs/ErrorReporter.sol";
import "../libs/Exponential.sol";
import "../token/IPToken.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "../farm/PiggyDistribution.sol";
//PIGGY-MODIFY: Modified some methods and fields according to WePiggy's business logic
contract Comptroller is ComptrollerStorage, IComptroller, ComptrollerErrorReporter, Exponential, OwnableUpgradeable {
// @notice Emitted when an admin supports a market
event MarketListed(IPToken pToken);
// @notice Emitted when an account enters a market
event MarketEntered(IPToken pToken, address account);
// @notice Emitted when an account exits a market
event MarketExited(IPToken pToken, address account);
// @notice Emitted when close factor is changed by admin
event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa);
// @notice Emitted when a collateral factor is changed by admin
event NewCollateralFactor(IPToken pToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);
// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa);
// @notice Emitted when maxAssets is changed by admin
event NewMaxAssets(uint oldMaxAssets, uint newMaxAssets);
// @notice Emitted when price oracle is changed
event NewPriceOracle(IPriceOracle oldPriceOracle, IPriceOracle newPriceOracle);
// @notice Emitted when an action is paused globally
event ActionPaused(string action, bool pauseState);
// @notice Emitted when an action is paused on a market
event ActionPaused(IPToken pToken, string action, bool pauseState);
/// @notice Emitted when borrow cap for a pToken is changed
event NewBorrowCap(IPToken indexed pToken, uint newBorrowCap);
event NewPiggyDistribution(IPiggyDistribution oldPiggyDistribution, IPiggyDistribution newPiggyDistribution);
/// @notice Emitted when mint cap for a pToken is changed
event NewMintCap(IPToken indexed pToken, uint newMintCap);
// closeFactorMantissa must be strictly greater than this value
uint internal constant closeFactorMinMantissa = 0.05e18;
// closeFactorMantissa must not exceed this value
uint internal constant closeFactorMaxMantissa = 0.9e18;
// No collateralFactorMantissa may exceed this value
uint internal constant collateralFactorMaxMantissa = 0.9e18;
// liquidationIncentiveMantissa must be no less than this value
uint internal constant liquidationIncentiveMinMantissa = 1.0e18;
// liquidationIncentiveMantissa must be no greater than this value
uint internal constant liquidationIncentiveMaxMantissa = 1.5e18;
// for distribute wpc
IPiggyDistribution public piggyDistribution;
mapping(address => uint256) public mintCaps;
function initialize() public initializer {
//setting the msg.sender as the initial owner.
super.__Ownable_init();
}
/*** Assets You Are In ***/
function enterMarkets(address[] memory pTokens) public override(IComptroller) returns (uint[] memory) {
uint len = pTokens.length;
uint[] memory results = new uint[](len);
for (uint i = 0; i < len; i++) {
IPToken pToken = IPToken(pTokens[i]);
results[i] = uint(addToMarketInternal(pToken, msg.sender));
}
return results;
}
/**
* @notice Add the market to the borrower's "assets in" for liquidity calculations
* @param pToken The market to enter
* @param borrower The address of the account to modify
* @return Success indicator for whether the market was entered
*/
function addToMarketInternal(IPToken pToken, address borrower) internal returns (Error) {
Market storage marketToJoin = markets[address(pToken)];
// market is not listed, cannot join
if (!marketToJoin.isListed) {
return Error.MARKET_NOT_LISTED;
}
// already joined
if (marketToJoin.accountMembership[borrower] == true) {
return Error.NO_ERROR;
}
// no space, cannot join
if (accountAssets[borrower].length >= maxAssets) {
return Error.TOO_MANY_ASSETS;
}
marketToJoin.accountMembership[borrower] = true;
accountAssets[borrower].push(pToken);
emit MarketEntered(pToken, borrower);
return Error.NO_ERROR;
}
function exitMarket(address pTokenAddress) external override(IComptroller) returns (uint) {
IPToken pToken = IPToken(pTokenAddress);
// Get sender tokensHeld and amountOwed underlying from the pToken
(uint oErr, uint tokensHeld, uint amountOwed,) = pToken.getAccountSnapshot(msg.sender);
require(oErr == 0, "exitMarket: getAccountSnapshot failed");
// Fail if the sender has a borrow balance
if (amountOwed != 0) {
return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED);
}
// Fail if the sender is not permitted to redeem all of their tokens
uint allowed = redeemAllowedInternal(pTokenAddress, msg.sender, tokensHeld);
if (allowed != 0) {
return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);
}
Market storage marketToExit = markets[address(pToken)];
// Return true if the sender is not already ‘in’ the market
if (!marketToExit.accountMembership[msg.sender]) {
return uint(Error.NO_ERROR);
}
// Set pToken account membership to false
delete marketToExit.accountMembership[msg.sender];
// Delete pToken from the account’s list of assets
// load into memory for faster iteration
IPToken[] memory userAssetList = accountAssets[msg.sender];
uint len = userAssetList.length;
uint assetIndex = len;
for (uint i = 0; i < len; i++) {
if (userAssetList[i] == pToken) {
assetIndex = i;
break;
}
}
// We *must* have found the asset in the list or our redundant data structure is broken
assert(assetIndex < len);
// copy last item in list to location of item to be removed, reduce length by 1
IPToken[] storage storedList = accountAssets[msg.sender];
storedList[assetIndex] = storedList[storedList.length - 1];
storedList.pop();
emit MarketExited(pToken, msg.sender);
return uint(Error.NO_ERROR);
}
/**
* @notice Returns the assets an account has entered
* @param account The address of the account to pull assets for
* @return A dynamic list with the assets the account has entered
*/
function getAssetsIn(address account) external view returns (IPToken[] memory) {
IPToken[] memory assetsIn = accountAssets[account];
return assetsIn;
}
/**
* @notice Returns whether the given account is entered in the given asset
* @param account The address of the account to check
* @param pToken The pToken to check
* @return True if the account is in the asset, otherwise false.
*/
function checkMembership(address account, IPToken pToken) external view returns (bool) {
return markets[address(pToken)].accountMembership[account];
}
/*** Policy Hooks ***/
function mintAllowed(address pToken, address minter, uint mintAmount) external override(IComptroller) returns (uint){
// Pausing is a very serious situation - we revert to sound the alarms
require(!pTokenMintGuardianPaused[pToken], "mint is paused");
//Shh - currently unused. It's written here to eliminate compile-time alarms.
minter;
mintAmount;
if (!markets[pToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
uint mintCap = mintCaps[pToken];
if (mintCap != 0) {
uint totalSupply = IPToken(pToken).totalSupply();
uint exchangeRate = IPToken(pToken).exchangeRateStored();
(MathError mErr, uint balance) = mulScalarTruncate(Exp({mantissa : exchangeRate}), totalSupply);
require(mErr == MathError.NO_ERROR, "balance could not be calculated");
(MathError mathErr, uint nextTotalMints) = addUInt(balance, mintAmount);
require(mathErr == MathError.NO_ERROR, "total mint amount overflow");
require(nextTotalMints < mintCap, "market mint cap reached");
}
if (distributeWpcPaused == false) {
piggyDistribution.distributeMintWpc(pToken, minter, false);
}
return uint(Error.NO_ERROR);
}
function mintVerify(address pToken, address minter, uint mintAmount, uint mintTokens) external override(IComptroller) {
//Shh - currently unused. It's written here to eliminate compile-time alarms.
pToken;
minter;
mintAmount;
mintTokens;
}
function redeemAllowed(address pToken, address redeemer, uint redeemTokens) external override(IComptroller) returns (uint){
uint allowed = redeemAllowedInternal(pToken, redeemer, redeemTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
if (distributeWpcPaused == false) {
piggyDistribution.distributeRedeemWpc(pToken, redeemer, false);
}
return uint(Error.NO_ERROR);
}
/**
* PIGGY-MODIFY:
* @notice Checks if the account should be allowed to redeem tokens in the given market
* @param pToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of pTokens to exchange for the underlying asset in the market
* @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function redeemAllowedInternal(address pToken, address redeemer, uint redeemTokens) internal view returns (uint) {
if (!markets[pToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
if (!markets[pToken].accountMembership[redeemer]) {
return uint(Error.NO_ERROR);
}
/* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, IPToken(pToken), redeemTokens, 0);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
return uint(Error.NO_ERROR);
}
function redeemVerify(address pToken, address redeemer, uint redeemAmount, uint redeemTokens) external override(IComptroller) {
//Shh - currently unused. It's written here to eliminate compile-time alarms.
pToken;
redeemer;
redeemAmount;
redeemTokens;
}
function borrowAllowed(address pToken, address borrower, uint borrowAmount) external override(IComptroller) returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!pTokenBorrowGuardianPaused[pToken], "borrow is paused");
if (!markets[pToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (!markets[pToken].accountMembership[borrower]) {
// only pTokens may call borrowAllowed if borrower not in market
require(msg.sender == pToken, "sender must be pToken");
// attempt to add borrower to the market
Error err = addToMarketInternal(IPToken(msg.sender), borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
// it should be impossible to break the important invariant
assert(markets[pToken].accountMembership[borrower]);
}
if (oracle.getUnderlyingPrice(IPToken(pToken)) == 0) {
return uint(Error.PRICE_ERROR);
}
uint borrowCap = borrowCaps[pToken];
// Borrow cap of 0 corresponds to unlimited borrowing
if (borrowCap != 0) {
uint totalBorrows = IPToken(pToken).totalBorrows();
(MathError mathErr, uint nextTotalBorrows) = addUInt(totalBorrows, borrowAmount);
require(mathErr == MathError.NO_ERROR, "total borrows overflow");
require(nextTotalBorrows < borrowCap, "market borrow cap reached");
}
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, IPToken(pToken), 0, borrowAmount);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
//distribute wpc
if (distributeWpcPaused == false) {
piggyDistribution.distributeBorrowWpc(pToken, borrower, false);
}
return uint(Error.NO_ERROR);
}
function borrowVerify(address pToken, address borrower, uint borrowAmount) external override(IComptroller) {
//Shh - currently unused. It's written here to eliminate compile-time alarms.
pToken;
borrower;
borrowAmount;
}
function repayBorrowAllowed(address pToken, address payer, address borrower, uint repayAmount) external override(IComptroller) returns (uint) {
if (!markets[pToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Shh - currently unused. It's written here to eliminate compile-time alarms.
payer;
borrower;
repayAmount;
//distribute wpc
if (distributeWpcPaused == false) {
piggyDistribution.distributeRepayBorrowWpc(pToken, borrower, false);
}
return uint(Error.NO_ERROR);
}
function repayBorrowVerify(address pToken, address payer, address borrower, uint repayAmount, uint borrowerIndex) external override(IComptroller) {
// Shh - currently unused. It's written here to eliminate compile-time alarms.
pToken;
payer;
borrower;
repayAmount;
borrowerIndex;
}
function liquidateBorrowAllowed(
address pTokenBorrowed,
address pTokenCollateral,
address liquidator,
address borrower,
uint repayAmount
) external override(IComptroller) returns (uint){
// Shh - currently unused. It's written here to eliminate compile-time alarms.
liquidator;
if (!markets[pTokenBorrowed].isListed || !markets[pTokenCollateral].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* The borrower must have shortfall in order to be liquidatable */
(Error err, , uint shortfall) = getAccountLiquidityInternal(borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall == 0) {
return uint(Error.INSUFFICIENT_SHORTFALL);
}
/* The liquidator may not repay more than what is allowed by the closeFactor */
uint borrowBalance = IPToken(pTokenBorrowed).borrowBalanceStored(borrower);
(MathError mathErr, uint maxClose) = mulScalarTruncate(Exp({mantissa : closeFactorMantissa}), borrowBalance);
if (mathErr != MathError.NO_ERROR) {
return uint(Error.MATH_ERROR);
}
if (repayAmount > maxClose) {
return uint(Error.TOO_MUCH_REPAY);
}
return uint(Error.NO_ERROR);
}
function liquidateBorrowVerify(
address pTokenBorrowed,
address pTokenCollateral,
address liquidator,
address borrower,
uint repayAmount,
uint seizeTokens
) external override(IComptroller) {
// Shh - currently unused. It's written here to eliminate compile-time alarms.
pTokenBorrowed;
pTokenCollateral;
liquidator;
borrower;
repayAmount;
seizeTokens;
}
function seizeAllowed(
address pTokenCollateral,
address pTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens
) external override(IComptroller) returns (uint){
// Pausing is a very serious situation - we revert to sound the alarms
require(!seizeGuardianPaused, "seize is paused");
// Shh - currently unused. It's written here to eliminate compile-time alarms.
seizeTokens;
if (!markets[pTokenCollateral].isListed || !markets[pTokenBorrowed].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (IPToken(pTokenCollateral).comptroller() != IPToken(pTokenBorrowed).comptroller()) {
return uint(Error.COMPTROLLER_MISMATCH);
}
//distribute wpc
if (distributeWpcPaused == false) {
piggyDistribution.distributeSeizeWpc(pTokenCollateral, borrower, liquidator, false);
}
return uint(Error.NO_ERROR);
}
function seizeVerify(
address pTokenCollateral,
address pTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens
) external override(IComptroller) {
// Shh - currently unused. It's written here to eliminate compile-time alarms.
pTokenCollateral;
pTokenBorrowed;
liquidator;
borrower;
seizeTokens;
}
function transferAllowed(
address pToken,
address src,
address dst,
uint transferTokens
) external override(IComptroller) returns (uint){
// Pausing is a very serious situation - we revert to sound the alarms
require(!transferGuardianPaused, "transfer is paused");
// Currently the only consideration is whether or not
// the src is allowed to redeem this many tokens
uint allowed = redeemAllowedInternal(pToken, src, transferTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
//distribute wpc
if (distributeWpcPaused == false) {
piggyDistribution.distributeTransferWpc(pToken, src, dst, false);
}
return uint(Error.NO_ERROR);
}
function transferVerify(
address pToken,
address src,
address dst,
uint transferTokens
) external override(IComptroller) {
// Shh - currently unused. It's written here to eliminate compile-time alarms.
pToken;
src;
dst;
transferTokens;
}
/*** Liquidity/Liquidation Calculations ***/
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `pTokenBalance` is the number of pTokens the account owns in the market,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
*/
struct AccountLiquidityLocalVars {
uint sumCollateral;
uint sumBorrowPlusEffects;
uint pTokenBalance;
uint borrowBalance;
uint exchangeRateMantissa;
uint oraclePriceMantissa;
Exp collateralFactor;
Exp exchangeRate;
Exp oraclePrice;
Exp tokensToDenom;
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code (semi-opaque),
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidity(address account) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, IPToken(0), 0, 0);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code,
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) {
return getHypotheticalAccountLiquidityInternal(account, IPToken(0), 0, 0);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param pTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @return (possible error code (semi-opaque),
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidity(
address account,
address pTokenModify,
uint redeemTokens,
uint borrowAmount) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, IPToken(pTokenModify), redeemTokens, borrowAmount);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param account The account to determine liquidity for
* @param pTokenModify The market to hypothetically redeem/borrow in
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @dev Note that we calculate the exchangeRateStored for each collateral pToken using stored data,
* without calculating accumulated interest.
* @return (possible error code,
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidityInternal(
address account,
IPToken pTokenModify,
uint redeemTokens,
uint borrowAmount) internal view returns (Error, uint, uint) {
AccountLiquidityLocalVars memory vars;
uint oErr;
MathError mErr;
// For each asset the account is in
IPToken[] memory assets = accountAssets[account];
for (uint i = 0; i < assets.length; i++) {
IPToken asset = assets[i];
// Read the balances and exchange rate from the pToken
(oErr, vars.pTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account);
if (oErr != 0) {// semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades
return (Error.SNAPSHOT_ERROR, 0, 0);
}
vars.collateralFactor = Exp({mantissa : markets[address(asset)].collateralFactorMantissa});
vars.exchangeRate = Exp({mantissa : vars.exchangeRateMantissa});
// Get the normalized price of the asset
vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset);
if (vars.oraclePriceMantissa == 0) {
return (Error.PRICE_ERROR, 0, 0);
}
vars.oraclePrice = Exp({mantissa : vars.oraclePriceMantissa});
// Pre-compute a conversion factor from tokens -> usd (normalized price value)
// pTokenPrice = oraclePrice * exchangeRate
(mErr, vars.tokensToDenom) = mulExp3(vars.collateralFactor, vars.exchangeRate, vars.oraclePrice);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// sumCollateral += tokensToDenom * pTokenBalance
(mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.pTokenBalance, vars.sumCollateral);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// sumBorrowPlusEffects += oraclePrice * borrowBalance
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// Calculate effects of interacting with pTokenModify
if (asset == pTokenModify) {
// redeem effect
// sumBorrowPlusEffects += tokensToDenom * redeemTokens
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// borrow effect
// sumBorrowPlusEffects += oraclePrice * borrowAmount
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
}
}
// These are safe, as the underflow condition is checked first
if (vars.sumCollateral > vars.sumBorrowPlusEffects) {
return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0);
} else {
return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral);
}
}
function liquidateCalculateSeizeTokens(
address pTokenBorrowed,
address pTokenCollateral,
uint actualRepayAmount
) external override(IComptroller) view returns (uint, uint) {
/* Read oracle prices for borrowed and collateral markets */
uint priceBorrowedMantissa = oracle.getUnderlyingPrice(IPToken(pTokenBorrowed));
uint priceCollateralMantissa = oracle.getUnderlyingPrice(IPToken(pTokenCollateral));
if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) {
return (uint(Error.PRICE_ERROR), 0);
}
/*
* Get the exchange rate and calculate the number of collateral tokens to seize:
* seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral
* seizeTokens = seizeAmount / exchangeRate
* = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate)
*
* Note: reverts on error
*/
uint exchangeRateMantissa = IPToken(pTokenCollateral).exchangeRateStored();
uint seizeTokens;
Exp memory numerator;
Exp memory denominator;
Exp memory ratio;
MathError mathErr;
(mathErr, numerator) = mulExp(liquidationIncentiveMantissa, priceBorrowedMantissa);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, denominator) = mulExp(priceCollateralMantissa, exchangeRateMantissa);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, ratio) = divExp(numerator, denominator);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, seizeTokens) = mulScalarTruncate(ratio, actualRepayAmount);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
return (uint(Error.NO_ERROR), seizeTokens);
}
/*** Admin Functions ***/
/**
* @notice Sets a new price oracle for the comptroller
* @dev Admin function to set a new price oracle
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPriceOracle(IPriceOracle newOracle) public onlyOwner returns (uint) {
IPriceOracle oldOracle = oracle;
oracle = newOracle;
emit NewPriceOracle(oldOracle, newOracle);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the closeFactor used when liquidating borrows
* @dev Admin function to set closeFactor
* @param newCloseFactorMantissa New close factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCloseFactor(uint newCloseFactorMantissa) external onlyOwner returns (uint) {
Exp memory newCloseFactorExp = Exp({mantissa : newCloseFactorMantissa});
Exp memory lowLimit = Exp({mantissa : closeFactorMinMantissa});
if (lessThanOrEqualExp(newCloseFactorExp, lowLimit)) {
return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION);
}
Exp memory highLimit = Exp({mantissa : closeFactorMaxMantissa});
if (lessThanExp(highLimit, newCloseFactorExp)) {
return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION);
}
uint oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = newCloseFactorMantissa;
emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the collateralFactor for a market
* @dev Admin function to set per-market collateralFactor
* @param pToken The market to set the factor on
* @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCollateralFactor(IPToken pToken, uint newCollateralFactorMantissa) external onlyOwner returns (uint) {
Market storage market = markets[address(pToken)];
if (!market.isListed) {
return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS);
}
Exp memory newCollateralFactorExp = Exp({mantissa : newCollateralFactorMantissa});
Exp memory highLimit = Exp({mantissa : collateralFactorMaxMantissa});
if (lessThanExp(highLimit, newCollateralFactorExp)) {
return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION);
}
if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(pToken) == 0) {
return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);
}
uint oldCollateralFactorMantissa = market.collateralFactorMantissa;
market.collateralFactorMantissa = newCollateralFactorMantissa;
emit NewCollateralFactor(pToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets maxAssets which controls how many markets can be entered
* @dev Admin function to set maxAssets
* @param newMaxAssets New max assets
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setMaxAssets(uint newMaxAssets) external onlyOwner returns (uint) {
uint oldMaxAssets = maxAssets;
maxAssets = newMaxAssets;
emit NewMaxAssets(oldMaxAssets, newMaxAssets);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets liquidationIncentive
* @dev Admin function to set liquidationIncentive
* @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external onlyOwner returns (uint) {
// Check de-scaled min <= newLiquidationIncentive <= max
Exp memory newLiquidationIncentive = Exp({mantissa : newLiquidationIncentiveMantissa});
Exp memory minLiquidationIncentive = Exp({mantissa : liquidationIncentiveMinMantissa});
if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) {
return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);
}
Exp memory maxLiquidationIncentive = Exp({mantissa : liquidationIncentiveMaxMantissa});
if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) {
return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);
}
uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Add the market to the markets mapping and set it as listed
* @dev Admin function to set isListed and add support for the market
* @param pToken The address of the market (token) to list
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _supportMarket(IPToken pToken) external onlyOwner returns (uint) {
if (markets[address(pToken)].isListed) {
return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS);
}
markets[address(pToken)] = Market({isListed : true, isMinted : false, collateralFactorMantissa : 0});
_addMarketInternal(address(pToken));
emit MarketListed(pToken);
return uint(Error.NO_ERROR);
}
function _addMarketInternal(address pToken) internal onlyOwner {
for (uint i = 0; i < allMarkets.length; i ++) {
require(allMarkets[i] != IPToken(pToken), "market already added");
}
allMarkets.push(IPToken(pToken));
}
/**
* @notice Set the given borrow caps for the given pToken markets. Borrowing that brings total borrows to or above borrow cap will revert.
* @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing.
* @param pTokens The addresses of the markets (tokens) to change the borrow caps for
* @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing.
*/
function _setMarketBorrowCaps(IPToken[] calldata pTokens, uint[] calldata newBorrowCaps) external {
require(msg.sender == owner(), "only owner can set borrow caps");
uint numMarkets = pTokens.length;
uint numBorrowCaps = newBorrowCaps.length;
for (uint i = 0; i < numMarkets; i++) {
borrowCaps[address(pTokens[i])] = newBorrowCaps[i];
emit NewBorrowCap(pTokens[i], newBorrowCaps[i]);
}
}
function _setMintPaused(IPToken pToken, bool state) public onlyOwner returns (bool) {
require(markets[address(pToken)].isListed, "cannot pause a market that is not listed");
pTokenMintGuardianPaused[address(pToken)] = state;
emit ActionPaused(pToken, "Mint", state);
return state;
}
function _setBorrowPaused(IPToken pToken, bool state) public onlyOwner returns (bool) {
require(markets[address(pToken)].isListed, "cannot pause a market that is not listed");
pTokenBorrowGuardianPaused[address(pToken)] = state;
emit ActionPaused(pToken, "Borrow", state);
return state;
}
function _setTransferPaused(bool state) public onlyOwner returns (bool) {
transferGuardianPaused = state;
emit ActionPaused("Transfer", state);
return state;
}
function _setSeizePaused(bool state) public onlyOwner returns (bool) {
seizeGuardianPaused = state;
emit ActionPaused("Seize", state);
return state;
}
function _setDistributeWpcPaused(bool state) public onlyOwner returns (bool) {
distributeWpcPaused = state;
emit ActionPaused("DistributeWpc", state);
return state;
}
/**
* @notice Sets a new price piggyDistribution for the comptroller
* @dev Admin function to set a new piggy distribution
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPiggyDistribution(IPiggyDistribution newPiggyDistribution) public onlyOwner returns (uint) {
IPiggyDistribution oldPiggyDistribution = piggyDistribution;
piggyDistribution = newPiggyDistribution;
emit NewPiggyDistribution(oldPiggyDistribution, newPiggyDistribution);
return uint(Error.NO_ERROR);
}
function getAllMarkets() public view returns (IPToken[] memory){
return allMarkets;
}
function isMarketMinted(address pToken) public view returns (bool){
return markets[pToken].isMinted;
}
function isMarketListed(address pToken) public view returns (bool){
return markets[pToken].isListed;
}
function _setMarketMinted(address pToken, bool status) public {
require(msg.sender == address(piggyDistribution) || msg.sender == owner(), "only PiggyDistribution or owner can update");
markets[pToken].isMinted = status;
}
function _setMarketMintCaps(IPToken[] calldata pTokens, uint[] calldata newMintCaps) external onlyOwner {
uint numMarkets = pTokens.length;
uint numMintCaps = newMintCaps.length;
for (uint i = 0; i < numMarkets; i++) {
mintCaps[address(pTokens[i])] = newMintCaps[i];
emit NewBorrowCap(pTokens[i], newMintCaps[i]);
}
}
}
|
Sets a new price piggyDistribution for the comptroller Admin function to set a new piggy distribution return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/
|
function _setPiggyDistribution(IPiggyDistribution newPiggyDistribution) public onlyOwner returns (uint) {
IPiggyDistribution oldPiggyDistribution = piggyDistribution;
piggyDistribution = newPiggyDistribution;
emit NewPiggyDistribution(oldPiggyDistribution, newPiggyDistribution);
return uint(Error.NO_ERROR);
}
| 5,421,827
|
// 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 {
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
// solhint-disable-next-line compiler-version
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 "./IERC1155Upgradeable.sol";
import "./IERC1155ReceiverUpgradeable.sol";
import "./extensions/IERC1155MetadataURIUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC1155Upgradeable, IERC1155MetadataURIUpgradeable {
using AddressUpgradeable for address;
// Mapping from token ID to account balances
mapping (uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping (address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
function __ERC1155_init(string memory uri_) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC1155_init_unchained(uri_);
}
function __ERC1155_init_unchained(string memory uri_) internal initializer {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return interfaceId == type(IERC1155Upgradeable).interfaceId
|| interfaceId == type(IERC1155MetadataURIUpgradeable).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(
address[] memory accounts,
uint256[] memory ids
)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(_msgSender() != operator, "ERC1155: setting approval status for self");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
public
virtual
override
{
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
_balances[id][from] = fromBalance - amount;
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
public
virtual
override
{
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
_balances[id][from] = fromBalance - amount;
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `account`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual {
require(account != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][account] += amount;
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `account`
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens of token type `id`.
*/
function _burn(address account, uint256 id, uint256 amount) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
_balances[id][account] = accountBalance - amount;
emit TransferSingle(operator, account, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
_balances[id][account] = accountBalance - amount;
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
internal
virtual
{ }
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155ReceiverUpgradeable(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155ReceiverUpgradeable(to).onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) {
if (response != IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
uint256[47] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155ReceiverUpgradeable is IERC165Upgradeable {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
)
external
returns(bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external
returns(bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC1155Upgradeable.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURIUpgradeable is IERC1155Upgradeable {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// 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.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) {
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
pragma solidity ^0.8.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;`
*/
library CountersUpgradeable {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
}
// 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 ECDSAUpgradeable {
/**
* @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) {
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// 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) {
// 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)))
}
} else if (signature.length == 64) {
// 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 {
let vs := mload(add(signature, 0x40))
r := mload(add(signature, 0x20))
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
} else {
revert("ECDSA: invalid signature length");
}
return recover(hash, v, r, s);
}
/**
* @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) {
// 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
* 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 "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.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 ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// 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 IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/token/ERC1155/ERC1155Upgradeable.sol';
import '@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol';
import '../Storage/CybertinoCanvasStorageV0.sol';
import '../Interface/ICybertinoCanvas.sol';
import '../Interface/ILayer.sol';
contract CybertinoCanvasV0 is
ERC1155Upgradeable,
OwnableUpgradeable,
ICybertinoCanvas,
InfluencerStorageV0
{
using ECDSAUpgradeable for bytes32;
using CountersUpgradeable for CountersUpgradeable.Counter;
function CybertinoCanvas_init(
string memory _name,
string memory _uri,
string memory _symbol,
address _signer,
address _owner
) public initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__Ownable_init_unchained();
__ERC1155_init_unchained(_uri);
CybertinoCanvas_init_unchained(_name, _symbol, _signer, _owner);
}
function CybertinoCanvas_init_unchained(
string memory _name,
string memory _symbol,
address _signer,
address _owner
) public initializer {
name = _name;
symbol = _symbol;
signer = _signer;
transferOwnership(_owner);
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC1155Upgradeable)
returns (bool)
{
return
interfaceId == type(ICybertinoCanvas).interfaceId ||
super.supportsInterface(interfaceId);
}
modifier pausable {
if (paused) {
revert('Paused');
} else {
_;
}
}
/**
* @dev Creates a new Canvas type
* @param _cid Content identifier
* param _data Data to pass if receiver is contract
* @return _id the newly created token ID
*/
function createCanvas(
string calldata _cid,
bytes calldata _data,
LayerToken[] calldata _tokens,
uint256 _maxSupply
) external onlyOwner returns (uint256 _id) {
require(bytes(_cid).length > 0, 'Err: Missing Content Identifier');
require(_tokens.length > 0, 'Err: Must have at least one layer');
_id = _nextId();
canvases[_id].id = _id;
canvases[_id].layerCount = _tokens.length;
for (uint256 i = 0; i < _tokens.length; i++) {
canvases[_id].layerTokens[i] = _tokens[i];
}
_mint(_msgSender(), _id, 0, _data);
idToUri[_id] = _cid;
maxTokenSupply[_id] = _maxSupply;
emit URI(uri(_id), _id);
}
/**
* @dev Mints an existing Canvas NFT
* @notice Enforces a maximum of 1 minting event per NFT type per account
* @param _to Account to mint NFT to (i.e. the owner)
* @param _id ID (i.e. type) of NFT to mint
* @param _amount number of NFTs of same type to mint
* @param _nonce platform nounce to prevent replay
* @param _signature Verified signature granting _account an NFT
* @param _data Data to pass if receiver is contract
*/
function mint(
address _to,
uint256 _id,
uint256 _amount,
uint256 _nonce,
bytes calldata _signature,
bytes calldata _data
) public pausable {
require(_exists(_id), 'CybertinoCanvas: invalid ID');
require(_amount >= 1, 'CybertinoCanvas: must mint at least one');
require(
tokenSupply[_id] + _amount <= maxTokenSupply[_id],
'CybertinoCanvas: exceeds max supply'
);
bytes32 messageHash = getMessageHash(_to, _id, _amount, _nonce);
require(!executed[messageHash], 'CybertinoCanvas: already minted');
require(
_verify(messageHash, _signature),
'CybertinoCanvas: invalid signature'
);
executed[messageHash] = true;
_mint(_to, _id, _amount, _data);
tokenSupply[_id] += _amount;
address operator = _msgSender();
emit CybertinoMint(operator, _to, _id, _amount, _nonce);
}
/**
* @dev Batch mints multiple different existing NFT types
* @notice Enforces a maximum of 1 minting event per account per NFT type
* @param _to Account to mint NFT to (i.e. the owner)
* @param _ids IDs of the type of NFT to mint
* @param _amounts numbers of NFTs of same type to mint
* @param _nonces platform nounces to prevent replay
* @param _signatures Verified signatures granting _account an NFT
* @param _data Data to pass if receiver is contract
*/
function batchMint(
address _to,
uint256[] calldata _ids,
uint256[] calldata _amounts,
uint256[] calldata _nonces,
bytes[] calldata _signatures,
bytes[] calldata _data
) external pausable {
for (uint256 i = 0; i < _ids.length; i++) {
mint(_to, _ids[i], _amounts[i], _nonces[i], _signatures[i], _data[i]);
}
}
/**
* @dev Sets a new URI for all token types
*/
function setURI(string memory _uri) public onlyOwner {
_setURI(_uri);
}
/**
* @dev Returns the uri of a token given its ID
* @param _id ID of the token to query
* @return uri of the token or an empty string if it does not exist
*/
function uri(uint256 _id) public view override returns (string memory) {
string memory baseUri = super.uri(0);
if (bytes(baseUri).length == 0) {
return '';
} else {
return string(abi.encodePacked(baseUri, idToUri[_id]));
}
}
/**
* @dev get Layer Token <address, id> pair, used to query token states
* with ILayer contracts
*/
function getLayerTokens(uint256 _id)
public
view
returns (ILayer[] memory, uint256[] memory)
{
Canvas storage canvas = canvases[_id];
ILayer[] memory layers = new ILayer[](canvas.layerCount);
uint256[] memory ids = new uint256[](canvas.layerCount);
for (uint256 i = 0; i < canvas.layerCount; i++) {
layers[i] = canvas.layerTokens[i].layer;
ids[i] = canvas.layerTokens[i].layerID;
}
return (layers, ids);
}
/**
* @dev Returns the total quantity for a token ID
* @param _id ID of the token to query
* @return amount of token in existence
*/
function totalSupply(uint256 _id) public view returns (uint256) {
return tokenSupply[_id];
}
/**
* @dev Returns the max quantity for a token ID
* @param _id ID of the token to query
* @return amount of token in existence
*/
function maxSupply(uint256 _id) public view returns (uint256) {
return maxTokenSupply[_id];
}
/**
* @dev Pause or unpause the minting and creation of NFTs
*/
function pause() public onlyOwner {
paused = !paused;
}
/**
* @dev Update the signer
*/
function updateSigner(address _signer) public onlyOwner {
signer = _signer;
}
/**
* @dev Create message hash to be signed
*/
function getMessageHash(
address _to,
uint256 _tokenId,
uint256 _amount,
uint256 _nonce
) public pure returns (bytes32) {
return keccak256(abi.encodePacked(_to, _tokenId, _amount, _nonce));
}
function _exists(uint256 _id) internal view returns (bool) {
return (bytes(idToUri[_id]).length > 0);
}
function _nextId() internal returns (uint256) {
id.increment();
return id.current();
}
function _verify(bytes32 messageHash, bytes memory signature)
internal
view
returns (bool)
{
bytes32 ethSignedMessageHash = messageHash.toEthSignedMessageHash();
return ethSignedMessageHash.recover(signature) == signer;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
interface ICybertinoCanvas {
/**
* @dev Slightly different from TransferSingle event, emitted when `value`
* tokens of token type `id` are minted to `to` by `operator` with platform's
* nonce `nonce`.
*/
event CybertinoMint(
address indexed operator,
address indexed to,
uint256 id,
uint256 value,
uint256 indexed nonce
);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
interface ILayer {
function getLayer(uint256 id)
external
view
returns (uint32 stateCount, uint32 currenctState);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import "../Interface/ILayer.sol";
import '@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol';
// Storage is append only and never to be modified
// To upgrade:
//
// contract InfluencerStorageV1 is InfluencerStorageV0 {...}
// contract InfluencerV1 is InfluencerStorageV1 ... {...}
contract InfluencerStorageV0 {
/**
* @dev influencer name
*/
string public name;
/**
* @dev collection symbol; token tracker symbol
*/
string public symbol;
/**
* @dev The current id of NFTs. Auto increment.
*/
CountersUpgradeable.Counter public id;
/**
* @dev LayerToken stores layer contract address and layer token id
*/
struct LayerToken {
// layer contract address
ILayer layer;
// layer token id
uint256 layerID;
}
/**
* Canvas consists of 1 or more layers
*/
struct Canvas {
// canvas id
uint256 id;
// The total number of layers
uint256 layerCount;
// all layer tokens
mapping(uint256 => LayerToken) layerTokens;
}
/**
* @dev tokenID to Canvas
*/
mapping(uint256 => Canvas) public canvases;
/**
* @dev Cybertino Platform signer
*/
address public signer;
// TODO: multiple mapping or mapping of struct
/**
* @dev Mapping from token ID to token URI, excluding base uri
*/
mapping(uint256 => string) internal idToUri;
/**
* @dev Mapping from token ID to token max supply
*/
mapping(uint256 => uint256) internal maxTokenSupply;
/**
* @dev Mapping from token ID to token supply, how many minted
*/
mapping(uint256 => uint256) internal tokenSupply;
/**
* @dev Mapping from signature hash to boolean to prevent replay
*/
mapping(bytes32 => bool) public executed;
/**
* @dev Paused boolean is turned on in case of emergency.
*/
bool public paused = false;
}
|
Creates a new Canvas type _cid Content identifier param _data Data to pass if receiver is contract return _id the newly created token ID/
|
function createCanvas(
string calldata _cid,
bytes calldata _data,
LayerToken[] calldata _tokens,
uint256 _maxSupply
) external onlyOwner returns (uint256 _id) {
require(bytes(_cid).length > 0, 'Err: Missing Content Identifier');
require(_tokens.length > 0, 'Err: Must have at least one layer');
_id = _nextId();
canvases[_id].id = _id;
canvases[_id].layerCount = _tokens.length;
for (uint256 i = 0; i < _tokens.length; i++) {
canvases[_id].layerTokens[i] = _tokens[i];
}
_mint(_msgSender(), _id, 0, _data);
idToUri[_id] = _cid;
maxTokenSupply[_id] = _maxSupply;
emit URI(uri(_id), _id);
}
| 1,509,588
|
./partial_match/1/0x14132D979fDdA62a56d9f552C9aa477b9c94851e/sources/@yield-protocol/yieldspace-tv/src/Exp64x64.sol
|
Raises a 64.64 number to the power of another 64.64 number x^y = 2^(ylog_2(x)) https://ethereum.stackexchange.com/questions/79903/exponential-function-with-fractional-numbers
|
function pow(int128 x, int128 y) internal pure returns (int128) {
return y.mul(x.log_2()).exp_2();
}
| 15,663,159
|
./full_match/5/0x5dF6D53FA5D7f3C325D2b0E3109C55AbF2c289a5/sources/erc721a-upgradeable/contracts/ERC721AUpgradeable.sol
|
Destroys `tokenId`. The approval is cleared when the token is burned. Requirements: - `tokenId` must exist. Emits a {Transfer} event./ The nested ifs save around 20+ gas over a compound boolean condition. Clear approvals from the previous owner. This is equivalent to `delete _tokenApprovals[tokenId]`. Underflow of the sender's balance is impossible because we check for ownership above and the recipient's balance can't realistically overflow. Counter overflow is incredibly unrealistic as `tokenId` would have to be 2256. Updates: - `balance -= 1`. - `numberBurned += 1`. We can directly decrement the balance, and increment the number burned. This is equivalent to `packed -= 1; packed += 1 << _BITPOS_NUMBER_BURNED;`. Updates: - `address` to the last owner. - `startTimestamp` to the timestamp of burning. - `burned` to `true`. - `nextInitialized` to `true`. If the next slot may not have been initialized (i.e. `nextInitialized == false`) . If the next slot's address is zero and not burned (i.e. packed value is zero). If the next slot is within bounds. Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`. Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
|
function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
address from = address(uint160(prevOwnershipPacked));
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);
if (approvalCheck) {
if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
assembly {
if approvedAddress {
sstore(approvedAddressSlot, 0)
}
}
unchecked {
ERC721AStorage.layout()._packedAddressData[from] += (1 << _BITPOS_NUMBER_BURNED) - 1;
ERC721AStorage.layout()._packedOwnerships[tokenId] = _packOwnershipData(
from,
(_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked)
);
if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
if (ERC721AStorage.layout()._packedOwnerships[nextTokenId] == 0) {
if (nextTokenId != ERC721AStorage.layout()._currentIndex) {
ERC721AStorage.layout()._packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, address(0), tokenId, 1);
unchecked {
ERC721AStorage.layout()._burnCounter++;
}
}
| 1,927,416
|
pragma solidity ^0.4.18;
/*
The Polymath Security Token Registrar provides a way to lookup security token details
from a single place and allows wizard creators to earn POLY fees by uploading to the
registrar.
*/
import './interfaces/ISecurityTokenRegistrar.sol';
import './interfaces/IERC20.sol';
import './SecurityToken.sol';
/**
* @title SecurityTokenRegistrar
* @dev Contract use to register the security token on Polymath platform
*/
contract SecurityTokenRegistrar is ISecurityTokenRegistrar {
string public VERSION = "2";
IERC20 public PolyToken; // Address of POLY token
address public polyCustomersAddress; // Address of the polymath-core Customers contract address
address public polyComplianceAddress; // Address of the polymath-core Compliance contract address
struct NameSpaceData {
address owner;
uint256 fee;
}
// Security Token
struct SecurityTokenData { // A structure that contains the specific info of each ST
string nameSpace;
string ticker;
address owner;
uint8 securityType;
}
mapping (string => NameSpaceData) nameSpaceData; // Mapping from nameSpace to owner / fee of nameSpace
mapping (address => SecurityTokenData) securityTokens; // Mapping from securityToken address to data about the securityToken
mapping (string => mapping (string => address)) tickers; // Mapping from nameSpace, to a mapping of ticker name to correspondong securityToken addresses
event LogNewSecurityToken(string _nameSpace, string _ticker, address indexed _securityTokenAddress, address indexed _owner, uint8 _type);
event LogNameSpaceCreated(string _nameSpace, address _owner, uint256 _fee);
event LogNameSpaceChange(string _nameSpace, address _newOwner, uint256 _newFee);
/**
* @dev Constructor use to set the essentials addresses to facilitate
* the creation of the security token
*/
function SecurityTokenRegistrar(
address _polyTokenAddress,
address _polyCustomersAddress,
address _polyComplianceAddress
) public
{
require(_polyTokenAddress != address(0));
require(_polyCustomersAddress != address(0));
require(_polyComplianceAddress != address(0));
PolyToken = IERC20(_polyTokenAddress);
polyCustomersAddress = _polyCustomersAddress;
polyComplianceAddress = _polyComplianceAddress;
}
/**
* @dev Creates a securityToken name space
* @param _nameSpace Name space string
* @param _fee Fee for this name space
*/
function createNameSpace(string _nameSpace, uint256 _fee) public {
require(bytes(_nameSpace).length > 0);
string memory nameSpace = lower(_nameSpace);
require(nameSpaceData[nameSpace].owner == address(0));
nameSpaceData[nameSpace].owner = msg.sender;
nameSpaceData[nameSpace].fee = _fee;
LogNameSpaceCreated(nameSpace, msg.sender, _fee);
}
/**
* @dev changes a string to lower case
* @param _base string to change
*/
function lower(string _base) internal pure returns (string) {
bytes memory _baseBytes = bytes(_base);
for (uint i = 0; i < _baseBytes.length; i++) {
bytes1 b1 = _baseBytes[i];
if (b1 >= 0x41 && b1 <= 0x5A) {
b1 = bytes1(uint8(b1)+32);
}
_baseBytes[i] = b1;
}
return string(_baseBytes);
}
/**
* @dev Changes name space fee
* @param _nameSpace Name space string
* @param _fee New fee for security token creation for this name space
*/
function changeNameSpace(string _nameSpace, uint256 _fee) public {
string memory nameSpace = lower(_nameSpace);
require(msg.sender == nameSpaceData[nameSpace].owner);
nameSpaceData[nameSpace].fee = _fee;
LogNameSpaceChange(nameSpace, msg.sender, _fee);
}
/**
* @dev Creates a new Security Token and saves it to the registry
* @param _nameSpaceName Name space for this security token
* @param _name Name of the security token
* @param _ticker Ticker name of the security
* @param _totalSupply Total amount of tokens being created
* @param _decimals Decimals value for token
* @param _owner Ethereum public key address of the security token owner
* @param _type Type of security being tokenized
*/
function createSecurityToken (
string _nameSpaceName,
string _name,
string _ticker,
uint256 _totalSupply,
uint8 _decimals,
address _owner,
uint8 _type
) external
{
require(_totalSupply > 0);
NameSpaceData storage nameSpace = nameSpaceData[_nameSpaceName];
require(tickers[_nameSpaceName][_ticker] == address(0));
require(nameSpace.owner != address(0));
require(_owner != address(0));
require(bytes(_name).length > 0 && bytes(_ticker).length > 0);
require(PolyToken.transferFrom(msg.sender, nameSpace.owner, nameSpace.fee));
address newSecurityTokenAddress = new SecurityToken(
_name,
_ticker,
_totalSupply,
_decimals,
_owner,
PolyToken,
polyCustomersAddress,
polyComplianceAddress
);
tickers[_nameSpaceName][_ticker] = newSecurityTokenAddress;
securityTokens[newSecurityTokenAddress] = SecurityTokenData(
_nameSpaceName,
_ticker,
_owner,
_type
);
LogNewSecurityToken(_nameSpaceName, _ticker, newSecurityTokenAddress, _owner, _type);
}
//////////////////////////////
///////// Get Functions
//////////////////////////////
/**
* @dev Get security token address by ticker name
* @param _nameSpace Name space of the Scurity token
* @param _ticker Symbol of the Scurity token
* @return address _ticker
*/
function getSecurityTokenAddress(string _nameSpace, string _ticker) public view returns (address) {
return tickers[_nameSpace][_ticker];
}
/**
* @dev Get Security token details by its ethereum address
* @param _STAddress Security token address
*/
function getSecurityTokenData(address _STAddress) public view returns (
string,
string,
address,
uint8
) {
return (
securityTokens[_STAddress].nameSpace,
securityTokens[_STAddress].ticker,
securityTokens[_STAddress].owner,
securityTokens[_STAddress].securityType
);
}
/**
* @dev Get the name space data
* @param _nameSpace Name space string.
*/
function getNameSpaceData(string _nameSpace) public view returns(address, uint256) {
string memory nameSpace = lower(_nameSpace);
return (
nameSpaceData[nameSpace].owner,
nameSpaceData[nameSpace].fee
);
}
}
|
Get the name space data _nameSpace Name space string./
|
function getNameSpaceData(string _nameSpace) public view returns(address, uint256) {
string memory nameSpace = lower(_nameSpace);
return (
nameSpaceData[nameSpace].owner,
nameSpaceData[nameSpace].fee
);
}
| 15,793,130
|
./partial_match/1/0xe245882dD81F25011ebd13bA2cDf2EABE7CD8184/sources/WrappedNFTFactory.sol
|
See {IERC721Metadata-tokenURI}./
|
function tokenURI(uint256 _tokenId) public view virtual override(IERC721Metadata, ERC721) returns (string memory) {
require(ERC721._exists(_tokenId), "BaseWrappedNFT: URI query for nonexistent token");
return nft.tokenURI(_tokenId);
}
| 2,816,891
|
// 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/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 "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../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 "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @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;
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;
// 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;
import "../NoobFriendlyTokenGenerator.sol";
/**
@author Chiao-Yu Yang, Justa Liang
@notice Blindbox: hind the NFT until revealed
*/
contract NFTBlindbox is NoobFriendlyTokenTemplate {
using Strings for uint;
/// @notice Price of token
uint public tokenPrice;
/// @notice Time to reveal the NFT
uint public revealTimestamp;
/// @notice Offset of the token ID after revealed
uint public offsetId;
/// @notice The baseURI before revealed
string public coverURI;
/// @dev Seed to do the hash
uint private _hashSeed;
/// @dev Setup the template
constructor(
BaseSettings memory baseSettings
)
ERC721(baseSettings.name, baseSettings.symbol)
PaymentSplitter(baseSettings.payees, baseSettings.shares)
NoobFriendlyTokenTemplate(baseSettings.typeOfNFT, baseSettings.maxSupply)
{}
/**
@notice Initialize the contract details
@param baseURI_ Base URI of revealed NFT
@param maxPurchase_ Max number of tokens per time
@param tokenPrice_ Price per token
@param startTimestamp_ Time to start sale
@param revealTimestamp_ Time to reveal
*/
function initialize(
string calldata baseURI_,
uint32 maxPurchase_,
uint tokenPrice_,
uint160 startTimestamp_,
uint160 revealTimestamp_
) external onlyOwner onlyOnce {
baseURI = baseURI_;
settings.maxPurchase = maxPurchase_;
tokenPrice = tokenPrice_;
settings.startTimestamp = startTimestamp_;
revealTimestamp = revealTimestamp_;
coverURI = "";
offsetId = 0;
}
/// @notice Reserve NFT by contract owner
function reserveNFT(
uint reserveNum
) public onlyOwner {
uint supply = totalSupply();
require(
supply + reserveNum <= settings.maxSupply,
"Blindbox: exceed max supply"
);
for (uint i = 0; i < reserveNum; i++) {
_safeMint(_msgSender(), supply + i);
_hashSeed += block.number;
}
}
/// @notice Set the after-revealed URI
function setBaseURI(
string calldata newBaseURI
) external onlyOwner {
baseURI = newBaseURI;
}
/// @notice Set the before-revealed URI
function setCoverURI(
string calldata newCoverURI
) external onlyOwner {
coverURI = newCoverURI;
}
/// @notice Change token price
function setTokenPrice(
uint newTokenPrice
) external onlyOwner {
tokenPrice = newTokenPrice;
}
/**
@notice Mint (buy) tokens from contract
@param numberOfTokens Number of token to mint (buy)
*/
function mintToken(
uint numberOfTokens
) external payable {
uint _maxSupply = settings.maxSupply;
uint _totalSuppy = totalSupply();
require(
isInit,
"BlindBox: not initialized"
);
require(
block.timestamp > settings.startTimestamp,
"BlindBox: sale is not start"
);
require(
numberOfTokens <= settings.maxPurchase,
"BlindBox: exceed max purchase"
);
require(
_totalSuppy + numberOfTokens <= _maxSupply,
"BlindBox: exceed max supply"
);
require(
msg.value >= tokenPrice*numberOfTokens,
"BlindBox: payment not enough"
);
for(uint i = 0; i < numberOfTokens; i++) {
_safeMint(owner(), _totalSuppy + i);
_safeTransfer(owner(), _msgSender(), _totalSuppy + i, "");
_hashSeed += block.number;
}
}
/// @notice Reveal NFT and shuffle token ID
function reveal() external {
require(
offsetId == 0,
"BlindBox: already revealed"
);
require(
totalSupply() == settings.maxSupply || block.timestamp >= revealTimestamp,
"BlindBox: not allowed to reveal"
);
require(
bytes(baseURI).length > 0,
"Blindbox: baseURI not set"
);
// Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
if (block.number > _hashSeed && block.number - _hashSeed > 255) {
offsetId = uint(blockhash(block.number - 1)) % settings.maxSupply;
}
else {
offsetId = uint(blockhash(_hashSeed)) % settings.maxSupply;
}
// Prevent default sequence
if (offsetId == 0) {
offsetId = 1;
}
}
/// @notice Override the ERC721-tokenURI()
function tokenURI(
uint tokenId
) public override view returns (string memory) {
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if (offsetId > 0) {
uint tokenIndex = (offsetId + tokenId) % settings.maxSupply;
return string(abi.encodePacked(baseURI, tokenIndex.toString()));
}
else {
if (bytes(coverURI).length == 0) {
return string(abi.encodePacked(baseURI, uint(settings.maxSupply).toString()));
}
else {
return string(abi.encodePacked(coverURI, tokenId.toString()));
}
}
}
}
/**
@author Justa Liang
@notice Blindbox generator
*/
contract NFTBlindboxGenerator is NoobFriendlyTokenGenerator {
constructor(
address adminAddr_,
uint slottingFee_
)
NoobFriendlyTokenGenerator(adminAddr_, slottingFee_)
{}
function _genContract(
BaseSettings calldata baseSettings
) internal override returns (address) {
return address(new NFTBlindbox(baseSettings));
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./NoobFriendlyTokenTemplate.sol";
/**
@author Justa Liang
@notice Template of NFT contract generator
*/
abstract contract NoobFriendlyTokenGenerator is Ownable, GeneratorInterface {
/// @notice Admin contract address
address public adminAddr;
/// @notice Slotting fee of generate one NFT contract
uint public override slottingFee;
/// @dev Setup slotting fee, and point to admin contract
constructor(
address adminAddr_,
uint slottingFee_
) {
adminAddr = adminAddr_;
slottingFee = slottingFee_;
}
/// @dev Should implement _genContract() in every generator
function _genContract(
BaseSettings calldata baseSettings
) internal virtual returns (address);
/**
@notice Generate NFT contract for user
@param client User who want to generate an NFT contract
@param baseSettings See BaseSettings in ./NoobFriendlyTokenTemplate.sol
*/
function genNFTContract(
address client,
BaseSettings calldata baseSettings
) external override returns (address) {
require(_msgSender() == adminAddr);
address contractAddr = _genContract(baseSettings);
TemplateInterface nftContract = TemplateInterface(contractAddr);
nftContract.transferOwnership(client);
return contractAddr;
}
/// @dev Update slotting fee
function updateSlottingFee(
uint newSlottingFee
) external onlyOwner {
slottingFee = newSlottingFee;
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/finance/PaymentSplitter.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
struct BaseSettings {
string name;
string symbol;
address[] payees;
uint[] shares;
uint32 typeOfNFT;
uint32 maxSupply;
}
struct BaseSettingsInfo {
string name;
string symbol;
uint32 typeOfNFT;
uint32 maxSupply;
}
interface GeneratorInterface {
function slottingFee() external view returns (uint);
function genNFTContract(address, BaseSettings calldata) external returns (address);
}
interface TemplateInterface {
function owner() external returns (address);
function transferOwnership(address newOwner) external;
}
/**
@author Justa Liang
@notice Template of NFT contract
*/
abstract contract NoobFriendlyTokenTemplate is Ownable, PaymentSplitter, ERC721Enumerable {
struct Settings {
uint32 maxSupply;
uint32 maxPurchase;
uint32 typeOfNFT;
uint160 startTimestamp;
}
/// @notice Template settings
Settings public settings;
/// @notice Prefix of tokenURI
string public baseURI;
/// @notice Whether contract is initialized
bool public isInit;
/// @dev Setup type and max supply
constructor(
uint32 typeOfNFT_,
uint32 maxSupply_
) {
settings.typeOfNFT = typeOfNFT_;
settings.maxSupply = maxSupply_;
isInit = false;
}
/// @dev Make the contract to initialized only once
modifier onlyOnce() {
require(!isInit, "template: init already");
isInit = true;
_;
}
/// @notice get BaseSettings
function getBaseSettings() external view returns (BaseSettingsInfo memory) {
return BaseSettingsInfo(
name(),
symbol(),
settings.typeOfNFT,
settings.maxSupply
);
}
}
|
Reserve NFT by contract owner
|
function reserveNFT(
uint reserveNum
) public onlyOwner {
uint supply = totalSupply();
require(
supply + reserveNum <= settings.maxSupply,
"Blindbox: exceed max supply"
);
for (uint i = 0; i < reserveNum; i++) {
_safeMint(_msgSender(), supply + i);
_hashSeed += block.number;
}
}
| 11,841,308
|
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../ERC1155/ERC1155BurnableV2.sol";
import "../DigitalaxAccessControls.sol";
import "../EIP2771/BaseRelayRecipient.sol";
/**
* @title Digitalax Materials NFT a.k.a. child NFTs
* @dev Issues ERC-1155 tokens which can be held by the parent ERC-721 contract
*/
contract DigitalaxMaterialsV2 is ERC1155BurnableV2, BaseRelayRecipient {
// @notice event emitted on contract creation
event DigitalaxMaterialsDeployed();
// @notice a single child has been created
event ChildCreated(
uint256 indexed childId
);
// @notice a batch of children have been created
event ChildrenCreated(
uint256[] childIds
);
string public name;
string public symbol;
// @notice current token ID pointer
uint256 public tokenIdPointer = 100000;
// @notice enforcing access controls
DigitalaxAccessControls public accessControls;
address public childChain;
modifier onlyChildChain() {
require(
_msgSender() == childChain,
"Child token: caller is not the child chain contract"
);
_;
}
constructor(
string memory _name,
string memory _symbol,
DigitalaxAccessControls _accessControls,
address _childChain,
address _trustedForwarder
) public {
name = _name;
symbol = _symbol;
accessControls = _accessControls;
trustedForwarder = _trustedForwarder;
childChain = _childChain;
emit DigitalaxMaterialsDeployed();
}
/**
* Override this function.
* This version is to keep track of BaseRelayRecipient you are using
* in your contract.
*/
function versionRecipient() external view override returns (string memory) {
return "1";
}
function setTrustedForwarder(address _trustedForwarder) external {
require(
accessControls.hasAdminRole(_msgSender()),
"DigitalaxMaterials.setTrustedForwarder: Sender must be admin"
);
trustedForwarder = _trustedForwarder;
}
// This is to support Native meta transactions
// never use msg.sender directly, use _msgSender() instead
function _msgSender()
internal
override
view
returns (address payable sender)
{
return BaseRelayRecipient.msgSender();
}
///////////////////////////
// Creating new children //
///////////////////////////
/**
@notice Creates a single child ERC1155 token
@dev Only callable with smart contact role
@return id the generated child Token ID
*/
function createChild(string calldata _uri) external returns (uint256 id) {
require(
accessControls.hasSmartContractRole(_msgSender()),
"DigitalaxMaterials.createChild: Sender must be smart contract"
);
require(bytes(_uri).length > 0, "DigitalaxMaterials.createChild: URI is a blank string");
tokenIdPointer = tokenIdPointer.add(1);
id = tokenIdPointer;
_setURI(id, _uri);
emit ChildCreated(id);
}
/**
@notice Creates a batch of child ERC1155 tokens
@dev Only callable with smart contact role
@return tokenIds the generated child Token IDs
*/
function batchCreateChildren(string[] calldata _uris) external returns (uint256[] memory tokenIds) {
require(
accessControls.hasSmartContractRole(_msgSender()),
"DigitalaxMaterials.batchCreateChildren: Sender must be smart contract"
);
require(_uris.length > 0, "DigitalaxMaterials.batchCreateChildren: No data supplied in array");
uint256 urisLength = _uris.length;
tokenIds = new uint256[](urisLength);
for (uint256 i = 0; i < urisLength; i++) {
string memory uri = _uris[i];
require(bytes(uri).length > 0, "DigitalaxMaterials.batchCreateChildren: URI is a blank string");
tokenIdPointer = tokenIdPointer.add(1);
_setURI(tokenIdPointer, uri);
tokenIds[i] = tokenIdPointer;
}
// Batched event for GAS savings
emit ChildrenCreated(tokenIds);
}
//////////////////////////////////
// Minting of existing children //
//////////////////////////////////
/**
@notice Mints a single child ERC1155 tokens, increasing its supply by the _amount specified. msg.data along with the
parent contract as the recipient can be used to map the created children to a given parent token
@dev Only callable with smart contact role
*/
function mintChild(uint256 _childTokenId, uint256 _amount, address _beneficiary, bytes calldata _data) external {
require(
accessControls.hasSmartContractRole(_msgSender()),
"DigitalaxMaterials.mintChild: Sender must be smart contract"
);
require(bytes(tokenUris[_childTokenId]).length > 0, "DigitalaxMaterials.mintChild: Strand does not exist");
require(_amount > 0, "DigitalaxMaterials.mintChild: No amount specified");
_mint(_beneficiary, _childTokenId, _amount, _data);
}
/**
@notice Mints a batch of child ERC1155 tokens, increasing its supply by the _amounts specified. msg.data along with the
parent contract as the recipient can be used to map the created children to a given parent token
@dev Only callable with smart contact role
*/
function batchMintChildren(
uint256[] calldata _childTokenIds,
uint256[] calldata _amounts,
address _beneficiary,
bytes calldata _data
) external {
require(
accessControls.hasSmartContractRole(_msgSender()),
"DigitalaxMaterials.batchMintChildren: Sender must be smart contract"
);
require(_childTokenIds.length == _amounts.length, "DigitalaxMaterials.batchMintChildren: Array lengths are invalid");
require(_childTokenIds.length > 0, "DigitalaxMaterials.batchMintChildren: No data supplied in arrays");
// Check the strands exist and no zero amounts
for (uint256 i = 0; i < _childTokenIds.length; i++) {
uint256 strandId = _childTokenIds[i];
require(bytes(tokenUris[strandId]).length > 0, "DigitalaxMaterials.batchMintChildren: Strand does not exist");
uint256 amount = _amounts[i];
require(amount > 0, "DigitalaxMaterials.batchMintChildren: Invalid amount");
}
_mintBatch(_beneficiary, _childTokenIds, _amounts, _data);
}
function updateAccessControls(DigitalaxAccessControls _accessControls) external {
require(
accessControls.hasAdminRole(_msgSender()),
"DigitalaxMaterials.updateAccessControls: Sender must be admin"
);
require(
address(_accessControls) != address(0),
"DigitalaxMaterials.updateAccessControls: New access controls cannot be ZERO address"
);
accessControls = _accessControls;
}
/**
* @notice called when tokens are deposited on root chain
* @dev Should be callable only by ChildChainManager
* Should handle deposit by minting the required tokens for user
* Make sure minting is done only by this function
* @param user user address for whom deposit is being done
* @param depositData abi encoded ids array and amounts array
*/
function deposit(address user, bytes calldata depositData)
external
onlyChildChain
{
(
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) = abi.decode(depositData, (uint256[], uint256[], bytes));
require(user != address(0x0), "DigitalaxMaterials: INVALID_DEPOSIT_USER");
_mintBatch(user, ids, amounts, data);
}
/**
* @notice called when user wants to withdraw single token back to root chain
* @dev Should burn user's tokens. This transaction will be verified when exiting on root chain
* @param id id to withdraw
* @param amount amount to withdraw
*/
function withdrawSingle(uint256 id, uint256 amount) external {
_burn(_msgSender(), id, amount);
}
/**
* @notice called when user wants to batch withdraw tokens back to root chain
* @dev Should burn user's tokens. This transaction will be verified when exiting on root chain
* @param ids ids to withdraw
* @param amounts amounts to withdraw
*/
function withdrawBatch(uint256[] calldata ids, uint256[] calldata amounts)
external
{
_burnBatch(_msgSender(), ids, amounts);
}
function setGarmentNFTApproved(address _garmentNFT) external {
require(
accessControls.hasAdminRole(_msgSender()),
"DigitalaxMaterials.updateAccessControls: Sender must be admin"
);
garmentNFTApproved = _garmentNFT;
}
}
|
called when user wants to batch withdraw tokens back to root chain Should burn user's tokens. This transaction will be verified when exiting on root chain ids ids to withdraw amounts amounts to withdraw/
|
function withdrawBatch(uint256[] calldata ids, uint256[] calldata amounts)
external
{
_burnBatch(_msgSender(), ids, amounts);
}
| 13,086,500
|
./full_match/1/0xc3f2C8F9d5F0705De706b1302B7a039e1e11aC88/sources/contracts/logic/Verifier.sol
|
Calculates hash of transaction bound params for snark verification _boundParams - bound parameters return bound parameters hash/
|
function hashBoundParams(BoundParams calldata _boundParams) public pure returns (uint256) {
return uint256(keccak256(abi.encode(_boundParams))) % SNARK_SCALAR_FIELD;
}
| 17,076,283
|
import "prefilled-token.sol";
pragma solidity ^0.4.11;
contract AEToken is PrefilledToken {
// Date when the tokens won't be transferable anymore
uint public transferableUntil;
/**
* HumanStandardToken(
uint256 initialAmount,
string tokenName,
uint8 decimalUnits,
string tokenSymbol
)
*/
function AEToken() HumanStandardToken(0, "AEToken", 16, "AE") {
uint nYears = 2;
transferableUntil = now + (60 * 60 * 24 * 365 * nYears);
}
function transfer(address _to, uint256 _value) only_transferable returns (bool success) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) only_transferable returns (bool success) {
return super.transferFrom(_from, _to, _value);
}
modifier only_transferable () {
if (now > transferableUntil) {
throw;
}
_;
}
}
|
HumanStandardToken(/
|
function AEToken() HumanStandardToken(0, "AEToken", 16, "AE") {
uint nYears = 2;
transferableUntil = now + (60 * 60 * 24 * 365 * nYears);
}
| 955,598
|
/**
* Copyright 2017-2020, bZeroX, LLC <https://bzx.network/>. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
library MathUtil {
/**
* @dev Integer division of two numbers, rounding up and truncating the quotient
*/
function divCeil(uint256 a, uint256 b) internal pure returns (uint256) {
return divCeil(a, b, "SafeMath: division by zero");
}
/**
* @dev Integer division of two numbers, rounding up and truncating the quotient
*/
function divCeil(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b != 0, errorMessage);
if (a == 0) {
return 0;
}
uint256 c = ((a - 1) / b) + 1;
return c;
}
function min256(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a < _b ? _a : _b;
}
}
interface IPriceFeeds {
function queryRate(
address sourceToken,
address destToken)
external
view
returns (uint256 rate, uint256 precision);
function queryPrecision(
address sourceToken,
address destToken)
external
view
returns (uint256 precision);
function queryReturn(
address sourceToken,
address destToken,
uint256 sourceAmount)
external
view
returns (uint256 destAmount);
function checkPriceDisagreement(
address sourceToken,
address destToken,
uint256 sourceAmount,
uint256 destAmount,
uint256 maxSlippage)
external
view
returns (uint256 sourceToDestSwapRate);
function amountInEth(
address Token,
uint256 amount)
external
view
returns (uint256 ethAmount);
function getMaxDrawdown(
address loanToken,
address collateralToken,
uint256 loanAmount,
uint256 collateralAmount,
uint256 maintenanceMargin)
external
view
returns (uint256);
function getCurrentMarginAndCollateralSize(
address loanToken,
address collateralToken,
uint256 loanAmount,
uint256 collateralAmount)
external
view
returns (uint256 currentMargin, uint256 collateralInEthAmount);
function getCurrentMargin(
address loanToken,
address collateralToken,
uint256 loanAmount,
uint256 collateralAmount)
external
view
returns (uint256 currentMargin, uint256 collateralToLoanRate);
function shouldLiquidate(
address loanToken,
address collateralToken,
uint256 loanAmount,
uint256 collateralAmount,
uint256 maintenanceMargin)
external
view
returns (bool);
function getFastGasPrice(
address payToken)
external
view
returns (uint256);
}
contract IVestingToken is IERC20 {
function claim()
external;
function vestedBalanceOf(
address _owner)
external
view
returns (uint256);
function claimedBalanceOf(
address _owner)
external
view
returns (uint256);
}
/**
* @dev Library for managing loan sets
*
* 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.
*
* Include with `using EnumerableBytes32Set for EnumerableBytes32Set.Bytes32Set;`.
*
*/
library EnumerableBytes32Set {
struct Bytes32Set {
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) index;
bytes32[] values;
}
/**
* @dev Add an address value to a set. O(1).
* Returns false if the value was already in the set.
*/
function addAddress(Bytes32Set storage set, address addrvalue)
internal
returns (bool)
{
bytes32 value;
assembly {
value := addrvalue
}
return addBytes32(set, value);
}
/**
* @dev Add a value to a set. O(1).
* Returns false if the value was already in the set.
*/
function addBytes32(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
if (!contains(set, value)){
set.index[value] = set.values.push(value);
return true;
} else {
return false;
}
}
/**
* @dev Removes an address value from a set. O(1).
* Returns false if the value was not present in the set.
*/
function removeAddress(Bytes32Set storage set, address addrvalue)
internal
returns (bool)
{
bytes32 value;
assembly {
value := addrvalue
}
return removeBytes32(set, value);
}
/**
* @dev Removes a value from a set. O(1).
* Returns false if the value was not present in the set.
*/
function removeBytes32(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
if (contains(set, value)){
uint256 toDeleteIndex = set.index[value] - 1;
uint256 lastIndex = set.values.length - 1;
// If the element we're deleting is the last one, we can just remove it without doing a swap
if (lastIndex != toDeleteIndex) {
bytes32 lastValue = set.values[lastIndex];
// Move the last value to the index where the deleted value is
set.values[toDeleteIndex] = lastValue;
// Update the index for the moved value
set.index[lastValue] = toDeleteIndex + 1; // All indexes are 1-based
}
// Delete the index entry for the deleted value
delete set.index[value];
// Delete the old entry for the moved value
set.values.pop();
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value)
internal
view
returns (bool)
{
return set.index[value] != 0;
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function containsAddress(Bytes32Set storage set, address addrvalue)
internal
view
returns (bool)
{
bytes32 value;
assembly {
value := addrvalue
}
return set.index[value] != 0;
}
/**
* @dev Returns an array with all values in the set. O(N).
* 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.
* WARNING: This function may run out of gas on large sets: use {length} and
* {get} instead in these cases.
*/
function enumerate(Bytes32Set storage set, uint256 start, uint256 count)
internal
view
returns (bytes32[] memory output)
{
uint256 end = start + count;
require(end >= start, "addition overflow");
end = set.values.length < end ? set.values.length : end;
if (end == 0 || start >= end) {
return output;
}
output = new bytes32[](end-start);
for (uint256 i = start; i < end; i++) {
output[i-start] = set.values[i];
}
return output;
}
/**
* @dev Returns the number of elements on the set. O(1).
*/
function length(Bytes32Set storage set)
internal
view
returns (uint256)
{
return set.values.length;
}
/** @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function get(Bytes32Set storage set, uint256 index)
internal
view
returns (bytes32)
{
return set.values[index];
}
/** @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function getAddress(Bytes32Set storage set, uint256 index)
internal
view
returns (address)
{
bytes32 value = set.values[index];
address addrvalue;
assembly {
addrvalue := value
}
return addrvalue;
}
}
interface IUniswapV2Router {
// 0x38ed1739
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline)
external
returns (uint256[] memory amounts);
// 0x8803dbee
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline)
external
returns (uint256[] memory amounts);
// 0x1f00ca74
function getAmountsIn(
uint256 amountOut,
address[] calldata path)
external
view
returns (uint256[] memory amounts);
// 0xd06ca61f
function getAmountsOut(
uint256 amountIn,
address[] calldata path)
external
view
returns (uint256[] memory amounts);
}
interface ICurve3Pool {
function add_liquidity(
uint256[3] calldata amounts,
uint256 min_mint_amount)
external;
function get_virtual_price()
external
view
returns (uint256);
}
/// @title A proxy interface for The Protocol
/// @author bZeroX
/// @notice This is just an interface, not to be deployed itself.
/// @dev This interface is to be used for the protocol interactions.
interface IBZx {
////// Protocol //////
/// @dev adds or replaces existing proxy module
/// @param target target proxy module address
function replaceContract(address target) external;
/// @dev updates all proxy modules addreses and function signatures.
/// sigsArr and targetsArr should be of equal length
/// @param sigsArr array of function signatures
/// @param targetsArr array of target proxy module addresses
function setTargets(
string[] calldata sigsArr,
address[] calldata targetsArr
) external;
/// @dev returns protocol module address given a function signature
/// @return module address
function getTarget(string calldata sig) external view returns (address);
////// Protocol Settings //////
/// @dev sets price feed contract address. The contract on the addres should implement IPriceFeeds interface
/// @param newContract module address for the IPriceFeeds implementation
function setPriceFeedContract(address newContract) external;
/// @dev sets swaps contract address. The contract on the addres should implement ISwapsImpl interface
/// @param newContract module address for the ISwapsImpl implementation
function setSwapsImplContract(address newContract) external;
/// @dev sets loan pool with assets. Accepts two arrays of equal length
/// @param pools array of address of pools
/// @param assets array of addresses of assets
function setLoanPool(address[] calldata pools, address[] calldata assets)
external;
/// @dev updates list of supported tokens, it can be use also to disable or enable particualr token
/// @param addrs array of address of pools
/// @param toggles array of addresses of assets
/// @param withApprovals resets tokens to unlimited approval with the swaps integration (kyber, etc.)
function setSupportedTokens(
address[] calldata addrs,
bool[] calldata toggles,
bool withApprovals
) external;
/// @dev sets lending fee with WEI_PERCENT_PRECISION
/// @param newValue lending fee percent
function setLendingFeePercent(uint256 newValue) external;
/// @dev sets trading fee with WEI_PERCENT_PRECISION
/// @param newValue trading fee percent
function setTradingFeePercent(uint256 newValue) external;
/// @dev sets borrowing fee with WEI_PERCENT_PRECISION
/// @param newValue borrowing fee percent
function setBorrowingFeePercent(uint256 newValue) external;
/// @dev sets affiliate fee with WEI_PERCENT_PRECISION
/// @param newValue affiliate fee percent
function setAffiliateFeePercent(uint256 newValue) external;
/// @dev sets liquidation inncetive percent per loan per token. This is the profit percent
/// that liquidator gets in the process of liquidating.
/// @param loanTokens array list of loan tokens
/// @param collateralTokens array list of collateral tokens
/// @param amounts array list of liquidation inncetive amount
function setLiquidationIncentivePercent(
address[] calldata loanTokens,
address[] calldata collateralTokens,
uint256[] calldata amounts
) external;
/// @dev sets max swap rate slippage percent.
/// @param newAmount max swap rate slippage percent.
function setMaxDisagreement(uint256 newAmount) external;
/// TODO
function setSourceBufferPercent(uint256 newAmount) external;
/// @dev sets maximum supported swap size in ETH
/// @param newAmount max swap size in ETH.
function setMaxSwapSize(uint256 newAmount) external;
/// @dev sets fee controller address
/// @param newController address of the new fees controller
function setFeesController(address newController) external;
/// @dev withdraws lending fees to receiver. Only can be called by feesController address
/// @param tokens array of token addresses.
/// @param receiver fees receiver address
/// @return amounts array of amounts withdrawn
function withdrawFees(
address[] calldata tokens,
address receiver,
FeeClaimType feeType
) external returns (uint256[] memory amounts);
/// @dev withdraw protocol token (BZRX) from vesting contract vBZRX
/// @param receiver address of BZRX tokens claimed
/// @param amount of BZRX token to be claimed. max is claimed if amount is greater than balance.
/// @return rewardToken reward token address
/// @return withdrawAmount amount
function withdrawProtocolToken(address receiver, uint256 amount)
external
returns (address rewardToken, uint256 withdrawAmount);
/// @dev depozit protocol token (BZRX)
/// @param amount address of BZRX tokens to deposit
function depositProtocolToken(uint256 amount) external;
function grantRewards(address[] calldata users, uint256[] calldata amounts)
external
returns (uint256 totalAmount);
// NOTE: this doesn't sanitize inputs -> inaccurate values may be returned if there are duplicates tokens input
function queryFees(address[] calldata tokens, FeeClaimType feeType)
external
view
returns (uint256[] memory amountsHeld, uint256[] memory amountsPaid);
function priceFeeds() external view returns (address);
function swapsImpl() external view returns (address);
function logicTargets(bytes4) external view returns (address);
function loans(bytes32) external view returns (Loan memory);
function loanParams(bytes32) external view returns (LoanParams memory);
// we don't use this yet
// function lenderOrders(address, bytes32) external returns (Order memory);
// function borrowerOrders(address, bytes32) external returns (Order memory);
function delegatedManagers(bytes32, address) external view returns (bool);
function lenderInterest(address, address)
external
view
returns (LenderInterest memory);
function loanInterest(bytes32) external view returns (LoanInterest memory);
function feesController() external view returns (address);
function lendingFeePercent() external view returns (uint256);
function lendingFeeTokensHeld(address) external view returns (uint256);
function lendingFeeTokensPaid(address) external view returns (uint256);
function borrowingFeePercent() external view returns (uint256);
function borrowingFeeTokensHeld(address) external view returns (uint256);
function borrowingFeeTokensPaid(address) external view returns (uint256);
function protocolTokenHeld() external view returns (uint256);
function protocolTokenPaid() external view returns (uint256);
function affiliateFeePercent() external view returns (uint256);
function liquidationIncentivePercent(address, address)
external
view
returns (uint256);
function loanPoolToUnderlying(address) external view returns (address);
function underlyingToLoanPool(address) external view returns (address);
function supportedTokens(address) external view returns (bool);
function maxDisagreement() external view returns (uint256);
function sourceBufferPercent() external view returns (uint256);
function maxSwapSize() external view returns (uint256);
/// @dev get list of loan pools in the system. Ordering is not guaranteed
/// @param start start index
/// @param count number of pools to return
/// @return loanPoolsList array of loan pools
function getLoanPoolsList(uint256 start, uint256 count)
external
view
returns (address[] memory loanPoolsList);
/// @dev checks whether addreess is a loan pool address
/// @return boolean
function isLoanPool(address loanPool) external view returns (bool);
////// Loan Settings //////
/// @dev creates new loan param settings
/// @param loanParamsList array of LoanParams
/// @return loanParamsIdList array of loan ids created
function setupLoanParams(LoanParams[] calldata loanParamsList)
external
returns (bytes32[] memory loanParamsIdList);
/// @dev Deactivates LoanParams for future loans. Active loans using it are unaffected.
/// @param loanParamsIdList array of loan ids
function disableLoanParams(bytes32[] calldata loanParamsIdList) external;
/// @dev gets array of LoanParams by given ids
/// @param loanParamsIdList array of loan ids
/// @return loanParamsList array of LoanParams
function getLoanParams(bytes32[] calldata loanParamsIdList)
external
view
returns (LoanParams[] memory loanParamsList);
/// @dev Enumerates LoanParams in the system by owner
/// @param owner of the loan params
/// @param start number of loans to return
/// @param count total number of the items
/// @return loanParamsList array of LoanParams
function getLoanParamsList(
address owner,
uint256 start,
uint256 count
) external view returns (bytes32[] memory loanParamsList);
/// @dev returns total loan principal for token address
/// @param lender address
/// @param loanToken address
/// @return total principal of the loan
function getTotalPrincipal(address lender, address loanToken)
external
view
returns (uint256);
////// Loan Openings //////
/// @dev This is THE function that borrows or trades on the protocol
/// @param loanParamsId id of the LoanParam created beforehand by setupLoanParams function
/// @param loanId id of existing loan, if 0, start a new loan
/// @param isTorqueLoan boolean whether it is toreque or non torque loan
/// @param initialMargin in WEI_PERCENT_PRECISION
/// @param sentAddresses array of size 4:
/// lender: must match loan if loanId provided
/// borrower: must match loan if loanId provided
/// receiver: receiver of funds (address(0) assumes borrower address)
/// manager: delegated manager of loan unless address(0)
/// @param sentValues array of size 5:
/// newRate: new loan interest rate
/// newPrincipal: new loan size (borrowAmount + any borrowed interest)
/// torqueInterest: new amount of interest to escrow for Torque loan (determines initial loan length)
/// loanTokenReceived: total loanToken deposit (amount not sent to borrower in the case of Torque loans)
/// collateralTokenReceived: total collateralToken deposit
/// @param loanDataBytes required when sending ether
/// @return principal of the loan and collateral amount
function borrowOrTradeFromPool(
bytes32 loanParamsId,
bytes32 loanId,
bool isTorqueLoan,
uint256 initialMargin,
address[4] calldata sentAddresses,
uint256[5] calldata sentValues,
bytes calldata loanDataBytes
) external payable returns (LoanOpenData memory);
/// @dev sets/disables/enables the delegated manager for the loan
/// @param loanId id of the loan
/// @param delegated delegated manager address
/// @param toggle boolean set enabled or disabled
function setDelegatedManager(
bytes32 loanId,
address delegated,
bool toggle
) external;
/// @dev estimates margin exposure for simulated position
/// @param loanToken address of the loan token
/// @param collateralToken address of collateral token
/// @param loanTokenSent amout of loan token sent
/// @param collateralTokenSent amount of collateral token sent
/// @param interestRate yearly interest rate
/// @param newPrincipal principal amount of the loan
/// @return estimated margin exposure amount
function getEstimatedMarginExposure(
address loanToken,
address collateralToken,
uint256 loanTokenSent,
uint256 collateralTokenSent,
uint256 interestRate,
uint256 newPrincipal
) external view returns (uint256);
/// @dev calculates required collateral for simulated position
/// @param loanToken address of loan token
/// @param collateralToken address of collateral token
/// @param newPrincipal principal amount of the loan
/// @param marginAmount margin amount of the loan
/// @param isTorqueLoan boolean torque or non torque loan
/// @return collateralAmountRequired amount required
function getRequiredCollateral(
address loanToken,
address collateralToken,
uint256 newPrincipal,
uint256 marginAmount,
bool isTorqueLoan
) external view returns (uint256 collateralAmountRequired);
function getRequiredCollateralByParams(
bytes32 loanParamsId,
uint256 newPrincipal
) external view returns (uint256 collateralAmountRequired);
/// @dev calculates borrow amount for simulated position
/// @param loanToken address of loan token
/// @param collateralToken address of collateral token
/// @param collateralTokenAmount amount of collateral token sent
/// @param marginAmount margin amount
/// @param isTorqueLoan boolean torque or non torque loan
/// @return borrowAmount possible borrow amount
function getBorrowAmount(
address loanToken,
address collateralToken,
uint256 collateralTokenAmount,
uint256 marginAmount,
bool isTorqueLoan
) external view returns (uint256 borrowAmount);
function getBorrowAmountByParams(
bytes32 loanParamsId,
uint256 collateralTokenAmount
) external view returns (uint256 borrowAmount);
////// Loan Closings //////
/// @dev liquidates unhealty loans
/// @param loanId id of the loan
/// @param receiver address receiving liquidated loan collateral
/// @param closeAmount amount to close denominated in loanToken
/// @return loanCloseAmount amount of the collateral token of the loan
/// @return seizedAmount sezied amount in the collateral token
/// @return seizedToken loan token address
function liquidate(
bytes32 loanId,
address receiver,
uint256 closeAmount
)
external
payable
returns (
uint256 loanCloseAmount,
uint256 seizedAmount,
address seizedToken
);
/// @dev rollover loan
/// @param loanId id of the loan
/// @param loanDataBytes reserved for future use.
function rollover(bytes32 loanId, bytes calldata loanDataBytes)
external
returns (address rebateToken, uint256 gasRebate);
/// @dev close position with loan token deposit
/// @param loanId id of the loan
/// @param receiver collateral token reciever address
/// @param depositAmount amount of loan token to deposit
/// @return loanCloseAmount loan close amount
/// @return withdrawAmount loan token withdraw amount
/// @return withdrawToken loan token address
function closeWithDeposit(
bytes32 loanId,
address receiver,
uint256 depositAmount // denominated in loanToken
)
external
payable
returns (
uint256 loanCloseAmount,
uint256 withdrawAmount,
address withdrawToken
);
/// @dev close position with swap
/// @param loanId id of the loan
/// @param receiver collateral token reciever address
/// @param swapAmount amount of loan token to swap
/// @param returnTokenIsCollateral boolean whether to return tokens is collateral
/// @param loanDataBytes reserved for future use
/// @return loanCloseAmount loan close amount
/// @return withdrawAmount loan token withdraw amount
/// @return withdrawToken loan token address
function closeWithSwap(
bytes32 loanId,
address receiver,
uint256 swapAmount, // denominated in collateralToken
bool returnTokenIsCollateral, // true: withdraws collateralToken, false: withdraws loanToken
bytes calldata loanDataBytes
)
external
returns (
uint256 loanCloseAmount,
uint256 withdrawAmount,
address withdrawToken
);
////// Loan Closings With Gas Token //////
/// @dev liquidates unhealty loans by using Gas token
/// @param loanId id of the loan
/// @param receiver address receiving liquidated loan collateral
/// @param gasTokenUser user address of the GAS token
/// @param closeAmount amount to close denominated in loanToken
/// @return loanCloseAmount loan close amount
/// @return seizedAmount loan token withdraw amount
/// @return seizedToken loan token address
function liquidateWithGasToken(
bytes32 loanId,
address receiver,
address gasTokenUser,
uint256 closeAmount // denominated in loanToken
)
external
payable
returns (
uint256 loanCloseAmount,
uint256 seizedAmount,
address seizedToken
);
/// @dev rollover loan
/// @param loanId id of the loan
/// @param gasTokenUser user address of the GAS token
function rolloverWithGasToken(
bytes32 loanId,
address gasTokenUser,
bytes calldata /*loanDataBytes*/
) external returns (address rebateToken, uint256 gasRebate);
/// @dev close position with loan token deposit
/// @param loanId id of the loan
/// @param receiver collateral token reciever address
/// @param gasTokenUser user address of the GAS token
/// @param depositAmount amount of loan token to deposit denominated in loanToken
/// @return loanCloseAmount loan close amount
/// @return withdrawAmount loan token withdraw amount
/// @return withdrawToken loan token address
function closeWithDepositWithGasToken(
bytes32 loanId,
address receiver,
address gasTokenUser,
uint256 depositAmount
)
external
payable
returns (
uint256 loanCloseAmount,
uint256 withdrawAmount,
address withdrawToken
);
/// @dev close position with swap
/// @param loanId id of the loan
/// @param receiver collateral token reciever address
/// @param gasTokenUser user address of the GAS token
/// @param swapAmount amount of loan token to swap denominated in collateralToken
/// @param returnTokenIsCollateral true: withdraws collateralToken, false: withdraws loanToken
/// @return loanCloseAmount loan close amount
/// @return withdrawAmount loan token withdraw amount
/// @return withdrawToken loan token address
function closeWithSwapWithGasToken(
bytes32 loanId,
address receiver,
address gasTokenUser,
uint256 swapAmount,
bool returnTokenIsCollateral,
bytes calldata loanDataBytes
)
external
returns (
uint256 loanCloseAmount,
uint256 withdrawAmount,
address withdrawToken
);
////// Loan Maintenance //////
/// @dev deposit collateral to existing loan
/// @param loanId existing loan id
/// @param depositAmount amount to deposit which must match msg.value if ether is sent
function depositCollateral(bytes32 loanId, uint256 depositAmount)
external
payable;
/// @dev withdraw collateral from existing loan
/// @param loanId existing lona id
/// @param receiver address of withdrawn tokens
/// @param withdrawAmount amount to withdraw
/// @return actualWithdrawAmount actual amount withdrawn
function withdrawCollateral(
bytes32 loanId,
address receiver,
uint256 withdrawAmount
) external returns (uint256 actualWithdrawAmount);
/// @dev withdraw accrued interest rate for a loan given token address
/// @param loanToken loan token address
function withdrawAccruedInterest(address loanToken) external;
/// @dev extends loan duration by depositing more collateral
/// @param loanId id of the existing loan
/// @param depositAmount amount to deposit
/// @param useCollateral boolean whether to extend using collateral or deposit amount
/// @return secondsExtended by that number of seconds loan duration was extended
function extendLoanDuration(
bytes32 loanId,
uint256 depositAmount,
bool useCollateral,
bytes calldata // for future use /*loanDataBytes*/
) external payable returns (uint256 secondsExtended);
/// @dev reduces loan duration by withdrawing collateral
/// @param loanId id of the existing loan
/// @param receiver address to receive tokens
/// @param withdrawAmount amount to withdraw
/// @return secondsReduced by that number of seconds loan duration was extended
function reduceLoanDuration(
bytes32 loanId,
address receiver,
uint256 withdrawAmount
) external returns (uint256 secondsReduced);
function setDepositAmount(
bytes32 loanId,
uint256 depositValueAsLoanToken,
uint256 depositValueAsCollateralToken
) external;
function claimRewards(address receiver)
external
returns (uint256 claimAmount);
function transferLoan(bytes32 loanId, address newOwner) external;
function rewardsBalanceOf(address user)
external
view
returns (uint256 rewardsBalance);
/// @dev Gets current lender interest data totals for all loans with a specific oracle and interest token
/// @param lender The lender address
/// @param loanToken The loan token address
/// @return interestPaid The total amount of interest that has been paid to a lender so far
/// @return interestPaidDate The date of the last interest pay out, or 0 if no interest has been withdrawn yet
/// @return interestOwedPerDay The amount of interest the lender is earning per day
/// @return interestUnPaid The total amount of interest the lender is owned and not yet withdrawn
/// @return interestFeePercent The fee retained by the protocol before interest is paid to the lender
/// @return principalTotal The total amount of outstading principal the lender has loaned
function getLenderInterestData(address lender, address loanToken)
external
view
returns (
uint256 interestPaid,
uint256 interestPaidDate,
uint256 interestOwedPerDay,
uint256 interestUnPaid,
uint256 interestFeePercent,
uint256 principalTotal
);
/// @dev Gets current interest data for a loan
/// @param loanId A unique id representing the loan
/// @return loanToken The loan token that interest is paid in
/// @return interestOwedPerDay The amount of interest the borrower is paying per day
/// @return interestDepositTotal The total amount of interest the borrower has deposited
/// @return interestDepositRemaining The amount of deposited interest that is not yet owed to a lender
function getLoanInterestData(bytes32 loanId)
external
view
returns (
address loanToken,
uint256 interestOwedPerDay,
uint256 interestDepositTotal,
uint256 interestDepositRemaining
);
/// @dev gets list of loans of particular user address
/// @param user address of the loans
/// @param start of the index
/// @param count number of loans to return
/// @param loanType type of the loan: All(0), Margin(1), NonMargin(2)
/// @param isLender whether to list lender loans or borrower loans
/// @param unsafeOnly booleat if true return only unsafe loans that are open for liquidation
/// @return loansData LoanReturnData array of loans
function getUserLoans(
address user,
uint256 start,
uint256 count,
LoanType loanType,
bool isLender,
bool unsafeOnly
) external view returns (LoanReturnData[] memory loansData);
function getUserLoansCount(address user, bool isLender)
external
view
returns (uint256);
/// @dev gets existing loan
/// @param loanId id of existing loan
/// @return loanData array of loans
function getLoan(bytes32 loanId)
external
view
returns (LoanReturnData memory loanData);
/// @dev get current active loans in the system
/// @param start of the index
/// @param count number of loans to return
/// @param unsafeOnly boolean if true return unsafe loan only (open for liquidation)
function getActiveLoans(
uint256 start,
uint256 count,
bool unsafeOnly
) external view returns (LoanReturnData[] memory loansData);
/// @dev get current active loans in the system
/// @param start of the index
/// @param count number of loans to return
/// @param unsafeOnly boolean if true return unsafe loan only (open for liquidation)
/// @param isLiquidatable boolean if true return liquidatable loans only
function getActiveLoansAdvanced(
uint256 start,
uint256 count,
bool unsafeOnly,
bool isLiquidatable
) external view returns (LoanReturnData[] memory loansData);
function getActiveLoansCount() external view returns (uint256);
////// Swap External //////
/// @dev swap thru external integration
/// @param sourceToken source token address
/// @param destToken destintaion token address
/// @param receiver address to receive tokens
/// @param returnToSender TODO
/// @param sourceTokenAmount source token amount
/// @param requiredDestTokenAmount destination token amount
/// @param swapData TODO
/// @return destTokenAmountReceived destination token received
/// @return sourceTokenAmountUsed source token amount used
function swapExternal(
address sourceToken,
address destToken,
address receiver,
address returnToSender,
uint256 sourceTokenAmount,
uint256 requiredDestTokenAmount,
bytes calldata swapData
)
external
payable
returns (
uint256 destTokenAmountReceived,
uint256 sourceTokenAmountUsed
);
/// @dev swap thru external integration using GAS
/// @param sourceToken source token address
/// @param destToken destintaion token address
/// @param receiver address to receive tokens
/// @param returnToSender TODO
/// @param gasTokenUser user address of the GAS token
/// @param sourceTokenAmount source token amount
/// @param requiredDestTokenAmount destination token amount
/// @param swapData TODO
/// @return destTokenAmountReceived destination token received
/// @return sourceTokenAmountUsed source token amount used
function swapExternalWithGasToken(
address sourceToken,
address destToken,
address receiver,
address returnToSender,
address gasTokenUser,
uint256 sourceTokenAmount,
uint256 requiredDestTokenAmount,
bytes calldata swapData
)
external
payable
returns (
uint256 destTokenAmountReceived,
uint256 sourceTokenAmountUsed
);
/// @dev calculate simulated return of swap
/// @param sourceToken source token address
/// @param destToken destination token address
/// @param sourceTokenAmount source token amount
/// @return amoun denominated in destination token
function getSwapExpectedReturn(
address sourceToken,
address destToken,
uint256 sourceTokenAmount
) external view returns (uint256);
function owner() external view returns (address);
function transferOwnership(address newOwner) external;
struct LoanParams {
bytes32 id;
bool active;
address owner;
address loanToken;
address collateralToken;
uint256 minInitialMargin;
uint256 maintenanceMargin;
uint256 maxLoanTerm;
}
struct LoanOpenData {
bytes32 loanId;
uint256 principal;
uint256 collateral;
}
enum LoanType {
All,
Margin,
NonMargin
}
struct LoanReturnData {
bytes32 loanId;
uint96 endTimestamp;
address loanToken;
address collateralToken;
uint256 principal;
uint256 collateral;
uint256 interestOwedPerDay;
uint256 interestDepositRemaining;
uint256 startRate;
uint256 startMargin;
uint256 maintenanceMargin;
uint256 currentMargin;
uint256 maxLoanTerm;
uint256 maxLiquidatable;
uint256 maxSeizable;
uint256 depositValueAsLoanToken;
uint256 depositValueAsCollateralToken;
}
enum FeeClaimType {
All,
Lending,
Trading,
Borrowing
}
struct Loan {
bytes32 id; // id of the loan
bytes32 loanParamsId; // the linked loan params id
bytes32 pendingTradesId; // the linked pending trades id
uint256 principal; // total borrowed amount outstanding
uint256 collateral; // total collateral escrowed for the loan
uint256 startTimestamp; // loan start time
uint256 endTimestamp; // for active loans, this is the expected loan end time, for in-active loans, is the actual (past) end time
uint256 startMargin; // initial margin when the loan opened
uint256 startRate; // reference rate when the loan opened for converting collateralToken to loanToken
address borrower; // borrower of this loan
address lender; // lender of this loan
bool active; // if false, the loan has been fully closed
}
struct LenderInterest {
uint256 principalTotal; // total borrowed amount outstanding of asset
uint256 owedPerDay; // interest owed per day for all loans of asset
uint256 owedTotal; // total interest owed for all loans of asset (assuming they go to full term)
uint256 paidTotal; // total interest paid so far for asset
uint256 updatedTimestamp; // last update
}
struct LoanInterest {
uint256 owedPerDay; // interest owed per day for loan
uint256 depositTotal; // total escrowed interest for loan
uint256 updatedTimestamp; // last update
}
}
/*
* @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;
}
}
/**
* @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 is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract StakingConstants {
address public constant BZRX = 0x56d811088235F11C8920698a204A5010a788f4b3;
address public constant vBZRX = 0xB72B31907C1C95F3650b64b2469e08EdACeE5e8F;
address public constant iBZRX = 0x18240BD9C07fA6156Ce3F3f61921cC82b2619157;
address public constant LPToken = 0xa30911e072A0C88D55B5D0A0984B66b0D04569d0; // sushiswap
address public constant LPTokenOld = 0xe26A220a341EAca116bDa64cF9D5638A935ae629; // balancer
IERC20 public constant curve3Crv = IERC20(0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490);
address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
address public constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
IUniswapV2Router public constant uniswapRouter = IUniswapV2Router(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); // sushiswap
ICurve3Pool public constant curve3pool = ICurve3Pool(0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7);
IBZx public constant bZx = IBZx(0xD8Ee69652E4e4838f2531732a46d1f7F584F0b7f);
uint256 public constant cliffDuration = 15768000; // 86400 * 365 * 0.5
uint256 public constant vestingDuration = 126144000; // 86400 * 365 * 4
uint256 internal constant vestingDurationAfterCliff = 110376000; // 86400 * 365 * 3.5
uint256 internal constant vestingStartTimestamp = 1594648800; // start_time
uint256 internal constant vestingCliffTimestamp = vestingStartTimestamp + cliffDuration;
uint256 internal constant vestingEndTimestamp = vestingStartTimestamp + vestingDuration;
uint256 internal constant _startingVBZRXBalance = 889389933e18; // 889,389,933 BZRX
uint256 public constant BZRXWeightStored = 1e18;
struct DelegatedTokens {
address user;
uint256 BZRX;
uint256 vBZRX;
uint256 iBZRX;
uint256 LPToken;
uint256 totalVotes;
}
event Stake(
address indexed user,
address indexed token,
address indexed delegate,
uint256 amount
);
event Unstake(
address indexed user,
address indexed token,
address indexed delegate,
uint256 amount
);
event AddRewards(
address indexed sender,
uint256 bzrxAmount,
uint256 stableCoinAmount
);
event Claim(
address indexed user,
uint256 bzrxAmount,
uint256 stableCoinAmount
);
event ChangeDelegate(
address indexed user,
address indexed oldDelegate,
address indexed newDelegate
);
event WithdrawFees(
address indexed sender
);
event ConvertFees(
address indexed sender,
uint256 bzrxOutput,
uint256 stableCoinOutput
);
event DistributeFees(
address indexed sender,
uint256 bzrxRewards,
uint256 stableCoinRewards
);
}
contract StakingUpgradeable is Ownable {
address public implementation;
}
contract StakingState is StakingUpgradeable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using EnumerableBytes32Set for EnumerableBytes32Set.Bytes32Set;
uint256 public constant initialCirculatingSupply = 1030000000e18 - 889389933e18;
address internal constant ZERO_ADDRESS = address(0);
bool public isPaused;
address public fundsWallet;
mapping(address => uint256) internal _totalSupplyPerToken; // token => value
mapping(address => mapping(address => uint256)) internal _balancesPerToken; // token => account => value
mapping(address => address) public delegate; // user => delegate
mapping(address => mapping(address => uint256)) public delegatedPerToken; // token => user => value
uint256 public bzrxPerTokenStored;
mapping(address => uint256) public bzrxRewardsPerTokenPaid; // user => value
mapping(address => uint256) public bzrxRewards; // user => value
mapping(address => uint256) public bzrxVesting; // user => value
uint256 public stableCoinPerTokenStored;
mapping(address => uint256) public stableCoinRewardsPerTokenPaid; // user => value
mapping(address => uint256) public stableCoinRewards; // user => value
mapping(address => uint256) public stableCoinVesting; // user => value
uint256 public vBZRXWeightStored;
uint256 public iBZRXWeightStored;
uint256 public LPTokenWeightStored;
EnumerableBytes32Set.Bytes32Set internal _delegatedSet;
uint256 public lastRewardsAddTime;
mapping(address => uint256) public vestingLastSync;
mapping(address => address[]) public swapPaths;
mapping(address => uint256) public stakingRewards;
uint256 public rewardPercent = 50e18;
uint256 public maxUniswapDisagreement = 3e18;
uint256 public maxCurveDisagreement = 3e18;
uint256 public callerRewardDivisor = 100;
address[] public currentFeeTokens;
struct ProposalState {
uint256 proposalTime;
uint256 iBZRXWeight;
uint256 lpBZRXBalance;
uint256 lpTotalSupply;
}
address public governor;
mapping(uint256 => ProposalState) internal _proposalState;
}
contract StakingV1_1 is StakingState, StakingConstants {
using MathUtil for uint256;
modifier onlyEOA() {
require(msg.sender == tx.origin, "unauthorized");
_;
}
modifier checkPause() {
require(!isPaused, "paused");
_;
}
function stake(
address[] calldata tokens,
uint256[] calldata values)
external
checkPause
updateRewards(msg.sender)
{
require(tokens.length == values.length, "count mismatch");
address token;
uint256 stakeAmount;
for (uint256 i = 0; i < tokens.length; i++) {
token = tokens[i];
require(token == BZRX || token == vBZRX || token == iBZRX || token == LPToken, "invalid token");
stakeAmount = values[i];
if (stakeAmount == 0) {
continue;
}
_balancesPerToken[token][msg.sender] = _balancesPerToken[token][msg.sender].add(stakeAmount);
_totalSupplyPerToken[token] = _totalSupplyPerToken[token].add(stakeAmount);
IERC20(token).safeTransferFrom(msg.sender, address(this), stakeAmount);
emit Stake(
msg.sender,
token,
msg.sender, //currentDelegate,
stakeAmount
);
}
}
function unstake(
address[] memory tokens,
uint256[] memory values)
public
checkPause
updateRewards(msg.sender)
{
require(tokens.length == values.length, "count mismatch");
address token;
uint256 unstakeAmount;
uint256 stakedAmount;
for (uint256 i = 0; i < tokens.length; i++) {
token = tokens[i];
require(token == BZRX || token == vBZRX || token == iBZRX || token == LPToken || token == LPTokenOld, "invalid token");
unstakeAmount = values[i];
stakedAmount = _balancesPerToken[token][msg.sender];
if (unstakeAmount == 0 || stakedAmount == 0) {
continue;
}
if (unstakeAmount > stakedAmount) {
unstakeAmount = stakedAmount;
}
_balancesPerToken[token][msg.sender] = stakedAmount - unstakeAmount; // will not overflow
_totalSupplyPerToken[token] = _totalSupplyPerToken[token] - unstakeAmount; // will not overflow
if (token == BZRX && IERC20(BZRX).balanceOf(address(this)) < unstakeAmount) {
// settle vested BZRX only if needed
IVestingToken(vBZRX).claim();
}
IERC20(token).safeTransfer(msg.sender, unstakeAmount);
emit Unstake(
msg.sender,
token,
msg.sender, //currentDelegate,
unstakeAmount
);
}
}
function claim(
bool restake)
external
checkPause
updateRewards(msg.sender)
returns (uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned)
{
return _claim(restake);
}
function claimBzrx()
external
checkPause
updateRewards(msg.sender)
returns (uint256 bzrxRewardsEarned)
{
bzrxRewardsEarned = _claimBzrx(false);
emit Claim(
msg.sender,
bzrxRewardsEarned,
0
);
}
function claim3Crv()
external
checkPause
updateRewards(msg.sender)
returns (uint256 stableCoinRewardsEarned)
{
stableCoinRewardsEarned = _claim3Crv();
emit Claim(
msg.sender,
0,
stableCoinRewardsEarned
);
}
function _claim(
bool restake)
internal
returns (uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned)
{
bzrxRewardsEarned = _claimBzrx(restake);
stableCoinRewardsEarned = _claim3Crv();
emit Claim(
msg.sender,
bzrxRewardsEarned,
stableCoinRewardsEarned
);
}
function _claimBzrx(
bool restake)
internal
returns (uint256 bzrxRewardsEarned)
{
bzrxRewardsEarned = bzrxRewards[msg.sender];
if (bzrxRewardsEarned != 0) {
bzrxRewards[msg.sender] = 0;
if (restake) {
_restakeBZRX(
msg.sender,
bzrxRewardsEarned
);
} else {
if (IERC20(BZRX).balanceOf(address(this)) < bzrxRewardsEarned) {
// settle vested BZRX only if needed
IVestingToken(vBZRX).claim();
}
IERC20(BZRX).transfer(msg.sender, bzrxRewardsEarned);
}
}
}
function _claim3Crv()
internal
returns (uint256 stableCoinRewardsEarned)
{
stableCoinRewardsEarned = stableCoinRewards[msg.sender];
if (stableCoinRewardsEarned != 0) {
stableCoinRewards[msg.sender] = 0;
curve3Crv.transfer(msg.sender, stableCoinRewardsEarned);
}
}
function _restakeBZRX(
address account,
uint256 amount)
internal
{
//address currentDelegate = delegate[account];
_balancesPerToken[BZRX][account] = _balancesPerToken[BZRX][account]
.add(amount);
_totalSupplyPerToken[BZRX] = _totalSupplyPerToken[BZRX]
.add(amount);
emit Stake(
account,
BZRX,
account, //currentDelegate,
amount
);
}
function exit()
public
// unstake() does a checkPause
{
address[] memory tokens = new address[](4);
uint256[] memory values = new uint256[](4);
tokens[0] = iBZRX;
tokens[1] = LPToken;
tokens[2] = vBZRX;
tokens[3] = BZRX;
values[0] = uint256(-1);
values[1] = uint256(-1);
values[2] = uint256(-1);
values[3] = uint256(-1);
unstake(tokens, values); // calls updateRewards
_claim(false);
}
modifier updateRewards(address account) {
uint256 _bzrxPerTokenStored = bzrxPerTokenStored;
uint256 _stableCoinPerTokenStored = stableCoinPerTokenStored;
(uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting) = _earned(
account,
_bzrxPerTokenStored,
_stableCoinPerTokenStored
);
bzrxRewardsPerTokenPaid[account] = _bzrxPerTokenStored;
stableCoinRewardsPerTokenPaid[account] = _stableCoinPerTokenStored;
// vesting amounts get updated before sync
bzrxVesting[account] = bzrxRewardsVesting;
stableCoinVesting[account] = stableCoinRewardsVesting;
(bzrxRewards[account], stableCoinRewards[account]) = _syncVesting(
account,
bzrxRewardsEarned,
stableCoinRewardsEarned,
bzrxRewardsVesting,
stableCoinRewardsVesting
);
vestingLastSync[account] = block.timestamp;
_;
}
function earned(
address account)
external
view
returns (uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting)
{
(bzrxRewardsEarned, stableCoinRewardsEarned, bzrxRewardsVesting, stableCoinRewardsVesting) = _earned(
account,
bzrxPerTokenStored,
stableCoinPerTokenStored
);
(bzrxRewardsEarned, stableCoinRewardsEarned) = _syncVesting(
account,
bzrxRewardsEarned,
stableCoinRewardsEarned,
bzrxRewardsVesting,
stableCoinRewardsVesting
);
// discount vesting amounts for vesting time
uint256 multiplier = vestedBalanceForAmount(
1e36,
0,
block.timestamp
);
bzrxRewardsVesting = bzrxRewardsVesting
.sub(bzrxRewardsVesting
.mul(multiplier)
.div(1e36)
);
stableCoinRewardsVesting = stableCoinRewardsVesting
.sub(stableCoinRewardsVesting
.mul(multiplier)
.div(1e36)
);
}
function _earned(
address account,
uint256 _bzrxPerToken,
uint256 _stableCoinPerToken)
internal
view
returns (uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting)
{
uint256 bzrxPerTokenUnpaid = _bzrxPerToken.sub(bzrxRewardsPerTokenPaid[account]);
uint256 stableCoinPerTokenUnpaid = _stableCoinPerToken.sub(stableCoinRewardsPerTokenPaid[account]);
bzrxRewardsEarned = bzrxRewards[account];
stableCoinRewardsEarned = stableCoinRewards[account];
bzrxRewardsVesting = bzrxVesting[account];
stableCoinRewardsVesting = stableCoinVesting[account];
if (bzrxPerTokenUnpaid != 0 || stableCoinPerTokenUnpaid != 0) {
uint256 value;
uint256 multiplier;
uint256 lastSync;
(uint256 vestedBalance, uint256 vestingBalance) = balanceOfStored(account);
value = vestedBalance
.mul(bzrxPerTokenUnpaid);
value /= 1e36;
bzrxRewardsEarned = value
.add(bzrxRewardsEarned);
value = vestedBalance
.mul(stableCoinPerTokenUnpaid);
value /= 1e36;
stableCoinRewardsEarned = value
.add(stableCoinRewardsEarned);
if (vestingBalance != 0 && bzrxPerTokenUnpaid != 0) {
// add new vesting amount for BZRX
value = vestingBalance
.mul(bzrxPerTokenUnpaid);
value /= 1e36;
bzrxRewardsVesting = bzrxRewardsVesting
.add(value);
// true up earned amount to vBZRX vesting schedule
lastSync = vestingLastSync[account];
multiplier = vestedBalanceForAmount(
1e36,
0,
lastSync
);
value = value
.mul(multiplier);
value /= 1e36;
bzrxRewardsEarned = bzrxRewardsEarned
.add(value);
}
if (vestingBalance != 0 && stableCoinPerTokenUnpaid != 0) {
// add new vesting amount for 3crv
value = vestingBalance
.mul(stableCoinPerTokenUnpaid);
value /= 1e36;
stableCoinRewardsVesting = stableCoinRewardsVesting
.add(value);
// true up earned amount to vBZRX vesting schedule
if (lastSync == 0) {
lastSync = vestingLastSync[account];
multiplier = vestedBalanceForAmount(
1e36,
0,
lastSync
);
}
value = value
.mul(multiplier);
value /= 1e36;
stableCoinRewardsEarned = stableCoinRewardsEarned
.add(value);
}
}
}
function _syncVesting(
address account,
uint256 bzrxRewardsEarned,
uint256 stableCoinRewardsEarned,
uint256 bzrxRewardsVesting,
uint256 stableCoinRewardsVesting)
internal
view
returns (uint256, uint256)
{
uint256 lastVestingSync = vestingLastSync[account];
if (lastVestingSync != block.timestamp) {
uint256 rewardsVested;
uint256 multiplier = vestedBalanceForAmount(
1e36,
lastVestingSync,
block.timestamp
);
if (bzrxRewardsVesting != 0) {
rewardsVested = bzrxRewardsVesting
.mul(multiplier)
.div(1e36);
bzrxRewardsEarned += rewardsVested;
}
if (stableCoinRewardsVesting != 0) {
rewardsVested = stableCoinRewardsVesting
.mul(multiplier)
.div(1e36);
stableCoinRewardsEarned += rewardsVested;
}
uint256 vBZRXBalance = _balancesPerToken[vBZRX][account];
if (vBZRXBalance != 0) {
// add vested BZRX to rewards balance
rewardsVested = vBZRXBalance
.mul(multiplier)
.div(1e36);
bzrxRewardsEarned += rewardsVested;
}
}
return (bzrxRewardsEarned, stableCoinRewardsEarned);
}
// note: anyone can contribute rewards to the contract
function addDirectRewards(
address[] calldata accounts,
uint256[] calldata bzrxAmounts,
uint256[] calldata stableCoinAmounts)
external
checkPause
returns (uint256 bzrxTotal, uint256 stableCoinTotal)
{
require(accounts.length == bzrxAmounts.length && accounts.length == stableCoinAmounts.length, "count mismatch");
for (uint256 i = 0; i < accounts.length; i++) {
bzrxRewards[accounts[i]] = bzrxRewards[accounts[i]].add(bzrxAmounts[i]);
bzrxTotal = bzrxTotal.add(bzrxAmounts[i]);
stableCoinRewards[accounts[i]] = stableCoinRewards[accounts[i]].add(stableCoinAmounts[i]);
stableCoinTotal = stableCoinTotal.add(stableCoinAmounts[i]);
}
if (bzrxTotal != 0) {
IERC20(BZRX).transferFrom(msg.sender, address(this), bzrxTotal);
}
if (stableCoinTotal != 0) {
curve3Crv.transferFrom(msg.sender, address(this), stableCoinTotal);
}
}
// note: anyone can contribute rewards to the contract
function addRewards(
uint256 newBZRX,
uint256 newStableCoin)
external
checkPause
{
if (newBZRX != 0 || newStableCoin != 0) {
_addRewards(newBZRX, newStableCoin);
if (newBZRX != 0) {
IERC20(BZRX).transferFrom(msg.sender, address(this), newBZRX);
}
if (newStableCoin != 0) {
curve3Crv.transferFrom(msg.sender, address(this), newStableCoin);
}
}
}
function _addRewards(
uint256 newBZRX,
uint256 newStableCoin)
internal
{
(vBZRXWeightStored, iBZRXWeightStored, LPTokenWeightStored) = getVariableWeights();
uint256 totalTokens = totalSupplyStored();
require(totalTokens != 0, "nothing staked");
bzrxPerTokenStored = newBZRX
.mul(1e36)
.div(totalTokens)
.add(bzrxPerTokenStored);
stableCoinPerTokenStored = newStableCoin
.mul(1e36)
.div(totalTokens)
.add(stableCoinPerTokenStored);
lastRewardsAddTime = block.timestamp;
emit AddRewards(
msg.sender,
newBZRX,
newStableCoin
);
}
function getVariableWeights()
public
view
returns (uint256 vBZRXWeight, uint256 iBZRXWeight, uint256 LPTokenWeight)
{
uint256 totalVested = vestedBalanceForAmount(
_startingVBZRXBalance,
0,
block.timestamp
);
vBZRXWeight = SafeMath.mul(_startingVBZRXBalance - totalVested, 1e18) // overflow not possible
.div(_startingVBZRXBalance);
iBZRXWeight = _calcIBZRXWeight();
uint256 lpTokenSupply = _totalSupplyPerToken[LPToken];
if (lpTokenSupply != 0) {
// staked LP tokens are assumed to represent the total unstaked supply (circulated supply - staked BZRX)
uint256 normalizedLPTokenSupply = initialCirculatingSupply +
totalVested -
_totalSupplyPerToken[BZRX];
LPTokenWeight = normalizedLPTokenSupply
.mul(1e18)
.div(lpTokenSupply);
}
}
function _calcIBZRXWeight()
internal
view
returns (uint256)
{
return IERC20(BZRX).balanceOf(iBZRX)
.mul(1e50)
.div(IERC20(iBZRX).totalSupply());
}
function balanceOfByAsset(
address token,
address account)
public
view
returns (uint256 balance)
{
balance = _balancesPerToken[token][account];
}
function balanceOfByAssets(
address account)
external
view
returns (
uint256 bzrxBalance,
uint256 iBZRXBalance,
uint256 vBZRXBalance,
uint256 LPTokenBalance,
uint256 LPTokenBalanceOld
)
{
return (
balanceOfByAsset(BZRX, account),
balanceOfByAsset(iBZRX, account),
balanceOfByAsset(vBZRX, account),
balanceOfByAsset(LPToken, account),
balanceOfByAsset(LPTokenOld, account)
);
}
function balanceOfStored(
address account)
public
view
returns (uint256 vestedBalance, uint256 vestingBalance)
{
uint256 balance = _balancesPerToken[vBZRX][account];
if (balance != 0) {
vestingBalance = _balancesPerToken[vBZRX][account]
.mul(vBZRXWeightStored)
.div(1e18);
}
vestedBalance = _balancesPerToken[BZRX][account];
balance = _balancesPerToken[iBZRX][account];
if (balance != 0) {
vestedBalance = balance
.mul(iBZRXWeightStored)
.div(1e50)
.add(vestedBalance);
}
balance = _balancesPerToken[LPToken][account];
if (balance != 0) {
vestedBalance = balance
.mul(LPTokenWeightStored)
.div(1e18)
.add(vestedBalance);
}
}
function totalSupplyByAsset(
address token)
external
view
returns (uint256)
{
return _totalSupplyPerToken[token];
}
function totalSupplyStored()
public
view
returns (uint256 supply)
{
supply = _totalSupplyPerToken[vBZRX]
.mul(vBZRXWeightStored)
.div(1e18);
supply = _totalSupplyPerToken[BZRX]
.add(supply);
supply = _totalSupplyPerToken[iBZRX]
.mul(iBZRXWeightStored)
.div(1e50)
.add(supply);
supply = _totalSupplyPerToken[LPToken]
.mul(LPTokenWeightStored)
.div(1e18)
.add(supply);
}
function vestedBalanceForAmount(
uint256 tokenBalance,
uint256 lastUpdate,
uint256 vestingEndTime)
public
view
returns (uint256 vested)
{
vestingEndTime = vestingEndTime.min256(block.timestamp);
if (vestingEndTime > lastUpdate) {
if (vestingEndTime <= vestingCliffTimestamp ||
lastUpdate >= vestingEndTimestamp) {
// time cannot be before vesting starts
// OR all vested token has already been claimed
return 0;
}
if (lastUpdate < vestingCliffTimestamp) {
// vesting starts at the cliff timestamp
lastUpdate = vestingCliffTimestamp;
}
if (vestingEndTime > vestingEndTimestamp) {
// vesting ends at the end timestamp
vestingEndTime = vestingEndTimestamp;
}
uint256 timeSinceClaim = vestingEndTime.sub(lastUpdate);
vested = tokenBalance.mul(timeSinceClaim) / vestingDurationAfterCliff; // will never divide by 0
}
}
// Governance Logic //
function votingBalanceOf(
address account,
uint256 proposalId)
public
view
returns (uint256 totalVotes)
{
return _votingBalanceOf(account, _proposalState[proposalId]);
}
function votingBalanceOfNow(
address account)
public
view
returns (uint256 totalVotes)
{
return _votingBalanceOf(account, _getProposalState());
}
function _setProposalVals(
address account,
uint256 proposalId)
public
returns (uint256)
{
require(msg.sender == governor, "unauthorized");
require(_proposalState[proposalId].proposalTime == 0, "proposal exists");
ProposalState memory newProposal = _getProposalState();
_proposalState[proposalId] = newProposal;
return _votingBalanceOf(account, newProposal);
}
function _getProposalState()
internal
view
returns (ProposalState memory)
{
return ProposalState({
proposalTime: block.timestamp - 1,
iBZRXWeight: _calcIBZRXWeight(),
lpBZRXBalance: IERC20(BZRX).balanceOf(LPToken),
lpTotalSupply: IERC20(LPToken).totalSupply()
});
}
function _votingBalanceOf(
address account,
ProposalState memory proposal)
internal
view
returns (uint256 totalVotes)
{
uint256 _vestingLastSync = vestingLastSync[account];
if (proposal.proposalTime == 0 || _vestingLastSync > proposal.proposalTime - 1) {
return 0;
}
uint256 _vBZRXBalance = _balancesPerToken[vBZRX][account];
if (_vBZRXBalance != 0) {
// staked vBZRX is prorated based on total vested
totalVotes = _vBZRXBalance
.mul(_startingVBZRXBalance -
vestedBalanceForAmount( // overflow not possible
_startingVBZRXBalance,
0,
proposal.proposalTime
)
).div(_startingVBZRXBalance);
// user is attributed a staked balance of vested BZRX, from their last update to the present
totalVotes = vestedBalanceForAmount(
_vBZRXBalance,
_vestingLastSync,
proposal.proposalTime
).add(totalVotes);
}
totalVotes = _balancesPerToken[BZRX][account]
.add(bzrxRewards[account]) // unclaimed BZRX rewards count as votes
.add(totalVotes);
totalVotes = _balancesPerToken[iBZRX][account]
.mul(proposal.iBZRXWeight)
.div(1e50)
.add(totalVotes);
// LPToken votes are measured based on amount of underlying BZRX staked
totalVotes = proposal.lpBZRXBalance
.mul(_balancesPerToken[LPToken][account])
.div(proposal.lpTotalSupply)
.add(totalVotes);
}
// Fee Conversion Logic //
function sweepFees()
public
// sweepFeesByAsset() does checkPause
returns (uint256 bzrxRewards, uint256 crv3Rewards)
{
return sweepFeesByAsset(currentFeeTokens);
}
function sweepFeesByAsset(
address[] memory assets)
public
checkPause
onlyEOA
returns (uint256 bzrxRewards, uint256 crv3Rewards)
{
uint256[] memory amounts = _withdrawFees(assets);
_convertFees(assets, amounts);
(bzrxRewards, crv3Rewards) = _distributeFees();
}
function _withdrawFees(
address[] memory assets)
internal
returns (uint256[] memory)
{
uint256[] memory amounts = bZx.withdrawFees(assets, address(this), IBZx.FeeClaimType.All);
for (uint256 i = 0; i < assets.length; i++) {
stakingRewards[assets[i]] = stakingRewards[assets[i]]
.add(amounts[i]);
}
emit WithdrawFees(
msg.sender
);
return amounts;
}
function _convertFees(
address[] memory assets,
uint256[] memory amounts)
internal
returns (uint256 bzrxOutput, uint256 crv3Output)
{
require(assets.length == amounts.length, "count mismatch");
IPriceFeeds priceFeeds = IPriceFeeds(bZx.priceFeeds());
(uint256 bzrxRate,) = priceFeeds.queryRate(
BZRX,
WETH
);
uint256 maxDisagreement = maxUniswapDisagreement;
address asset;
uint256 daiAmount;
uint256 usdcAmount;
uint256 usdtAmount;
for (uint256 i = 0; i < assets.length; i++) {
asset = assets[i];
if (asset == BZRX) {
continue;
} else if (asset == DAI) {
daiAmount = daiAmount.add(amounts[i]);
continue;
} else if (asset == USDC) {
usdcAmount = usdcAmount.add(amounts[i]);
continue;
} else if (asset == USDT) {
usdtAmount = usdtAmount.add(amounts[i]);
continue;
}
if (amounts[i] != 0) {
bzrxOutput += _convertFeeWithUniswap(asset, amounts[i], priceFeeds, bzrxRate, maxDisagreement);
}
}
if (bzrxOutput != 0) {
stakingRewards[BZRX] += bzrxOutput;
}
if (daiAmount != 0 || usdcAmount != 0 || usdtAmount != 0) {
crv3Output = _convertFeesWithCurve(
daiAmount,
usdcAmount,
usdtAmount
);
stakingRewards[address(curve3Crv)] += crv3Output;
}
emit ConvertFees(
msg.sender,
bzrxOutput,
crv3Output
);
}
function _distributeFees()
internal
returns (uint256 bzrxRewards, uint256 crv3Rewards)
{
bzrxRewards = stakingRewards[BZRX];
crv3Rewards = stakingRewards[address(curve3Crv)];
if (bzrxRewards != 0 || crv3Rewards != 0) {
address _fundsWallet = fundsWallet;
uint256 rewardAmount;
uint256 callerReward;
if (bzrxRewards != 0) {
stakingRewards[BZRX] = 0;
rewardAmount = bzrxRewards
.mul(rewardPercent)
.div(1e20);
IERC20(BZRX).transfer(
_fundsWallet,
bzrxRewards - rewardAmount
);
bzrxRewards = rewardAmount;
callerReward = bzrxRewards / callerRewardDivisor;
IERC20(BZRX).transfer(
msg.sender,
callerReward
);
bzrxRewards = bzrxRewards
.sub(callerReward);
}
if (crv3Rewards != 0) {
stakingRewards[address(curve3Crv)] = 0;
rewardAmount = crv3Rewards
.mul(rewardPercent)
.div(1e20);
curve3Crv.transfer(
_fundsWallet,
crv3Rewards - rewardAmount
);
crv3Rewards = rewardAmount;
callerReward = crv3Rewards / callerRewardDivisor;
curve3Crv.transfer(
msg.sender,
callerReward
);
crv3Rewards = crv3Rewards
.sub(callerReward);
}
_addRewards(bzrxRewards, crv3Rewards);
}
emit DistributeFees(
msg.sender,
bzrxRewards,
crv3Rewards
);
}
function _convertFeeWithUniswap(
address asset,
uint256 amount,
IPriceFeeds priceFeeds,
uint256 bzrxRate,
uint256 maxDisagreement)
internal
returns (uint256 returnAmount)
{
uint256 stakingReward = stakingRewards[asset];
if (stakingReward != 0) {
if (amount > stakingReward) {
amount = stakingReward;
}
stakingRewards[asset] = stakingReward
.sub(amount);
uint256[] memory amounts = uniswapRouter.swapExactTokensForTokens(
amount,
1, // amountOutMin
swapPaths[asset],
address(this),
block.timestamp
);
returnAmount = amounts[amounts.length - 1];
// will revert if disagreement found
_checkUniDisagreement(
asset,
amount,
returnAmount,
priceFeeds,
bzrxRate,
maxDisagreement
);
}
}
function _convertFeesWithCurve(
uint256 daiAmount,
uint256 usdcAmount,
uint256 usdtAmount)
internal
returns (uint256 returnAmount)
{
uint256[3] memory curveAmounts;
uint256 curveTotal;
uint256 stakingReward;
if (daiAmount != 0) {
stakingReward = stakingRewards[DAI];
if (stakingReward != 0) {
if (daiAmount > stakingReward) {
daiAmount = stakingReward;
}
stakingRewards[DAI] = stakingReward
.sub(daiAmount);
curveAmounts[0] = daiAmount;
curveTotal = daiAmount;
}
}
if (usdcAmount != 0) {
stakingReward = stakingRewards[USDC];
if (stakingReward != 0) {
if (usdcAmount > stakingReward) {
usdcAmount = stakingReward;
}
stakingRewards[USDC] = stakingReward
.sub(usdcAmount);
curveAmounts[1] = usdcAmount;
curveTotal = curveTotal.add(usdcAmount.mul(1e12)); // normalize to 18 decimals
}
}
if (usdtAmount != 0) {
stakingReward = stakingRewards[USDT];
if (stakingReward != 0) {
if (usdtAmount > stakingReward) {
usdtAmount = stakingReward;
}
stakingRewards[USDT] = stakingReward
.sub(usdtAmount);
curveAmounts[2] = usdtAmount;
curveTotal = curveTotal.add(usdtAmount.mul(1e12)); // normalize to 18 decimals
}
}
uint256 beforeBalance = curve3Crv.balanceOf(address(this));
curve3pool.add_liquidity(curveAmounts, 0);
returnAmount = curve3Crv.balanceOf(address(this)) - beforeBalance;
// will revert if disagreement found
_checkCurveDisagreement(
curveTotal,
returnAmount,
maxCurveDisagreement
);
}
function _checkUniDisagreement(
address asset,
uint256 assetAmount,
uint256 bzrxAmount,
IPriceFeeds priceFeeds,
uint256 bzrxRate,
uint256 maxDisagreement)
internal
view
{
(uint256 rate, uint256 precision) = priceFeeds.queryRate(
asset,
WETH
);
rate = rate
.mul(1e36)
.div(precision)
.div(bzrxRate);
uint256 sourceToDestSwapRate = bzrxAmount
.mul(1e18)
.div(assetAmount);
uint256 spreadValue = sourceToDestSwapRate > rate ?
sourceToDestSwapRate - rate :
rate - sourceToDestSwapRate;
if (spreadValue != 0) {
spreadValue = spreadValue
.mul(1e20)
.div(sourceToDestSwapRate);
require(
spreadValue <= maxDisagreement,
"uniswap price disagreement"
);
}
}
function _checkCurveDisagreement(
uint256 sendAmount, // deposit tokens
uint256 actualReturn, // returned lp token
uint256 maxDisagreement)
internal
view
{
uint256 expectedReturn = sendAmount
.mul(1e18)
.div(curve3pool.get_virtual_price());
uint256 spreadValue = actualReturn > expectedReturn ?
actualReturn - expectedReturn :
expectedReturn - actualReturn;
if (spreadValue != 0) {
spreadValue = spreadValue
.mul(1e20)
.div(actualReturn);
require(
spreadValue <= maxDisagreement,
"curve price disagreement"
);
}
}
// OnlyOwner functions
function togglePause(
bool _isPaused)
external
onlyOwner
{
isPaused = _isPaused;
}
function setFundsWallet(
address _fundsWallet)
external
onlyOwner
{
fundsWallet = _fundsWallet;
}
function setGovernor(
address _governor)
external
onlyOwner
{
governor = _governor;
}
function setFeeTokens(
address[] calldata tokens)
external
onlyOwner
{
currentFeeTokens = tokens;
}
// path should start with the asset to swap and end with BZRX
// only one path allowed per asset
// ex: asset -> WETH -> BZRX
function setPaths(
address[][] calldata paths)
external
onlyOwner
{
address[] memory path;
for (uint256 i = 0; i < paths.length; i++) {
path = paths[i];
require(path.length >= 2 &&
path[0] != path[path.length - 1] &&
path[path.length - 1] == BZRX,
"invalid path"
);
// check that the path exists
uint256[] memory amountsOut = uniswapRouter.getAmountsOut(1e10, path);
require(amountsOut[amountsOut.length - 1] != 0, "path does not exist");
swapPaths[path[0]] = path;
IERC20(path[0]).safeApprove(address(uniswapRouter), 0);
IERC20(path[0]).safeApprove(address(uniswapRouter), uint256(-1));
}
}
function setRewardPercent(
uint256 _rewardPercent)
external
onlyOwner
{
require(_rewardPercent <= 1e20, "value too high");
rewardPercent = _rewardPercent;
}
function setMaxUniswapDisagreement(
uint256 _maxUniswapDisagreement)
external
onlyOwner
{
require(_maxUniswapDisagreement != 0, "invalid param");
maxUniswapDisagreement = _maxUniswapDisagreement;
}
function setMaxCurveDisagreement(
uint256 _maxCurveDisagreement)
external
onlyOwner
{
require(_maxCurveDisagreement != 0, "invalid param");
maxCurveDisagreement = _maxCurveDisagreement;
}
function setCallerRewardDivisor(
uint256 _callerRewardDivisor)
external
onlyOwner
{
require(_callerRewardDivisor != 0, "invalid param");
callerRewardDivisor = _callerRewardDivisor;
}
}
|
path should start with the asset to swap and end with BZRX only one path allowed per asset ex: asset -> WETH -> BZRX check that the path exists
|
function setPaths(
address[][] calldata paths)
external
onlyOwner
{
address[] memory path;
for (uint256 i = 0; i < paths.length; i++) {
path = paths[i];
require(path.length >= 2 &&
path[0] != path[path.length - 1] &&
path[path.length - 1] == BZRX,
"invalid path"
);
uint256[] memory amountsOut = uniswapRouter.getAmountsOut(1e10, path);
require(amountsOut[amountsOut.length - 1] != 0, "path does not exist");
swapPaths[path[0]] = path;
IERC20(path[0]).safeApprove(address(uniswapRouter), 0);
IERC20(path[0]).safeApprove(address(uniswapRouter), uint256(-1));
}
}
| 605,468
|
./full_match/1/0x864a1CBB53b9Dea3691a6974B456088C2771DcAd/sources/browser/Bar.sol
|
Internal view function to get all of the extra data for a single pool Only calculate with fixed apr after the Soft Launch User pool informationpoolMetadata[14] = _pendingUni(_pid, _user);poolMetadata[16] = _userInfo.uniClaimed;
|
function _getPoolMetadataFor(uint256 _pid, address _user, uint256 _boogiePrice) internal view returns (uint[17] memory poolMetadata) {
PoolInfo memory pool = poolInfo[_pid];
uint256 totalSupply;
uint256 totalLPSupply;
uint256 stakedLPSupply;
uint256 tokenPrice;
uint256 lpTokenPrice;
uint256 totalLiquidityValue;
uint256 boogiePerBlock;
if (_pid != 0 || boogiePoolActive == true) {
totalSupply = pool.token.totalSupply();
totalLPSupply = pool.lpToken.totalSupply();
stakedLPSupply = _getPoolSupply(_pid);
tokenPrice = 10**uint256(pool.token.decimals()) * weth.balanceOf(address(pool.lpToken)) / pool.token.balanceOf(address(pool.lpToken));
lpTokenPrice = 10**18 * 2 * weth.balanceOf(address(pool.lpToken)) / totalLPSupply;
totalLiquidityValue = stakedLPSupply * lpTokenPrice / 1e18;
}
if (block.number >= startBlock + SOFT_LAUNCH_DURATION) {
boogiePerBlock = ((pool.apr * 1e18 * totalLiquidityValue / _boogiePrice) / APPROX_BLOCKS_PER_YEAR) / 100;
if (_pid != 0) {
boogiePerBlock = SOFT_LAUNCH_BOOGIE_PER_BLOCK;
boogiePerBlock = 25 * SOFT_LAUNCH_BOOGIE_PER_BLOCK;
}
}
poolMetadata[1] = totalLPSupply;
poolMetadata[2] = stakedLPSupply;
poolMetadata[3] = tokenPrice;
poolMetadata[4] = lpTokenPrice;
poolMetadata[5] = totalLiquidityValue;
poolMetadata[6] = boogiePerBlock;
poolMetadata[7] = pool.token.decimals();
if (_pid != 0 || boogiePoolActive == true) {
UserInfo memory _userInfo = userInfo[_pid][_user];
poolMetadata[8] = pool.token.balanceOf(_user);
poolMetadata[9] = pool.token.allowance(_user, address(this));
poolMetadata[10] = pool.lpToken.balanceOf(_user);
poolMetadata[11] = pool.lpToken.allowance(_user, address(this));
poolMetadata[12] = _userInfo.staked;
poolMetadata[13] = _pendingBoogie(_pid, _user);
poolMetadata[15] = _userInfo.claimed;
}
}
| 4,927,156
|
//Address: 0x2de60f36bb208b5c96acb36d4a49aad3e2be0627
//Contract name: GJCICO
//Balance: 0 Ether
//Verification Date: 10/27/2017
//Transacion Count: 824
// CODE STARTS HERE
pragma solidity ^0.4.15;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract 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 public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
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();
}
}
contract GJCICO is Pausable{
using SafeMath for uint256;
//Gas/GWei
uint constant public minContribAmount = 0.01 ether;
// The token being sold
GJCToken public token;
uint256 constant public tokenDecimals = 18;
// The vesting contract
TokenVesting public vesting;
uint256 constant public VESTING_TIMES = 4;
uint256 constant public DURATION_PER_VESTING = 52 weeks;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
// need to be enabled to allow investor to participate in the ico
bool public icoEnabled;
// address where funds are collected
address public multisignWallet;
// amount of raised money in wei
uint256 public weiRaised;
// totalSupply
uint256 constant public totalSupply = 100000000 * (10 ** tokenDecimals);
//pre sale cap
uint256 constant public preSaleCap = 10000000 * (10 ** tokenDecimals);
//sale cap
uint256 constant public initialICOCap = 60000000 * (10 ** tokenDecimals);
//founder share
uint256 constant public tokensForFounder = 10000000 * (10 ** tokenDecimals);
//dev team share
uint256 constant public tokensForDevteam = 10000000 * (10 ** tokenDecimals);
//Partners share
uint256 constant public tokensForPartners = 5000000 * (10 ** tokenDecimals);
//Charity share
uint256 constant public tokensForCharity = 3000000 * (10 ** tokenDecimals);
//Bounty share
uint256 constant public tokensForBounty = 2000000 * (10 ** tokenDecimals);
//Sold presale tokens
uint256 public soldPreSaleTokens;
uint256 public sentPreSaleTokens;
//ICO tokens
//Is calcluated as: initialICOCap + preSaleCap - soldPreSaleTokens
uint256 public icoCap;
uint256 public icoSoldTokens;
bool public icoEnded = false;
//Sale rates
uint256 constant public RATE_FOR_WEEK1 = 525;
uint256 constant public RATE_FOR_WEEK2 = 455;
uint256 constant public RATE_FOR_WEEK3 = 420;
uint256 constant public RATE_NO_DISCOUNT = 350;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function GJCICO(address _multisignWallet) {
require(_multisignWallet != address(0));
token = createTokenContract();
//send all dao tokens to multiwallet
uint256 tokensToDao = tokensForDevteam.add(tokensForPartners).add(tokensForBounty).add(tokensForCharity);
multisignWallet = _multisignWallet;
token.transfer(multisignWallet, tokensToDao);
}
function createVestingForFounder(address founderAddress) external onlyOwner(){
require(founderAddress != address(0));
//create only once
require(address(vesting) == address(0));
vesting = createTokenVestingContract(address(token));
// create vesting schema for founders from now, total token amount is divided in 4 periods of 12 months each
vesting.createVestingByDurationAndSplits(founderAddress, tokensForFounder, now, DURATION_PER_VESTING, VESTING_TIMES);
//send tokens to vesting contracts
token.transfer(address(vesting), tokensForFounder);
}
//
// Token related operations
//
// creates the token to be sold.
function createTokenContract() internal returns (GJCToken) {
return new GJCToken();
}
// creates the token to be sold.
// override this method to have crowdsale of a specific mintable token.
function createTokenVestingContract(address tokenAddress) internal returns (TokenVesting) {
require(address(token) != address(0));
return new TokenVesting(tokenAddress);
}
// enable token tranferability
function enableTokenTransferability() external onlyOwner {
require(token != address(0));
token.unpause();
}
// disable token tranferability
function disableTokenTransferability() external onlyOwner {
require(token != address(0));
token.pause();
}
//
// Presale related operations
//
// set total pre sale sold token
// can not be changed once the ico is enabled
// Ico cap is determined by SaleCap + PreSaleCap - soldPreSaleTokens
function setSoldPreSaleTokens(uint256 _soldPreSaleTokens) external onlyOwner{
require(!icoEnabled);
require(_soldPreSaleTokens <= preSaleCap);
soldPreSaleTokens = _soldPreSaleTokens;
}
// transfer pre sale tokend to investors
// soldPreSaleTokens need to be set beforehand, and bigger than 0
// the total amount to tranfered need to be less or equal to soldPreSaleTokens
function transferPreSaleTokens(uint256 tokens, address beneficiary) external onlyOwner {
require(beneficiary != address(0));
require(soldPreSaleTokens > 0);
uint256 newSentPreSaleTokens = sentPreSaleTokens.add(tokens);
require(newSentPreSaleTokens <= soldPreSaleTokens);
sentPreSaleTokens = newSentPreSaleTokens;
token.transfer(beneficiary, tokens);
}
//
// ICO related operations
//
// set multisign wallet
function setMultisignWallet(address _multisignWallet) external onlyOwner{
// need to be set before the ico start
require(!icoEnabled || now < startTime);
require(_multisignWallet != address(0));
multisignWallet = _multisignWallet;
}
// delegate vesting contract owner
function delegateVestingContractOwner(address newOwner) external onlyOwner{
vesting.transferOwnership(newOwner);
}
// set contribution dates
function setContributionDates(uint256 _startTime, uint256 _endTime) external onlyOwner{
require(!icoEnabled);
require(_startTime >= now);
require(_endTime >= _startTime);
startTime = _startTime;
endTime = _endTime;
}
// enable ICO, need to be true to actually start ico
// multisign wallet need to be set, because once ico started, invested funds is transfered to this address
// once ico is enabled, following parameters can not be changed anymore:
// startTime, endTime, soldPreSaleTokens
function enableICO() external onlyOwner{
require(startTime >= now);
require(multisignWallet != address(0));
icoEnabled = true;
icoCap = initialICOCap.add(preSaleCap).sub(soldPreSaleTokens);
}
// fallback function can be used to buy tokens
function () payable whenNotPaused {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) public payable whenNotPaused {
require(beneficiary != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 returnWeiAmount;
// calculate token amount to be created
uint rate = getRate();
assert(rate > 0);
uint256 tokens = weiAmount.mul(rate);
uint256 newIcoSoldTokens = icoSoldTokens.add(tokens);
if (newIcoSoldTokens > icoCap) {
newIcoSoldTokens = icoCap;
tokens = icoCap.sub(icoSoldTokens);
uint256 newWeiAmount = tokens.div(rate);
returnWeiAmount = weiAmount.sub(newWeiAmount);
weiAmount = newWeiAmount;
}
// update state
weiRaised = weiRaised.add(weiAmount);
token.transfer(beneficiary, tokens);
icoSoldTokens = newIcoSoldTokens;
if (returnWeiAmount > 0){
msg.sender.transfer(returnWeiAmount);
}
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
// send ether to the fund collection wallet
function forwardFunds() internal {
multisignWallet.transfer(this.balance);
}
// unsold ico tokens transfer automatically in endIco
// function transferUnsoldIcoTokens() onlyOwner {
// require(hasEnded());
// require(icoSoldTokens < icoCap);
// uint256 unsoldTokens = icoCap.sub(icoSoldTokens);
// token.transfer(multisignWallet, unsoldTokens);
//}
// @return true if the transaction can buy tokens
function validPurchase() internal constant returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonMinimumPurchase = msg.value >= minContribAmount;
bool icoTokensAvailable = icoSoldTokens < icoCap;
return !icoEnded && icoEnabled && withinPeriod && nonMinimumPurchase && icoTokensAvailable;
}
// end ico by owner, not really needed in normal situation
function endIco() external onlyOwner {
require(!icoEnded);
icoEnded = true;
// send unsold tokens to multi-sign wallet
uint256 unsoldTokens = icoCap.sub(icoSoldTokens);
token.transfer(multisignWallet, unsoldTokens);
}
// @return true if crowdsale event has ended
function hasEnded() public constant returns (bool) {
return (icoEnded || icoSoldTokens >= icoCap || now > endTime);
}
function getRate() public constant returns(uint){
require(now >= startTime);
if (now < startTime.add(1 weeks)){
// week 1
return RATE_FOR_WEEK1;
}else if (now < startTime.add(2 weeks)){
// week 2
return RATE_FOR_WEEK2;
}else if (now < startTime.add(3 weeks)){
// week 3
return RATE_FOR_WEEK3;
}else if (now < endTime){
// no discount
return RATE_NO_DISCOUNT;
}
return 0;
}
// drain all eth for owner in an emergency situation
function drain() external onlyOwner {
owner.transfer(this.balance);
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
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 constant returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
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));
}
}
contract TokenVesting is Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20Basic;
ERC20Basic token;
// vesting
mapping (address => uint256) totalVestedAmount;
struct Vesting {
uint256 amount;
uint256 vestingDate;
}
address[] accountKeys;
mapping (address => Vesting[]) public vestingAccounts;
// events
event Vest(address indexed beneficiary, uint256 amount);
event VestingCreated(address indexed beneficiary, uint256 amount, uint256 vestingDate);
// modifiers here
modifier tokenSet() {
require(address(token) != address(0));
_;
}
// vesting constructor
function TokenVesting(address token_address){
require(token_address != address(0));
token = ERC20Basic(token_address);
}
// set vesting token address
function setVestingToken(address token_address) external onlyOwner {
require(token_address != address(0));
token = ERC20Basic(token_address);
}
// create vesting by introducing beneficiary addres, total token amount, start date, duration for each vest period and number of periods
function createVestingByDurationAndSplits(address user, uint256 total_amount, uint256 startDate, uint256 durationPerVesting, uint256 times) public onlyOwner tokenSet {
require(user != address(0));
require(startDate >= now);
require(times > 0);
require(durationPerVesting > 0);
uint256 vestingDate = startDate;
uint256 i;
uint256 amount = total_amount.div(times);
for (i = 0; i < times; i++) {
vestingDate = vestingDate.add(durationPerVesting);
if (vestingAccounts[user].length == 0){
accountKeys.push(user);
}
vestingAccounts[user].push(Vesting(amount, vestingDate));
VestingCreated(user, amount, vestingDate);
}
}
// get current user total granted token amount
function getVestingAmountByNow(address user) constant returns (uint256){
uint256 amount;
uint256 i;
for (i = 0; i < vestingAccounts[user].length; i++) {
if (vestingAccounts[user][i].vestingDate < now) {
amount = amount.add(vestingAccounts[user][i].amount);
}
}
}
// get user available vesting amount, total amount - received amount
function getAvailableVestingAmount(address user) constant returns (uint256){
uint256 amount;
amount = getVestingAmountByNow(user);
amount = amount.sub(totalVestedAmount[user]);
return amount;
}
// get list of vesting users address
function getAccountKeys(uint256 page) external constant returns (address[10]){
address[10] memory accountList;
uint256 i;
for (i=0 + page * 10; i<10; i++){
if (i < accountKeys.length){
accountList[i - page * 10] = accountKeys[i];
}
}
return accountList;
}
// vest
function vest() external tokenSet {
uint256 availableAmount = getAvailableVestingAmount(msg.sender);
require(availableAmount > 0);
totalVestedAmount[msg.sender] = totalVestedAmount[msg.sender].add(availableAmount);
token.transfer(msg.sender, availableAmount);
Vest(msg.sender, availableAmount);
}
// drain all eth and tokens to owner in an emergency situation
function drain() external onlyOwner {
owner.transfer(this.balance);
token.transfer(owner, this.balance);
}
}
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 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) public 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) public 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;
}
}
contract PausableToken is StandardToken, Pausable {
/**
* @dev modifier to allow actions only when the contract is not paused or
* the sender is the owner of the contract
*/
modifier whenNotPausedOrOwner() {
require(msg.sender == owner || !paused);
_;
}
function transfer(address _to, uint256 _value) public whenNotPausedOrOwner returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPausedOrOwner returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPausedOrOwner returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPausedOrOwner returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPausedOrOwner returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
contract GJCToken is PausableToken {
string constant public name = "GJC";
string constant public symbol = "GJC";
uint256 constant public decimals = 18;
uint256 constant TOKEN_UNIT = 10 ** uint256(decimals);
uint256 constant INITIAL_SUPPLY = 100000000 * TOKEN_UNIT;
function GJCToken() {
// Set untransferable by default to the token
paused = true;
// asign all tokens to the contract creator
totalSupply = INITIAL_SUPPLY;
Transfer(0x0, msg.sender, INITIAL_SUPPLY);
balances[msg.sender] = INITIAL_SUPPLY;
}
}
|
drain all eth and tokens to owner in an emergency situation
|
function drain() external onlyOwner {
owner.transfer(this.balance);
token.transfer(owner, this.balance);
}
| 6,457,534
|
./partial_match/1/0x1a32C09aE57EB02Ae0Db4522F6DF7b997a9a34EB/sources/NyanV2.sol
|
Override ERC20 transferFrom function with transfer fee. _sender Owner of the tokens being transferred. _recipient Recepient of the transfer. _amount Amount of tokens being transferred./
|
function transferFrom(address _sender, address _recipient, uint256 _amount) delegatedOnly public override returns(bool) {
if (hasExited[msg.sender]) {
require(!isExitPeriod);
}
return super.transferFrom(_sender, _recipient, _amount);
}
event UniswapAddressesSet(address factory, address router);
event LGEEndBlockSet(uint256 block);
event NyanxETHSupplied(address indexed user, uint256 nyanAmount, uint256 ETHAmount);
address public uniswapRouterV2;
address public uniswapFactory;
| 2,722,952
|
/**
* @title Rental
* @author Clément Lesaege - <clement@lesaege.com>
* Bug Bounties: This code hasn't undertaken a bug bounty program yet.
*/
pragma solidity ^0.4.15;
import "./TwoPartyArbitrable.sol";
/** @title Rental
* This is a a contract for rental agreement.
* This can be used to rent objects or properties.
* Party A is the renter. Party B is the owner.
* Party A put a deposit. If everything goes well, it will be given back.
* Otherwize parties can claim an amount of damages. If they disagree, the arbitrator will have to solve this dispute.
*/
contract Rental is TwoPartyArbitrable {
string constant RULING_OPTIONS = "Rule for party A (renter);Rule for Party B (owner)";
uint8 constant AMOUNT_OF_CHOICES = 2; // The number of ruling options available.
uint public amount; // Amount sent by party A.
uint public damagesClaimedByPartyA; // The amount party A agrees to pay to compensate damages.
uint public damagesClaimedByPartyB; // The amount party B claims to compensate damages.
/** @dev Constructor. Choose the arbitrator. Should be called by party A (the payer).
* @param _arbitrator The arbitrator of the contract.
* @param _timeout Time after which a party automatically loose a dispute.
* @param _partyB The owner.
* @param _arbitratorExtraData Extra data for the arbitrator.
* @param _metaEvidence Link to meta-evidence JSON.
*/
constructor(
Arbitrator _arbitrator,
uint _timeout,
address _partyB,
bytes _arbitratorExtraData,
string _metaEvidence
)
public
TwoPartyArbitrable(_arbitrator,_timeout,_partyB,AMOUNT_OF_CHOICES,_arbitratorExtraData, _metaEvidence)
payable
{
amount += msg.value;
}
/** @dev Claim an amount of damages.
* Must be called before the dispute is created.
* If the amount agreed is the same for both, pay it.
* @param _damages The amount asked or agreed to be paid.
*/
function claimDamages(uint _damages) public onlyParty {
// Make sure that parties can't change when a dispute already started.
require(status < Status.DisputeCreated, "The dispute has already been created.");
// Needed to avoid claiming 0 first and triggering an agreement. Use forfeitDeposit and unlockDeposit for the cases where 0 is claimed.
require(_damages != 0, "There must be damages.");
require(_damages <= amount, "Cannot claim more than balance."); // Make sure not to claim more than the contract has.
if (msg.sender == partyA)
damagesClaimedByPartyA = _damages;
else
damagesClaimedByPartyB = _damages;
if (damagesClaimedByPartyA==damagesClaimedByPartyB) { // If there is an agreement.
partyA.send((amount - damagesClaimedByPartyB) + partyAFee);
partyB.send(damagesClaimedByPartyB + partyBFee);
damagesClaimedByPartyA = 0;
damagesClaimedByPartyB = 0;
partyAFee = 0;
partyBFee = 0;
amount = 0;
status = Status.Resolved;
}
}
/** @dev Forfeit the deposit to party B.
* To be called if the good has been completely broken or that the property damages exceed the deposit.
*/
function forfeitDeposit() public onlyPartyA {
partyB.transfer(amount);
amount = 0;
}
/** @dev Unlock party A deposit. To be called if the good or property has been returned without damages.
*/
function unlockDeposit() public onlyPartyB {
partyA.transfer(amount);
amount = 0;
}
/** @dev Execute a ruling of a dispute. It reimburse the fee to the winning party.
* This need to be extended by contract inheriting from it.
* @param _disputeID ID of the dispute in the Arbitrator contract.
* @param _ruling Ruling given by the arbitrator. 1 : Rule for party A (renter). 2 : Rule for Party B (owner).
*/
function executeRuling(uint _disputeID, uint _ruling) internal {
super.executeRuling(_disputeID,_ruling);
if (_ruling == PARTY_A_WINS) {
partyA.send(amount - damagesClaimedByPartyA);
partyB.send(damagesClaimedByPartyA);
}
else if (_ruling == PARTY_B_WINS) {
partyA.send(amount - damagesClaimedByPartyB);
partyB.send(damagesClaimedByPartyB);
}
amount = 0;
damagesClaimedByPartyA = 0;
damagesClaimedByPartyB = 0;
}
}
|
Forfeit the deposit to party B. To be called if the good has been completely broken or that the property damages exceed the deposit./
|
function forfeitDeposit() public onlyPartyA {
partyB.transfer(amount);
amount = 0;
}
| 5,531,814
|
./full_match/80001/0xBd99517e1994226FB8124D37087A0b835829D593/sources/contracts/Portfolio.sol
|
Write function to update skill
|
function updateSkill(
uint256 _index,
string memory name,
uint _rating
) public onlyOwner {
require(_index < _skills.length, "Invalid index");
require(bytes(name).length > 0, "Name cannot be empty");
require(
_rating >= 1 && _rating <= 10,
"Rating must be between 1 and 10"
);
_skills[_index].name = name;
_skills[_index].rating = _rating;
}
| 5,572,185
|
./full_match/80001/0x18598e5E600537dc21FA0A5a337b81a294F86633/sources/contracts/AdventureERC721.sol
|
Admin-only ability to boot a token from all quests on an adventure. This ability is only unlocked in the event that an adventure has been unwhitelisted, as early exiting from quests can cause out of sync state between the ERC721 token contract and the adventure/quest.
|
function bootFromAllQuests(uint256 tokenId, address adventure) external onlyOwner onlyWhenRemovedFromWhitelist(adventure) {
_exitAllQuests(tokenId, adventure, true);
}
| 834,540
|
//Address: 0x99d439455991f7f4885f20c634c9a31918d366e5
//Contract name: RexToken
//Balance: 0 Ether
//Verification Date: 7/30/2017
//Transacion Count: 1044
// CODE STARTS HERE
pragma solidity ^0.4.11;
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value);
function approve(address spender, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract FinalizableToken {
bool public isFinalized = false;
}
contract BasicToken is FinalizableToken, 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) {
if (!isFinalized) revert();
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
}
/**
* @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];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) {
if (!isFinalized) revert();
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// if (_value > _allowance) throw;
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) {
// 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
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) revert();
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract SimpleToken is StandardToken {
string public name = "SimpleToken";
string public symbol = "SIM";
uint256 public decimals = 18;
uint256 public INITIAL_SUPPLY = 10000;
/**
* @dev Contructor that gives msg.sender all of existing tokens.
*/
function SimpleToken() {
totalSupply = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
}
}
contract Ownable {
address public owner;
/**
* @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() {
if (msg.sender != owner) {
revert();
}
_;
}
/**
* @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 {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal 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 returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
library Math {
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
}
contract RexToken is StandardToken, Ownable {
function version() constant returns (bytes32) {
return "0.1.1";
}
string public constant name = "REX - Real Estate tokens";
string public constant symbol = "REX";
uint256 public constant decimals = 18;
uint256 constant BASE_RATE = 700;
uint256 constant ETH_RATE = 225;
uint256 constant USD_RAISED_CAP = 30*10**6;
uint256 constant ETHER_RAISED_CAP = USD_RAISED_CAP / ETH_RATE;
uint256 public constant WEI_RAISED_CAP = ETHER_RAISED_CAP * 1 ether;
uint256 constant DURATION = 4 weeks;
uint256 TOTAL_SHARE = 1000;
uint256 CROWDSALE_SHARE = 500;
address ANGELS_ADDRESS = 0x00998eba0E5B83018a0CFCdeCc5304f9f167d27a;
uint256 ANGELS_SHARE = 50;
address CORE_1_ADDRESS = 0x4aD48BE9bf6E2d35277Bd33C100D283C29C7951F;
uint256 CORE_1_SHARE = 75;
address CORE_2_ADDRESS = 0x2a62609c6A6bDBE25Da4fb05980e85db9A479C5e;
uint256 CORE_2_SHARE = 75;
address PARTNERSHIP_ADDRESS = 0x53B8fFBe35AE548f22d5a3b31D6E5e0C04f0d2DF;
uint256 PARTNERSHIP_SHARE = 70;
address REWARDS_ADDRESS = 0x43F1aa047D3241B7DD250EB37b25fc509085fDf9;
uint256 REWARDS_SHARE = 200;
address AFFILIATE_ADDRESS = 0x64ea62A8080eD1C2b8d996ACC7a82108975e5361;
uint256 AFFILIATE_SHARE = 30;
// state variables
address vault;
uint256 public startTime;
uint256 public weiRaised;
event TokenCreated(address indexed investor, uint256 amount);
function RexToken(uint256 _start, address _vault) {
startTime = _start;
vault = _vault;
isFinalized = false;
}
function () payable {
createTokens(msg.sender);
}
function createTokens(address recipient) payable {
if (tokenSaleOnHold) revert();
if (msg.value == 0) revert();
if (now < startTime) revert();
if (now > startTime + DURATION) revert();
uint256 weiAmount = msg.value;
if (weiRaised >= WEI_RAISED_CAP) revert();
//if funder sent more than the remaining amount then send them a refund of the difference
if ((weiRaised + weiAmount) > WEI_RAISED_CAP) {
weiAmount = WEI_RAISED_CAP - weiRaised;
if (!msg.sender.send(msg.value - weiAmount))
revert();
}
// calculate token amount to be created
uint256 tokens = weiAmount.mul(getRate());
// update totals
totalSupply = totalSupply.add(tokens);
weiRaised = weiRaised.add(weiAmount);
balances[recipient] = balances[recipient].add(tokens);
TokenCreated(recipient, tokens);
// send ether to the vault
if (!vault.send(weiAmount)) revert();
}
// return dynamic pricing
function getRate() constant returns (uint256) {
uint256 bonus = 0;
if (now < (startTime + 1 weeks)) {
bonus = 300;
} else if (now < (startTime + 2 weeks)) {
bonus = 200;
} else if (now < (startTime + 3 weeks)) {
bonus = 100;
}
return BASE_RATE.add(bonus);
}
function tokenAmount(uint256 share, uint256 finalSupply) constant returns (uint) {
if (share > TOTAL_SHARE) revert();
return share.mul(finalSupply).div(TOTAL_SHARE);
}
// grant regular tokens by share
function grantTokensByShare(address to, uint256 share, uint256 finalSupply) internal {
uint256 tokens = tokenAmount(share, finalSupply);
balances[to] = balances[to].add(tokens);
TokenCreated(to, tokens);
totalSupply = totalSupply.add(tokens);
}
function getFinalSupply() constant returns (uint256) {
return TOTAL_SHARE.mul(totalSupply).div(CROWDSALE_SHARE);
}
// do final token distribution
function finalize() onlyOwner() {
if (isFinalized) revert();
//if we are under the cap and not hit the duration then throw
if (weiRaised < WEI_RAISED_CAP && now <= startTime + DURATION) revert();
uint256 finalSupply = getFinalSupply();
grantTokensByShare(ANGELS_ADDRESS, ANGELS_SHARE, finalSupply);
grantTokensByShare(CORE_1_ADDRESS, CORE_1_SHARE, finalSupply);
grantTokensByShare(CORE_2_ADDRESS, CORE_2_SHARE, finalSupply);
grantTokensByShare(PARTNERSHIP_ADDRESS, PARTNERSHIP_SHARE, finalSupply);
grantTokensByShare(REWARDS_ADDRESS, REWARDS_SHARE, finalSupply);
grantTokensByShare(AFFILIATE_ADDRESS, AFFILIATE_SHARE, finalSupply);
isFinalized = true;
}
bool public tokenSaleOnHold;
function toggleTokenSaleOnHold() onlyOwner() {
if (tokenSaleOnHold)
tokenSaleOnHold = false;
else
tokenSaleOnHold = true;
}
bool public migrateDisabled;
struct structMigrate {
uint dateTimeCreated;
uint amount;
}
mapping(address => structMigrate) pendingMigrations;
function toggleMigrationStatus() onlyOwner() {
if (migrateDisabled)
migrateDisabled = false;
else
migrateDisabled = true;
}
function migrate(uint256 amount) {
//dont allow migrations until crowdfund is done
if (!isFinalized)
revert();
//dont proceed if migrate is disabled
if (migrateDisabled)
revert();
//dont proceed if there is pending value
if (pendingMigrations[msg.sender].amount > 0)
revert();
//amount parameter is in Wei
//old rex token is only 4 decimal places
//i.e. to migrate 8 old REX (80000) user inputs 8, ui converts to 8**18 (wei), then we divide by 14dp to get the original 80000.
uint256 amount_4dp = amount / (10**14);
//this will throw if they dont have the balance/allowance
StandardToken(0x0042a689f1ebfca404e13c29cb6d01e00059ba9dbc).transferFrom(msg.sender, this, amount_4dp);
//store time and amount in pending mapping
pendingMigrations[msg.sender].dateTimeCreated = now;
pendingMigrations[msg.sender].amount = amount;
}
function claimMigrate() {
//dont allow if migrations are disabled
if (migrateDisabled)
revert();
//dont proceed if no value
if (pendingMigrations[msg.sender].amount == 0)
revert();
//can only claim after a week has passed
if (now < pendingMigrations[msg.sender].dateTimeCreated + 1 weeks)
revert();
//credit the balances
balances[msg.sender] += pendingMigrations[msg.sender].amount;
totalSupply += pendingMigrations[msg.sender].amount;
//remove the pending migration from the mapping
delete pendingMigrations[msg.sender];
}
function transferOwnCoins(address _to, uint _value) onlyOwner() {
if (!isFinalized) revert();
balances[this] = balances[this].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(this, _to, _value);
}
}
|
Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. _spender The address which will spend the funds. _value The amount of tokens to be spent./ 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/20issuecomment-263524729
|
function approve(address _spender, uint256 _value) {
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) revert();
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
}
| 1,070,993
|
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.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: @openzeppelin/contracts/utils/EnumerableSet.sol
pragma solidity ^0.6.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.0.0, only sets of type `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];
}
// 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(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(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(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(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.6.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;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @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 is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev 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: contracts/XdexToken.sol
pragma solidity 0.6.12;
// XdexToken with Governance.
contract XdexToken is ERC20("XdexToken", "XDEX"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// https://github.com/quantstamp/sushiswap-security-review 3.4 fixed.
function _transfer(address sender, address recipient, uint256 amount) internal override(ERC20) {
_moveDelegates(_delegates[sender], _delegates[recipient], amount);
ERC20._transfer(sender, recipient, amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @notice A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "XDEX::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "XDEX::delegateBySig: invalid nonce");
require(now <= expiry, "XDEX::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "XDEX::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying XDEXs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "XDEX::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
// File: contracts/MasterChef.sol
pragma solidity 0.6.12;
interface IMigratorChef {
// Perform LP token migration from legacy UniswapV2 to XdexSwap.
// Take the current LP token address and return the new LP token address.
// Migrator should have full access to the caller's LP token.
// Return the new LP token address.
//
// XXX Migrator must have allowance access to UniswapV2 LP tokens.
// XdexSwap must mint EXACTLY the same amount of XdexSwap LP tokens or
// else something bad will happen. Traditional UniswapV2 does not
// do that so be careful!
function migrate(IERC20 token) external returns (IERC20);
}
// MasterChef is the master of Xdex. He can make Xdex and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once XDEX is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
contract MasterChef is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of XDEXs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accXdexPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accXdexPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. XDEXs to distribute per block.
uint256 lastRewardBlock; // Last block number that XDEXs distribution occurs.
uint256 accXdexPerShare; // Accumulated XDEXs per share, times 1e12. See below.
}
// The XDEX TOKEN!
XdexToken public xdex;
// Block number when bonus XDEX period ends.
uint256 public bonusEndBlock;
// XDEX tokens created per block.
uint256 public xdexPerBlock;
// Bonus muliplier for early xdex makers.
uint256 public constant BONUS_MULTIPLIER = 10;
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
mapping (IERC20 => bool) public lpTokenInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when XDEX mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
XdexToken _xdex,
IMigratorChef _migrator,
uint256 _xdexPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
require(address(_migrator) != address(0), "setMigrator: no _migrator");
migrator = _migrator;
xdex = _xdex;
xdexPerBlock = _xdexPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// https://github.com/quantstamp/sushiswap-security-review 3.1 fixed.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
require(lpTokenInfo[_lpToken] == false,"MasterChef::add - This lpToken already added");
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accXdexPerShare: 0
}));
lpTokenInfo[_lpToken] = true;
}
// Update the given pool's XDEX allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
// View function to see pending XDEXs on frontend.
function pendingXdex(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accXdexPerShare = pool.accXdexPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 xdexReward = multiplier.mul(xdexPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accXdexPerShare = accXdexPerShare.add(xdexReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accXdexPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 xdexReward = multiplier.mul(xdexPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
xdex.mint(address(this), xdexReward);
pool.accXdexPerShare = pool.accXdexPerShare.add(xdexReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for XDEX allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accXdexPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeXdexTransfer(msg.sender, pending);
}
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accXdexPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accXdexPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeXdexTransfer(msg.sender, pending);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accXdexPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 user_amount = user.amount;// https://github.com/quantstamp/sushiswap-security-review 3.6 fixed.
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), user_amount);
emit EmergencyWithdraw(msg.sender, _pid, user_amount);
}
// Safe xdex transfer function, just in case if rounding error causes pool to not have enough XDEXs.
function safeXdexTransfer(address _to, uint256 _amount) internal {
uint256 xdexBal = xdex.balanceOf(address(this));
if (_amount > xdexBal) {
xdex.transfer(_to, xdexBal);
} else {
xdex.transfer(_to, _amount);
}
}
}
|
Safe xdex transfer function, just in case if rounding error causes pool to not have enough XDEXs.
|
function safeXdexTransfer(address _to, uint256 _amount) internal {
uint256 xdexBal = xdex.balanceOf(address(this));
if (_amount > xdexBal) {
xdex.transfer(_to, xdexBal);
xdex.transfer(_to, _amount);
}
}
| 60,461
|
/*
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░█████░░░░░░░░█████░░░░░░░███░░░░░█████░░░░░██░░░░░░░░█████░░░░░░░█████░░░░░
░░░██░░░░░███░░███░░░░░██░░░██░░░░░███░░░░░██░░░░░███░░███░░░░░██░░░██░░░░░███░░
░░░░░███░░░░░██░░░░░███░░░░░░░█████░░░░░░░░░░█████░░░░░░░░██░░░░░███░░░░░██░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
████████████████████████████████████████████████████████████████████████████████
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░██░░░░░ ░░░░░███░░
░░░░░███░░ ░░░██░░░░░
░░░█████░░ ██████████ ██████████ ░░░░░███░░
░░░░░░░░░░ ██ ███ ██ ███ ░░░░░░░░░░
░░░░░███░░ ███ █████ ██ ███ █████ ██ ░░░██░░░░░
░░░██░░░░░ ███ ██ ██ █████ ███ ██ ██ ░░░░░███░░
░░░█████░░ ███ █████ ██ ███ █████ ██ ░░░██░░░░░
░░░░░░░░░░ ███ █████ ██ █████ ███ █████ ██ ░░░░░░░░░░
░░░█████░░ ███ ██ ███ ██ ░░░░░███░░
░░░██░░░░░ ███████████████ █████ ███████████████ ░░░██░░░░░
░░░░░███░░ ░░░░░███░░
░░░░░░░░░░ █████ █████ ░░░░░░░░░░
░░░█████░░ █████ █████ █████ █████ █████ █████ █████ ░░░██░░░░░
░░░░░███░░ █████ █████ █████ ██ █████ ░░░░░███░░
░░░██░░░░░ ░░░██░░░░░
░░░░░░░░░░ ░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
████████████████████████████████████████████████████████████████████████████████
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░█████░░░░░████████░░███░░███░░░░░░░░░░░░░░░██░░░██░░░██░░░██░░░██░░░██░░░░░
░░░░░███░░███░░█████░░░░░░░░██░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░████████░░███░░░░░░░███░░███░░░░░░░░░░░░░░░██░░░██░░░██░░░██░░░██░░░██░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
*/
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.13;
import {Base64} from './lib/Base64.sol';
import {Ownable} from '@openzeppelin/contracts/access/Ownable.sol';
import '@divergencetech/ethier/contracts/utils/DynamicBuffer.sol';
import {IOKPC} from './interfaces/IOKPC.sol';
import {OKPCParts} from './OKPCParts.sol';
import {IOKPCFont} from './interfaces/IOKPCFont.sol';
import {IOKPCMetadata} from './interfaces/IOKPCMetadata.sol';
import {IOKPCGenesisArtwork} from './interfaces/IOKPCGenesisArtwork.sol';
import {ENSNameResolver} from './lib/ENSNameResolver.sol';
contract OKPCMetadata is IOKPCMetadata, Ownable, ENSNameResolver {
/* --------------------------------- ****** --------------------------------- */
/* -------------------------------------------------------------------------- */
/* CONFIG */
/* -------------------------------------------------------------------------- */
using DynamicBuffer for bytes;
string public FALLBACK_URL = 'https://okpc.app/api/okpc/';
string public DESCRIPTION_URL = 'https://okpc.app/gallery/';
/* --------------------------------- ****** --------------------------------- */
/* -------------------------------------------------------------------------- */
/* STORAGE */
/* -------------------------------------------------------------------------- */
IOKPC private _okpc;
OKPCParts private _parts;
IOKPCFont private _font;
IOKPCGenesisArtwork private _genesisArtwork;
/* --------------------------------- ****** --------------------------------- */
/* -------------------------------------------------------------------------- */
/* INITIALIZATION */
/* -------------------------------------------------------------------------- */
constructor(
address okpcAddress,
address partsAddress,
address fontAddress,
address genesisArtworkAddress
) {
_okpc = IOKPC(okpcAddress);
_parts = OKPCParts(partsAddress);
_font = IOKPCFont(fontAddress);
_genesisArtwork = IOKPCGenesisArtwork(genesisArtworkAddress);
}
/* --------------------------------- ****** --------------------------------- */
/* -------------------------------------------------------------------------- */
/* ADMIN */
/* -------------------------------------------------------------------------- */
/// @notice Allows the owner to update the Parts address.
/// @param partsAddress The new Parts contract to use for the renderer. Must conform to IOKPCParts.
function setParts(address partsAddress) public onlyOwner {
_parts = OKPCParts(partsAddress);
}
/// @notice Allows the owner to update the Fonts address.
/// @param fontAddress The new Fonts address to use for the renderer. Must conform to IOKPCFont.
function setFont(address fontAddress) public onlyOwner {
_font = IOKPCFont(fontAddress);
}
/// @notice Allows the owner to update the Genesis Artwork address.
/// @param genesisArtworkAddress The new Genesis Artwork address to use for the renderer. Must conform to IOKPCGenesisArtwork.
function setGenesisArtworkAddress(address genesisArtworkAddress)
public
onlyOwner
{
_genesisArtwork = IOKPCGenesisArtwork(genesisArtworkAddress);
}
/// @notice Allows the owner to update the fallback / off-chain metadata address.
/// @param url The new off-chain metadata url base to use. The tokenId will be appended to this url.
function setFallbackURL(string memory url) public onlyOwner {
FALLBACK_URL = url;
}
/// @notice Allows the owner to update the description url.
/// @param url The url base to the use for the artist links in the token description. The full address will be appended to this url.
function setDescriptionURL(string memory url) public onlyOwner {
DESCRIPTION_URL = url;
}
/// @notice Gets the TokenURI for a specified OKPC given params
/// @param tokenId The tokenId of the OKPC
function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
if (tokenId < 1 || tokenId > 8192) revert InvalidTokenID();
return
string(
abi.encodePacked(
'data:application/json;base64,',
_getMetadataJSON(tokenId)
)
);
}
function _getMetadataJSON(uint256 tokenId)
internal
view
returns (string memory)
{
Parts memory parts = getParts(tokenId);
uint256 artId = _okpc.activeArtForOKPC(tokenId);
uint256 clockSpeed = _okpc.clockSpeed(tokenId);
uint256 artCollected = _okpc.artCountForOKPC(tokenId);
bool useOffChainRenderer = _okpc.useOffchainMetadata(tokenId);
bool isCustomArt = artId == 0;
IOKPC.Art memory art = isCustomArt
? _okpc.getPaintArt(tokenId)
: _okpc.getGalleryArt(artId);
bytes memory artData = abi.encodePacked(art.data1, art.data2);
if (artData.length < 56) revert NotEnoughPixelData();
(, IOKPC.Art memory shippedWithArt) = _genesisArtwork.getGenesisArtwork(
tokenId
);
return
Base64.encode(
abi.encodePacked(
_getMetadataHeader(tokenId, parts, art),
useOffChainRenderer
? abi.encodePacked(FALLBACK_URL, toString(tokenId), '/img')
: abi.encodePacked(
'data:image/svg+xml;base64,',
drawOKPC(clockSpeed, artData, parts)
),
'", "attributes": ',
_getAttributes(
parts,
clockSpeed,
artCollected,
art,
shippedWithArt,
useOffChainRenderer,
isCustomArt
),
'}'
)
);
}
/// @notice Returns the SVG of the specified art in the specified color
/// @param art The byte data for the artwork to render
/// @param colorIndex The color to use for the art. Accepts values between 0 and 5;
function renderArt(bytes memory art, uint256 colorIndex)
public
view
returns (string memory)
{
// get svg
OKPCParts.Color memory color = _parts.getColor(colorIndex);
return
string(
abi.encodePacked(
'<svg viewBox="0 0 24 16" xmlns="http://www.w3.org/2000/svg" shape-rendering="crispEdges" height="512" width="512" fill="#',
color.dark,
'"><rect width="24" height="16" fill="#',
color.light,
'"/>',
drawArt(art),
'</svg>'
)
);
}
/// @notice Gets the proper parts for a given OKPC TokenID
function getParts(uint256 tokenId)
public
view
override
returns (Parts memory)
{
if (tokenId < 1 || tokenId > 8192) revert InvalidTokenID();
Parts memory parts;
if (tokenId <= 128) {
parts.color = _parts.getColor((tokenId - 1) % _parts.NUM_COLORS());
parts.word = _parts.getWord(tokenId - 1);
} else {
parts.color = _parts.getColor(
uint256(keccak256(abi.encodePacked('COLOR', tokenId))) %
_parts.NUM_COLORS()
);
parts.word = _parts.getWord(
uint256(keccak256(abi.encodePacked('WORD', tokenId))) %
_parts.NUM_WORDS()
);
}
parts.headband = _parts.getHeadband(
uint256(keccak256(abi.encodePacked('HEADBAND', tokenId))) %
_parts.NUM_HEADBANDS()
);
parts.rightSpeaker = _parts.getSpeaker(
uint256(keccak256(abi.encodePacked('RIGHT SPEAKER', tokenId))) %
_parts.NUM_SPEAKERS()
);
parts.leftSpeaker = _parts.getSpeaker(
uint256(keccak256(abi.encodePacked('LEFT SPEAKER', tokenId))) %
_parts.NUM_SPEAKERS()
);
return parts;
}
/// @notice Gets the SVG Base64 encoded for a specified OKPC
/// @param tokenId The tokenId of the OKPC to draw
function drawOKPC(uint256 tokenId) public view returns (string memory) {
uint256 artId = _okpc.activeArtForOKPC(tokenId);
uint256 clockSpeed = _okpc.clockSpeed(tokenId);
bool isCustomArt = artId == 0;
IOKPC.Art memory art = isCustomArt
? _okpc.getPaintArt(artId)
: _okpc.getGalleryArt(artId);
bytes memory artData = abi.encodePacked(art.data1, art.data2);
if (artData.length < 56) revert NotEnoughPixelData();
Parts memory parts = getParts(tokenId);
return drawOKPC(clockSpeed, artData, parts);
}
/// @notice Renders the SVG for a given configuration.
/// @param speed The clockspeed of the OKPC to draw
/// @param art The artwork to draw on the OKPC's screen
/// @param parts The parts of the OKPC (headband, speaker, etc)
function drawOKPC(
uint256 speed,
bytes memory art,
Parts memory parts
) public view returns (string memory) {
bytes memory svg = abi.encodePacked(
abi.encodePacked(
'<svg viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg" shape-rendering="crispEdges" fill="#',
parts.color.dark,
'" height="512" width="512"><rect width="32" height="32" fill="#',
parts.color.regular,
'"/><rect x="4" y="8" width="24" height="16" fill="#',
parts.color.light,
'"/><rect width="32" height="1" x="0" y="5" /><rect width="32" height="1" x="0" y="26" /><path transform="translate(1,1)" d="',
parts.headband.data,
'"/><path transform="translate(1, 8)" d="',
parts.leftSpeaker.data,
'"/><path transform="translate(31, 8) scale(-1,1)" d="',
parts.rightSpeaker.data,
'"/><g transform="translate(4, 8)" fill-rule="evenodd" clip-rule="evenodd">'
),
drawArt(art),
'</g>',
_drawWord(parts.word),
'<g transform="translate(19, 28)">',
_drawClockSpeed(speed, parts),
'</g></svg>'
);
return Base64.encode(svg);
}
/// @notice Returns the SVG rects for artData.
/// @param artData The data to draw as bytes.
function drawArt(bytes memory artData)
public
pure
override
returns (string memory)
{
bytes memory rects = DynamicBuffer.allocate(2**16); // Allocate 64KB of memory, we will not use this much, but it's safe.
uint256 offset = 8;
// render 8 pixels at a time
for (uint256 pixelNum = 0; pixelNum < 384; pixelNum += 8) {
uint8 workingByte = uint8(artData[offset + (pixelNum / 8)]);
uint256 y = uint256(pixelNum / 24);
uint256 x = uint256(pixelNum % 24);
for (uint256 i; i < 8; i++) {
// if the pixel is a 1, draw it
if ((workingByte >> (7 - i)) & 1 == 1) {
rects.appendSafe(
abi.encodePacked(
'<rect width="1" height="1" x="',
toString(x + i),
'" y="',
toString(y),
'"/>'
)
);
}
}
}
return string(rects);
}
/// @notice Renders the SVG path for an OKPC Word.
function _drawWord(string memory word) internal view returns (bytes memory) {
bytes memory wordBytes = bytes(word);
bytes memory path;
for (uint256 i; i < wordBytes.length; i++) {
if (wordBytes[i] != 0x0) {
path = abi.encodePacked(
path,
'<path clip-rule="evenodd" fill-rule="evenodd" transform="translate(',
toString(2 + i * 4),
',28)" d="',
_font.getChar(wordBytes[i]),
'"/>'
);
} else {
break;
}
}
return path;
}
function _drawClockSpeed(uint256 speed, Parts memory parts)
internal
pure
returns (bytes memory)
{
bytes memory clockSpeedPixels = DynamicBuffer.allocate(2**16); // Allocate 64KB of memory, we will not use this much, but it's safe.
bytes6 color;
for (uint256 i; i < 12; i++) {
uint256 x = 10 - ((i / 2) * 2);
uint256 y = (i % 2 == 0) ? 2 : 0;
if (i < speed / 128) color = parts.color.light;
else color = parts.color.dark;
clockSpeedPixels.appendSafe(
abi.encodePacked(
'<rect width="1" height="1" x="',
toString(x),
'" y="',
toString(y),
'" fill="#',
color,
'"/>'
)
);
}
return clockSpeedPixels;
}
function _getMetadataHeader(
uint256 tokenId,
Parts memory parts,
IOKPC.Art memory art
) internal view returns (bytes memory) {
string memory artistENS = ENSNameResolver.getENSName(art.artist);
return
abi.encodePacked(
'{"name": "OKPC #',
toString(tokenId),
'", "description": "A ',
parts.color.name,
" OKPC displaying '",
bytes16ToString(art.title),
"' by [",
bytes(artistENS).length > 0
? artistENS
: string(abi.encodePacked('0x', toAsciiString(art.artist))),
'](',
DESCRIPTION_URL,
string(abi.encodePacked('0x', toAsciiString(art.artist))),
')", "image": "'
);
}
function _getAttributes(
Parts memory parts,
uint256 speed,
uint256 artCollected,
IOKPC.Art memory art,
IOKPC.Art memory shippedWithArt,
bool isFallbackRenderer,
bool isCustomArt
) internal view returns (bytes memory) {
string memory artistENS = ENSNameResolver.getENSName(art.artist);
string memory word = parts.word;
// if word is 200% change it to 200 Percent to avoid OpenSea bug
if (keccak256(abi.encodePacked(word)) == keccak256('200%'))
word = string(abi.encodePacked('200', '\xEF\xBC\x85'));
return
abi.encodePacked(
'[{"trait_type":"Art Collected", "value": ',
toString(artCollected),
'}, {"trait_type":"Word", "value": "',
word,
'"}, {"trait_type": "Color", "value": "',
parts.color.name,
abi.encodePacked(
'"}, {"trait_type": "Headband", "value": "',
parts.headband.name,
'"}, {"trait_type": "Right Speaker", "value": "',
parts.rightSpeaker.name,
'"}, {"trait_type": "Left Speaker", "value": "',
parts.leftSpeaker.name,
'"}, {"trait_type": "Clock Speed", "value": "',
toString(speed)
),
abi.encodePacked(
'"}, {"trait_type": "Art", "value": "',
bytes16ToString(art.title),
'"}, {"trait_type": "Renderer", "value": "',
isFallbackRenderer ? 'Off Chain' : 'On Chain',
'"}, {"trait_type": "Screen", "value": "',
isCustomArt ? 'Custom Art' : 'Gallery Art'
),
abi.encodePacked(
'"}, {"trait_type": "Artist", "value": "',
bytes(artistENS).length > 0
? artistENS
: string(abi.encodePacked('0x', toAsciiString(art.artist))),
'"}, {"trait_type": "Shipped With", "value": "',
bytes16ToString(shippedWithArt.title),
' by ',
bytes(artistENS).length > 0
? artistENS
: string(abi.encodePacked('0x', toAsciiString(art.artist))),
'"}]'
)
);
}
// * UTILITIES * //
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT license
// 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);
}
function bytes16ToString(bytes16 x) internal pure returns (string memory) {
uint256 numChars = 0;
for (uint256 i; i < 16; i++) {
if (x[i] == bytes1(0)) break;
numChars++;
}
bytes memory result = new bytes(numChars);
for (uint256 i; i < numChars; i++) result[i] = x[i];
return string(result);
}
function toAsciiString(address x) internal pure returns (string memory) {
bytes memory s = new bytes(40);
for (uint256 i; i < 20; i++) {
bytes1 b = bytes1(uint8(uint256(uint160(x)) / (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 b) internal pure returns (bytes1 c) {
if (uint8(b) < 10) return bytes1(uint8(b) + 0x30);
else return bytes1(uint8(b) + 0x57);
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library Base64 {
bytes internal constant TABLE =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/// @notice Encodes some bytes to the base64 representation
function encode(bytes memory data) internal pure returns (string memory) {
uint256 len = data.length;
if (len == 0) return "";
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((len + 2) / 3);
// Add some extra buffer at the end
bytes memory result = new bytes(encodedLen + 32);
bytes memory table = TABLE;
assembly {
let tablePtr := add(table, 1)
let resultPtr := add(result, 32)
for {
let i := 0
} lt(i, len) {
} {
i := add(i, 3)
let input := and(mload(add(data, i)), 0xffffff)
let out := mload(add(tablePtr, and(shr(18, input), 0x3F)))
out := shl(8, out)
out := add(
out,
and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF)
)
out := shl(8, out)
out := add(
out,
and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF)
)
out := shl(8, out)
out := add(
out,
and(mload(add(tablePtr, and(input, 0x3F))), 0xFF)
)
out := shl(224, out)
mstore(resultPtr, out)
resultPtr := add(resultPtr, 4)
}
switch mod(len, 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
mstore(result, encodedLen)
}
return string(result);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier)
pragma solidity >=0.8.0;
/// @title DynamicBuffer
/// @author David Huber (@cxkoda) and Simon Fremaux (@dievardump). See also
/// https://raw.githubusercontent.com/dievardump/solidity-dynamic-buffer
/// @notice This library is used to allocate a big amount of container memory
// which will be subsequently filled without needing to reallocate
/// memory.
/// @dev First, allocate memory.
/// Then use `buffer.appendUnchecked(theBytes)` or `appendSafe()` if
/// bounds checking is required.
library DynamicBuffer {
/// @notice Allocates container space for the DynamicBuffer
/// @param capacity The intended max amount of bytes in the buffer
/// @return buffer The memory location of the buffer
/// @dev Allocates `capacity + 0x60` bytes of space
/// The buffer array starts at the first container data position,
/// (i.e. `buffer = container + 0x20`)
function allocate(uint256 capacity)
internal
pure
returns (bytes memory buffer)
{
assembly {
// Get next-free memory address
let container := mload(0x40)
// Allocate memory by setting a new next-free address
{
// Add 2 x 32 bytes in size for the two length fields
// Add 32 bytes safety space for 32B chunked copy
let size := add(capacity, 0x60)
let newNextFree := add(container, size)
mstore(0x40, newNextFree)
}
// Set the correct container length
{
let length := add(capacity, 0x40)
mstore(container, length)
}
// The buffer starts at idx 1 in the container (0 is length)
buffer := add(container, 0x20)
// Init content with length 0
mstore(buffer, 0)
}
return buffer;
}
/// @notice Appends data to buffer, and update buffer length
/// @param buffer the buffer to append the data to
/// @param data the data to append
/// @dev Does not perform out-of-bound checks (container capacity)
/// for efficiency.
function appendUnchecked(bytes memory buffer, bytes memory data)
internal
pure
{
assembly {
let length := mload(data)
for {
data := add(data, 0x20)
let dataEnd := add(data, length)
let copyTo := add(buffer, add(mload(buffer), 0x20))
} lt(data, dataEnd) {
data := add(data, 0x20)
copyTo := add(copyTo, 0x20)
} {
// Copy 32B chunks from data to buffer.
// This may read over data array boundaries and copy invalid
// bytes, which doesn't matter in the end since we will
// later set the correct buffer length, and have allocated an
// additional word to avoid buffer overflow.
mstore(copyTo, mload(data))
}
// Update buffer length
mstore(buffer, add(mload(buffer), length))
}
}
/// @notice Appends data to buffer, and update buffer length
/// @param buffer the buffer to append the data to
/// @param data the data to append
/// @dev Performs out-of-bound checks and calls `appendUnchecked`.
function appendSafe(bytes memory buffer, bytes memory data) internal pure {
uint256 capacity;
uint256 length;
assembly {
capacity := sub(mload(sub(buffer, 0x20)), 0x40)
length := mload(buffer)
}
require(
length + data.length <= capacity,
"DynamicBuffer: Appending out of bounds."
);
appendUnchecked(buffer, data);
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.8;
interface IOKPC {
enum Phase {
INIT,
EARLY_BIRDS,
FRIENDS,
PUBLIC
}
struct Art {
address artist;
bytes16 title;
uint256 data1;
uint256 data2;
}
struct Commission {
address artist;
uint256 amount;
}
struct ClockSpeedXP {
uint256 savedSpeed;
uint256 lastSaveBlock;
uint256 transferCount;
uint256 artLastChanged;
}
function getPaintArt(uint256) external view returns (Art memory);
function getGalleryArt(uint256) external view returns (Art memory);
function activeArtForOKPC(uint256) external view returns (uint256);
function useOffchainMetadata(uint256) external view returns (bool);
function clockSpeed(uint256) external view returns (uint256);
function artCountForOKPC(uint256) external view returns (uint256);
}
/*
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░███░░████████░░███░░████████░░███░░░░░███░░███████░░███░░████████░░███░░░░░
░░░░░███░░░░░░░███░░███░░░░░░░███░░███░░░░░███░░███░░░░░░███░░███░░░░░░░███░░░░░
░░░░░████████░░███░░████████░░███░░███████████░░███░░███████░░███░░████████░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
████████████████████████████████████████████████████████████████████████████████
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░ ░░░░░░░░░░
░░░░░███░░ ██████████ ██████████ ░░░░░███░░
░░░█████░░ ██ ███ ██ ███ ░░░██░░░░░
░░░░░░░░░░ ███ █████ ██ ███ ██ ░░░░░░░░░░
░░░░░░░░░░ ███ ███ ██ ███ █████ ██ ░░░░░░░░░░
░░░░░███░░ ███ █████ ██ █████ ███ ██ ██ ░░░░░███░░
░░░█████░░ ███ █████ ██ ███ █████ ██ ░░░██░░░░░
░░░░░░░░░░ ███ ██ █████ ███ █████ ██ ░░░░░░░░░░
░░░░░░░░░░ ██ ███ ██ ███ ░░░░░░░░░░
░░░█████░░ ██████████ █████ ██████████ ░░░░░███░░
░░░░░███░░ ░░░██░░░░░
░░░░░░░░░░ █████ █████ █████ █████ ░░░░░░░░░░
░░░░░░░░░░ █████ █████ █████ █████ ██ █████ █████ ░░░░░░░░░░
░░░█████░░ █████ █████ █████ ░░░░░███░░
░░░░░███░░ ░░░██░░░░░
░░░░░░░░░░ ░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
████████████████████████████████████████████████████████████████████████████████
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░████████░░████████░░████████░░░░░░░░░░░░░░░██░░░██░░░██░░░██░░░██░░░██░░░░░
░░░░░███░░░░░░░███░░███░░████████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░███░░░░░░░████████░░███░░███░░░░░░░░░░░░░░░██░░░██░░░██░░░██░░░██░░░██░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
*/
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.8;
import {IOKPCParts} from './interfaces/IOKPCParts.sol';
import '@0xsequence/sstore2/contracts/SSTORE2.sol';
contract OKPCParts is IOKPCParts {
/* --------------------------------- ****** --------------------------------- */
/* -------------------------------------------------------------------------- */
/* CONFIG */
/* -------------------------------------------------------------------------- */
uint256 public constant NUM_COLORS = 6;
uint256 public constant NUM_HEADBANDS = 8;
uint256 public constant NUM_SPEAKERS = 8;
uint256 public constant NUM_WORDS = 128;
/* --------------------------------- ****** --------------------------------- */
/* -------------------------------------------------------------------------- */
/* STORAGE */
/* -------------------------------------------------------------------------- */
Color[NUM_COLORS] public colors;
Vector[NUM_HEADBANDS] public headbands;
Vector[NUM_SPEAKERS] public speakers;
bytes4[NUM_WORDS] public words;
/* --------------------------------- ****** --------------------------------- */
/* -------------------------------------------------------------------------- */
/* INITIALIZATION */
/* -------------------------------------------------------------------------- */
constructor() {
_initColors();
_initHeadbands();
_initSpeakers();
_initWords();
}
/* --------------------------------- ****** --------------------------------- */
/* -------------------------------------------------------------------------- */
/* PARTS */
/* -------------------------------------------------------------------------- */
/// @notice Gets the Color by index. Accepts values between 0 and 5.
function getColor(uint256 index) public view override returns (Color memory) {
if (index > NUM_COLORS - 1) revert IndexOutOfBounds(index, NUM_COLORS - 1);
return colors[index];
}
/// @notice Gets the Headband by index. Accepts values between 0 and 7.
function getHeadband(uint256 index)
public
view
override
returns (Vector memory)
{
if (index > NUM_HEADBANDS - 1)
revert IndexOutOfBounds(index, NUM_HEADBANDS - 1);
return headbands[index];
}
/// @notice Gets the Speaker by index. Accepts values between 0 and 7.
function getSpeaker(uint256 index)
public
view
override
returns (Vector memory)
{
if (index > NUM_SPEAKERS - 1)
revert IndexOutOfBounds(index, NUM_SPEAKERS - 1);
return speakers[index];
}
/// @notice Gets the Word by index. Accepts values between 0 and 127.
function getWord(uint256 index) public view override returns (string memory) {
if (index > NUM_WORDS - 1) revert IndexOutOfBounds(index, NUM_WORDS - 1);
return _toString(words[index]);
}
/* --------------------------------- ****** --------------------------------- */
/* -------------------------------------------------------------------------- */
/* INITIALIZATION */
/* -------------------------------------------------------------------------- */
/// @notice Initializes the stored Colors.
function _initColors() internal {
// gray
colors[0] = Color(
bytes6('CCCCCC'),
bytes6('838383'),
bytes6('4D4D4D'),
'Gray'
);
// green
colors[1] = Color(
bytes6('54F8B5'),
bytes6('00DC82'),
bytes6('037245'),
'Green'
);
// blue
colors[2] = Color(
bytes6('80B3FF'),
bytes6('2E82FF'),
bytes6('003D99'),
'Blue'
);
// purple
colors[3] = Color(
bytes6('DF99FF'),
bytes6('C13CFF'),
bytes6('750DA5'),
'Purple'
);
// yellow
colors[4] = Color(
bytes6('FBDA9D'),
bytes6('F8B73E'),
bytes6('795106'),
'Yellow'
);
// pink
colors[5] = Color(
bytes6('FF99D8'),
bytes6('FF44B7'),
bytes6('99005E'),
'Pink'
);
}
/// @notice Initializes the stored Headbands.
function _initHeadbands() internal {
headbands[0] = Vector(
'M2 3H1V0H2V2H4V3H2ZM3 0H5H6V3H5V1H3V0ZM11 0H9V1H11V3H12V0H11ZM14 0H13V3H14H16H17V0H16V2H14V0ZM19 0H21V1H19V3H18V0H19ZM27 0H25H24V3H25V1H27V0ZM20 3V2H22V0H23V3H22H20ZM26 2V3H28H29V0H28V2H26ZM8 3H10V2H8V0H7V3H8Z',
'Crest'
);
headbands[1] = Vector(
'M11 1H12V0H11V1ZM11 2H10V1H11V2ZM13 2H11V3H13V2ZM14 1H13V2H14V1ZM16 1V0H14V1H16ZM17 2H16V1H17V2ZM19 2V3H17V2H19ZM19 1H20V2H19V1ZM19 1V0H18V1H19ZM0 1H1V2H0V1ZM1 2H2V3H1V2ZM3 1V0H1V1H3ZM4 2V1H3V2H4ZM5 2H4V3H5V2ZM6 1H5V2H6V1ZM8 1V0H6V1H8ZM8 2H9V1H8V2ZM8 2H7V3H8V2ZM24 1H25V2H24V1ZM22 1V0H24V1H22ZM22 2H21V1H22V2ZM22 2H23V3H22V2ZM26 2V3H25V2H26ZM27 1V2H26V1H27ZM29 1H27V0H29V1ZM29 2V1H30V2H29ZM29 2V3H28V2H29Z',
'Ornate'
);
headbands[2] = Vector(
'M3 0H1V1H3V2H1V3H3V2H4V3H6V2H4V1H6V0H4V1H3V0ZM27 0H29V1H27V0ZM27 2V1H26V0H24V1H26V2H24V3H26V2H27ZM27 2H29V3H27V2ZM10 0H12V1H10V0ZM10 2V1H9V0H7V1H9V2H7V3H9V2H10ZM10 2H12V3H10V2ZM18 0H20V1H18V0ZM21 1H20V2H18V3H20V2H21V3H23V2H21V1ZM21 1V0H23V1H21ZM16 0H15V1H14V3H15V2H16V0Z',
'Power'
);
headbands[3] = Vector(
'M1 3H2H3V2H2V1H4V3H5H7H8V1H10V3H11H14V2V1H16V2V3H19H20V1H22V3H23H25H26V1H28V2H27V3H28H29V0H28H26H25V2H23V0H22H20H19V2H17V1H18V0H12V1H13V2H11V0H10H8H7V2H5V0H4H2H1V3Z',
'Temple'
);
headbands[4] = Vector(
'M2 1H1V0H2V1ZM2 2V1H3V2H2ZM2 2V3H1V2H2ZM28 1H29V0H28V1ZM28 2V1H27V2H28ZM28 2H29V3H28V2ZM4 1H5V2H4V3H5V2H6V1H5V0H4V1ZM25 1H26V0H25V1ZM25 2V1H24V2H25ZM25 2H26V3H25V2ZM7 1H8V2H7V3H8V2H9V1H8V0H7V1ZM22 1H23V0H22V1ZM22 2V1H21V2H22ZM22 2H23V3H22V2ZM10 1H11V2H10V3H11V2H12V1H11V0H10V1ZM16 1H14V0H16V1ZM16 2V1H17V2H16ZM14 2H16V3H14V2ZM14 2V1H13V2H14ZM19 1H20V0H19V1ZM19 2V1H18V2H19ZM19 2H20V3H19V2Z',
'Wreath'
);
headbands[5] = Vector(
'M1 1H10V0H1V1ZM12 1H13V2H14V3H16V2H17V1H18V0H16V1V2H14V1V0H12V1ZM11 3H1V2H11V3ZM29 1H20V0H29V1ZM19 3H29V2H19V3Z',
'Valiant'
);
headbands[6] = Vector(
'M2 1H3V2H2V1ZM2 1H1V2H2V3H3V2H4V1H3V0H2V1ZM6 1H7V2H6V1ZM6 1H5V2H6V3H7V2H8V1H7V0H6V1ZM11 1H10V0H11V1ZM11 2V1H12V2H11ZM10 2H11V3H10V2ZM10 2V1H9V2H10ZM28 1H27V0H28V1ZM28 2V1H29V2H28ZM27 2H28V3H27V2ZM27 2V1H26V2H27ZM24 1H23V0H24V1ZM24 2V1H25V2H24ZM23 2H24V3H23V2ZM23 2V1H22V2H23ZM20 1H19V0H20V1ZM20 2V1H21V2H20ZM19 2H20V3H19V2ZM19 2V1H18V2H19ZM16 2H14V1H16V2ZM16 2V3H17V2H16ZM16 1V0H17V1H16ZM14 1H13V0H14V1ZM14 2V3H13V2H14Z',
'Tainia'
);
headbands[7] = Vector(
'M10 0H14V1H13V2H17V1H16V0H20V1H18V2H19V3H11V2H12V1H10V0ZM3 2H5V3H1V2H2V1H1V0H9V1H8V2H10V3H6V2H7V1H3V2ZM25 2H27V1H23V2H24V3H20V2H22V1H21V0H29V1H28V2H29V3H25V2Z',
'Colossus'
);
}
/// @notice Initializes the stored Speakers.
function _initSpeakers() internal {
speakers[0] = Vector(
'M1 1H0V2H1V3H2V2H1V1ZM1 5H0V6H1V7H2V6H1V5ZM0 9H1V10H0V9ZM1 10H2V11H1V10ZM1 13H0V14H1V15H2V14H1V13Z',
'Piezo'
);
speakers[1] = Vector(
'M1 1L1 0H0V1H1ZM1 2H2V1H1V2ZM1 2H0V3H1V2ZM1 10L1 11H0V10H1ZM1 9H2V10H1L1 9ZM1 9H0V8H1L1 9ZM1 4L1 5H0V6H1L1 7H2L2 6H1L1 5H2L2 4H1ZM1 13L1 12H2L2 13H1ZM1 14L1 13H0V14H1ZM1 14H2L2 15H1L1 14Z',
'Ambient'
);
speakers[2] = Vector(
'M0 2H1V3H2L2 1H1L1 0H0V2ZM1 5H2L2 7H1V6H0V4H1L1 5ZM2 14H1L1 15H0V13H1V12H2L2 14ZM2 10L2 8H1V9H0V11H1L1 10H2Z',
'Hyper'
);
speakers[3] = Vector(
'M1 1L1 0H0V1H1ZM1 1H2V2V3H1H0V2H1V1ZM1 5L1 4H2V5H1ZM1 5L1 6H2V7H1H0V6V5H1ZM1 13H0V12H1H2V13V14H1L1 13ZM1 14L1 15H0V14H1ZM2 9V8H1H0V9V10H1V11H2V10H1V9H2Z',
'Crystal'
);
speakers[4] = Vector(
'M2 0H1V1H0V2H1V3H2V0ZM2 5H1V4H0V7H1V6H2V5ZM2 9H1V8H0V11H1V10H2V9ZM0 13H1V12H2V15H1V14H0V13Z',
'Taser'
);
speakers[5] = Vector(
'M2 0V1V2V3H0V2H1V1V0H2ZM0 4V5V6V7H2V6H1L1 5H2V4H0ZM2 10V11H0V10H1V9H0V8H2V9V10ZM0 12V13H1V14V15H2V14L2 13V12H0Z',
'Buster'
);
speakers[6] = Vector(
'M0 0V1L2 1V0H0ZM1 3V2H2V3H1ZM2 5V4H0V5H2ZM1 11V10H2V11H1ZM2 13V12H0V13H2ZM2 15V14H1V15H2ZM2 7V6H1V7H2ZM0 8V9H2V8H0Z',
'Tower'
);
speakers[7] = Vector(
'M2 1V2V3H0V2L1 2V1H2ZM1 11V10H0V9H2L2 10V11H1ZM2 14V13H0V14H1V15H2V14ZM1 5V6H0V7H2L2 6V5H1Z',
'Blaster'
);
}
/// @notice Initializes the stored Words.
function _initWords() internal {
words = [
bytes4('WAIT'),
'OK',
'INFO',
'HELP',
'WARN',
'ERR',
'OOF',
'WHAT',
'RARE',
'200%',
'GATO',
'ABRA',
'POOF',
'FUN',
'BYTE',
'POLY',
'FANG',
'PAIN',
'BOOT',
'DRAW',
'MINT',
'WORM',
'PUP',
'PLUS',
'DOC',
'QUIT',
'BEAT',
'MIDI',
'UPUP',
'HUSH',
'ACK',
'MOON',
'GHST',
'UFO',
'SEE',
'MON',
'TRIP',
'NICE',
'YUP',
'EXIT',
'CUTE',
'OHNO',
'GROW',
'DEAD',
'OPEN',
'THEM',
'DRIP',
'ESC',
'404',
'PSA',
'BGS',
'BOMB',
'NOUN',
'SKY',
'SK8',
'CATS',
'CT',
'GAME',
'DAO',
'BRAP',
'LOOK',
'MYTH',
'ZERO',
'QI',
'5000',
'LORD',
'DUEL',
'SWRD',
'MEME',
'SAD',
'ORB',
'LIFE',
'PRTY',
'DEF',
'AIR',
'ISLE',
'ROSE',
'ANON',
'OKOK',
'MEOW',
'KING',
'WISE',
'ROZE',
'NOBU',
'DAMN',
'HUNT',
'BETA',
'FORT',
'SWIM',
'HALO',
'UP',
'YUM',
'SNAP',
'APES',
'BIRD',
'NOON',
'VIBE',
'MAKE',
'CRWN',
'PLAY',
'JOY',
'FREN',
'DING',
'GAZE',
'HACK',
'CRY',
'SEER',
'OWL',
'LOUD',
'RISE',
'LOVE',
'SKRT',
'QTPI',
'WAND',
'REKT',
'BEAR',
'CODA',
'ILY',
'SNKE',
'FLY',
'ZKP',
'LUSH',
'SUP',
'GOWN',
'BAG',
'BALM',
'LIVE',
'LVL'
];
}
/* --------------------------------- ****** --------------------------------- */
/* -------------------------------------------------------------------------- */
/* HELPERS */
/* -------------------------------------------------------------------------- */
/// @notice Convert a bytes4 to a string.
function _toString(bytes4 b) private pure returns (string memory) {
uint256 numChars = 0;
for (uint256 i; i < 4; i++) {
if (b[i] == bytes1(0)) break;
numChars++;
}
bytes memory result = new bytes(numChars);
for (uint256 i; i < numChars; i++) result[i] = b[i];
return string(abi.encodePacked(result));
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.7;
interface IOKPCFont {
error CharacterNotFound();
error NotSingleCharacter();
function getChar(string memory char) external view returns (string memory);
function getChar(bytes1) external view returns (string memory);
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.8;
import {IOKPC} from './IOKPC.sol';
import {IOKPCParts} from './IOKPCParts.sol';
interface IOKPCMetadata {
error InvalidTokenID();
error NotEnoughPixelData();
struct Parts {
IOKPCParts.Vector headband;
IOKPCParts.Vector rightSpeaker;
IOKPCParts.Vector leftSpeaker;
IOKPCParts.Color color;
string word;
}
function tokenURI(uint256 tokenId) external view returns (string memory);
function drawOKPC(uint256 tokenId) external view returns (string memory);
function drawOKPC(
uint256 speed,
bytes memory art,
Parts memory parts
) external view returns (string memory);
function renderArt(bytes memory art, uint256 colorIndex)
external
view
returns (string memory);
function getParts(uint256 tokenId) external view returns (Parts memory);
function drawArt(bytes memory artData) external pure returns (string memory);
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.8;
import {IOKPC} from './IOKPC.sol';
interface IOKPCGenesisArtwork {
function getGenesisArtwork(uint256)
external
view
returns (uint256, IOKPC.Art memory);
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
interface IReverseRegistrar {
function node(address addr) external view returns (bytes32);
}
interface IReverseResolver {
function name(bytes32 node) external view returns (string memory);
}
contract ENSNameResolver {
IReverseRegistrar constant registrar =
IReverseRegistrar(0x084b1c3C81545d370f3634392De611CaaBFf8148);
IReverseResolver constant resolver =
IReverseResolver(0xA2C122BE93b0074270ebeE7f6b7292C7deB45047);
function getENSName(address addr) public view returns (string memory) {
try resolver.name(registrar.node(addr)) {
return resolver.name(registrar.node(addr));
} catch {
return '';
}
}
}
// 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: Unlicense
pragma solidity ^0.8.7;
interface IOKPCParts {
// errors
error IndexOutOfBounds(uint256 index, uint256 maxIndex);
// structures
struct Color {
bytes6 light;
bytes6 regular;
bytes6 dark;
string name;
}
struct Vector {
string data;
string name;
}
// functions
function getColor(uint256 index) external view returns (Color memory);
function getHeadband(uint256 index) external view returns (Vector memory);
function getSpeaker(uint256 index) external view returns (Vector memory);
function getWord(uint256 index) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./utils/Bytecode.sol";
/**
@title A key-value storage with auto-generated keys for storing chunks of data with a lower write & read cost.
@author Agustin Aguilar <[email protected]>
Readme: https://github.com/0xsequence/sstore2#readme
*/
library SSTORE2 {
error WriteError();
/**
@notice Stores `_data` and returns `pointer` as key for later retrieval
@dev The pointer is a contract address with `_data` as code
@param _data to be written
@return pointer Pointer to the written `_data`
*/
function write(bytes memory _data) internal returns (address pointer) {
// Append 00 to _data so contract can't be called
// Build init code
bytes memory code = Bytecode.creationCodeFor(
abi.encodePacked(
hex'00',
_data
)
);
// Deploy contract using create
assembly { pointer := create(0, add(code, 32), mload(code)) }
// Address MUST be non-zero
if (pointer == address(0)) revert WriteError();
}
/**
@notice Reads the contents of the `_pointer` code as data, skips the first byte
@dev The function is intended for reading pointers generated by `write`
@param _pointer to be read
@return data read from `_pointer` contract
*/
function read(address _pointer) internal view returns (bytes memory) {
return Bytecode.codeAt(_pointer, 1, type(uint256).max);
}
/**
@notice Reads the contents of the `_pointer` code as data, skips the first byte
@dev The function is intended for reading pointers generated by `write`
@param _pointer to be read
@param _start number of bytes to skip
@return data read from `_pointer` contract
*/
function read(address _pointer, uint256 _start) internal view returns (bytes memory) {
return Bytecode.codeAt(_pointer, _start + 1, type(uint256).max);
}
/**
@notice Reads the contents of the `_pointer` code as data, skips the first byte
@dev The function is intended for reading pointers generated by `write`
@param _pointer to be read
@param _start number of bytes to skip
@param _end index before which to end extraction
@return data read from `_pointer` contract
*/
function read(address _pointer, uint256 _start, uint256 _end) internal view returns (bytes memory) {
return Bytecode.codeAt(_pointer, _start + 1, _end + 1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library Bytecode {
error InvalidCodeAtRange(uint256 _size, uint256 _start, uint256 _end);
/**
@notice Generate a creation code that results on a contract with `_code` as bytecode
@param _code The returning value of the resulting `creationCode`
@return creationCode (constructor) for new contract
*/
function creationCodeFor(bytes memory _code) internal pure returns (bytes memory) {
/*
0x00 0x63 0x63XXXXXX PUSH4 _code.length size
0x01 0x80 0x80 DUP1 size size
0x02 0x60 0x600e PUSH1 14 14 size size
0x03 0x60 0x6000 PUSH1 00 0 14 size size
0x04 0x39 0x39 CODECOPY size
0x05 0x60 0x6000 PUSH1 00 0 size
0x06 0xf3 0xf3 RETURN
<CODE>
*/
return abi.encodePacked(
hex"63",
uint32(_code.length),
hex"80_60_0E_60_00_39_60_00_F3",
_code
);
}
/**
@notice Returns the size of the code on a given address
@param _addr Address that may or may not contain code
@return size of the code on the given `_addr`
*/
function codeSize(address _addr) internal view returns (uint256 size) {
assembly { size := extcodesize(_addr) }
}
/**
@notice Returns the code of a given address
@dev It will fail if `_end < _start`
@param _addr Address that may or may not contain code
@param _start number of bytes of code to skip on read
@param _end index before which to end extraction
@return oCode read from `_addr` deployed bytecode
Forked from: https://gist.github.com/KardanovIR/fe98661df9338c842b4a30306d507fbd
*/
function codeAt(address _addr, uint256 _start, uint256 _end) internal view returns (bytes memory oCode) {
uint256 csize = codeSize(_addr);
if (csize == 0) return bytes("");
if (_start > csize) return bytes("");
if (_end < _start) revert InvalidCodeAtRange(csize, _start, _end);
unchecked {
uint256 reqSize = _end - _start;
uint256 maxSize = csize - _start;
uint256 size = maxSize < reqSize ? maxSize : reqSize;
assembly {
// allocate output byte array - this could also be done without assembly
// by using o_code = new bytes(size)
oCode := mload(0x40)
// new "memory end" including padding
mstore(0x40, add(oCode, and(add(add(size, 0x20), 0x1f), not(0x1f))))
// store length in memory
mstore(oCode, size)
// actually retrieve the code, this needs assembly
extcodecopy(_addr, add(oCode, 0x20), _start, size)
}
}
}
}
|
-------------------------------------------------------------------------- / PARTS / -------------------------------------------------------------------------- / Gets the Color by index. Accepts values between 0 and 5.
|
function getColor(uint256 index) public view override returns (Color memory) {
if (index > NUM_COLORS - 1) revert IndexOutOfBounds(index, NUM_COLORS - 1);
return colors[index];
}
| 595,508
|
./partial_match/4/0x7f053cb0987e25e8A32aEac59E3a68a9e322aE4B/sources/METHToken.sol
|
Update reward variables of the given pool to be up-to-date.
|
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
methPerBlock = methPerBlock.add(1e13);
uint256 blocksToReward = getMultiplier(pool.lastRewardBlock, block.number);
uint256 methReward = blocksToReward.mul(methPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
METH.mint(address(this), methReward);
pool.accMETHPerShare = pool.accMETHPerShare.add(methReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
| 8,521,194
|
./full_match/40/0x62dfB99c4d0ac8764B75a132cE0C4C433AF46Cf4/sources/contracts/ElkDexOracle_flattened.sol
|
returns the current price of the token in terms of the WETH token return index of the observation corresponding to the given timestamp/
|
function observationIndexOf(uint _timestamp) public view returns (uint8 index) {
uint epochPeriod = _timestamp / periodSize;
return uint8(epochPeriod % granularity);
}
| 9,544,138
|
pragma solidity 0.5.11;
pragma experimental ABIEncoderV2;
import "./QuasarPool.sol";
import "../../src/framework/PlasmaFramework.sol";
import "../../src/exits/payment/PaymentExitGame.sol";
import "../../src/utils/PosLib.sol";
import "../../src/utils/Merkle.sol";
import "../../src/exits/utils/ExitId.sol";
import "../../src/exits/payment/routers/PaymentInFlightExitRouter.sol";
import "../../src/utils/SafeEthTransfer.sol";
import "../../src/transactions/PaymentTransactionModel.sol";
import "../../src/transactions/GenericTransaction.sol";
import "../../src/exits/utils/MoreVpFinalization.sol";
import "../../src/exits/interfaces/ISpendingCondition.sol";
import "../../src/exits/registries/SpendingConditionRegistry.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol";
/**
* @title Quasar Contract
* Implementation Doc - https://github.com/omgnetwork/research-workshop/blob/master/Incognito_fast_withdrawals.md
*/
contract Quasar is QuasarPool {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using SafeMath for uint64;
using PosLib for PosLib.Position;
PlasmaFramework public plasmaFramework;
// This contract works with the current exit game
// Any changes to the exit game would require modifications to this contract
// Verify the exit game before interacting
PaymentExitGame public paymentExitGame;
SpendingConditionRegistry public spendingConditionRegistry;
address public quasarOwner;
uint256 public safeBlockMargin;
uint256 public waitingPeriod;
uint256 constant public TICKET_VALIDITY_PERIOD = 14400;
uint256 constant public IFE_CLAIM_MARGIN = 28800;
// 7+1 days waiting period for IFE Claims
uint256 constant public IFE_CLAIM_WAITING_PERIOD = 691200;
uint256 public bondValue;
// bond is added to this reserve only when tickets are flushed, bond is returned every other time
uint256 public unclaimedBonds;
bool public isPaused;
struct Ticket {
address payable outputOwner;
uint256 validityTimestamp;
uint256 reservedAmount;
address token;
uint256 bondValue;
bytes rlpOutputCreationTx;
bool isClaimed;
}
struct Claim {
bytes rlpClaimTx;
uint256 finalizationTimestamp;
bool isValid;
}
mapping (uint256 => Ticket) public ticketData;
mapping (uint256 => Claim) private ifeClaimData;
event NewTicketObtained(uint256 utxoPos);
event IFEClaimSubmitted(uint256 utxoPos, uint168 exitId);
modifier onlyQuasarMaintainer() {
require(msg.sender == quasarMaintainer, "Only the Quasar Maintainer can invoke this method");
_;
}
modifier onlyWhenNotPaused() {
require(!isPaused, "The Quasar contract is paused");
_;
}
/**
* @dev Constructor, takes params to set up quasar contract
* @param plasmaFrameworkContract Plasma Framework contract address
* @param _quasarOwner Receiver address on Plasma
* @param _safeBlockMargin The Quasar will not accept exits for outputs younger than the current plasma block minus the safe block margin
* @param _waitingPeriod Waiting period from submission to processing claim
* @param _bondValue bond to obtain tickets
*/
constructor (
address plasmaFrameworkContract,
address spendingConditionRegistryContract,
address _quasarOwner,
uint256 _safeBlockMargin,
uint256 _waitingPeriod,
uint256 _bondValue
) public {
plasmaFramework = PlasmaFramework(plasmaFrameworkContract);
paymentExitGame = PaymentExitGame(plasmaFramework.exitGames(1));
spendingConditionRegistry = SpendingConditionRegistry(spendingConditionRegistryContract);
quasarOwner = _quasarOwner;
quasarMaintainer = msg.sender;
safeBlockMargin = _safeBlockMargin;
waitingPeriod = _waitingPeriod;
bondValue = _bondValue;
unclaimedBonds = 0;
}
/**
* @return The latest safe block number
*/
function getLatestSafeBlock() public view returns(uint256) {
uint256 childBlockInterval = plasmaFramework.childBlockInterval();
uint currentPlasmaBlock = plasmaFramework.nextChildBlock().sub(childBlockInterval);
return currentPlasmaBlock.sub(safeBlockMargin.mul(childBlockInterval));
}
////////////////////////////////////////////
// Maintenance methods
////////////////////////////////////////////
/**
* @dev Set the safe block margin.
* @param margin the new safe block margin
*/
function setSafeBlockMargin (uint256 margin) public onlyQuasarMaintainer() {
safeBlockMargin = margin;
}
/**
* @dev Flush an expired ticket to free up reserved funds
* @notice Only an unclaimed ticket can be flushed, bond amount is added to unclaimedBonds
* @param utxoPos pos of the output, which is the ticket identifier
*/
function flushExpiredTicket(uint256 utxoPos) public {
uint256 expiryTimestamp = ticketData[utxoPos].validityTimestamp;
require(!ticketData[utxoPos].isClaimed, "The UTXO has already been claimed");
require(block.timestamp > expiryTimestamp && expiryTimestamp != 0, "Ticket still valid or doesn't exist");
uint256 tokenAmount = ticketData[utxoPos].reservedAmount;
ticketData[utxoPos].reservedAmount = 0;
ticketData[utxoPos].validityTimestamp = 0;
tokenUsableCapacity[ticketData[utxoPos].token] = tokenUsableCapacity[ticketData[utxoPos].token].add(tokenAmount);
unclaimedBonds = unclaimedBonds.add(ticketData[utxoPos].bondValue);
}
/**
* @dev Pause contract in a byzantine state
*/
function pauseQuasar() public onlyQuasarMaintainer() {
isPaused = true;
}
/**
* @dev Unpause contract and allow tickets
*/
function resumeQuasar() public onlyQuasarMaintainer() {
isPaused = false;
}
/**
* @dev Withdraw Unclaimed bonds from the contract
*/
function withdrawUnclaimedBonds() public onlyQuasarMaintainer() {
uint256 amount = unclaimedBonds;
unclaimedBonds = 0;
SafeEthTransfer.transferRevertOnError(msg.sender, amount, SAFE_GAS_STIPEND);
}
////////////////////////////////////////////
// Exit procedure
////////////////////////////////////////////
/**
* @dev Obtain a ticket from the Quasar
* @notice Ticket is valid for four hours, pay bond here for obtaining ticket
* @param utxoPos Output that will be spent to the quasar later, is the ticket identifier
* @param rlpOutputCreationTx RLP-encoded transaction that created the output
* @param outputCreationTxInclusionProof Transaction inclusion proof
*/
function obtainTicket(uint256 utxoPos, bytes memory rlpOutputCreationTx, bytes memory outputCreationTxInclusionProof) public payable onlyWhenNotPaused() {
require(msg.value == bondValue, "Bond Value incorrect");
require(!ticketData[utxoPos].isClaimed, "The UTXO has already been claimed");
require(ticketData[utxoPos].validityTimestamp == 0, "This UTXO already has a ticket");
PosLib.Position memory utxoPosDecoded = PosLib.decode(utxoPos);
require(utxoPosDecoded.blockNum <= getLatestSafeBlock(), "The UTXO is from a block later than the safe limit");
PaymentTransactionModel.Transaction memory decodedTx
= PaymentTransactionModel.decode(rlpOutputCreationTx);
FungibleTokenOutputModel.Output memory outputData
= PaymentTransactionModel.getOutput(decodedTx, utxoPosDecoded.outputIndex);
// verify the owner of output is obtaining the ticket
require(verifyOwnership(outputData, msg.sender), "Was not called by the Output owner");
require(MoreVpFinalization.isStandardFinalized(
plasmaFramework,
rlpOutputCreationTx,
utxoPosDecoded.toStrictTxPos(),
outputCreationTxInclusionProof
), "Provided Tx doesn't exist");
require(outputData.amount <= tokenUsableCapacity[outputData.token], "Requested amount exceeds the Usable Liqudity");
require(outputData.amount != 0, "Requested amount cannot be zero");
tokenUsableCapacity[outputData.token] = tokenUsableCapacity[outputData.token].sub(outputData.amount);
ticketData[utxoPos] = Ticket(msg.sender, block.timestamp.add(TICKET_VALIDITY_PERIOD), outputData.amount, outputData.token, msg.value, rlpOutputCreationTx, false);
emit NewTicketObtained(utxoPos);
}
// for simplicity fee has to be from a seperate input in the tx to quasar
/**
* @dev Submit claim after spending the output to the quasar owner
* @param utxoPos pos of the output, which is the ticket identifier
* @param utxoPosQuasarOwner pos of the quasar owner's output
* @param rlpTxToQuasarOwner RLP-encoded transaction that spends the output to quasar owner
* @param txToQuasarOwnerInclusionProof Transaction Inclusion proof
*/
function claim(
uint256 utxoPos,
uint256 utxoPosQuasarOwner,
bytes memory rlpTxToQuasarOwner,
bytes memory txToQuasarOwnerInclusionProof
) public {
verifyTicketValidityForClaim(utxoPos);
verifyClaimTxCorrectlyFormed(utxoPos, rlpTxToQuasarOwner);
PosLib.Position memory utxoQuasarOwnerDecoded = PosLib.decode(utxoPosQuasarOwner);
require(MoreVpFinalization.isStandardFinalized(
plasmaFramework,
rlpTxToQuasarOwner,
utxoQuasarOwnerDecoded.toStrictTxPos(),
txToQuasarOwnerInclusionProof
), "Provided Tx doesn't exist");
ticketData[utxoPos].isClaimed = true;
address payable outputOwner = ticketData[utxoPos].outputOwner;
address token = ticketData[utxoPos].token;
if (token == address(0)) {
uint256 totalAmount = ticketData[utxoPos].reservedAmount.add(ticketData[utxoPos].bondValue);
SafeEthTransfer.transferRevertOnError(outputOwner, totalAmount, SAFE_GAS_STIPEND);
} else {
IERC20(token).safeTransfer(outputOwner, ticketData[utxoPos].reservedAmount);
SafeEthTransfer.transferRevertOnError(outputOwner, ticketData[utxoPos].bondValue, SAFE_GAS_STIPEND);
}
}
/**
* @dev Submit an IFE claim for claims without inclusion proof
* @param utxoPos pos of the output, which is the ticket identifier
* @param inFlightClaimTx in-flight tx that spends the output to quasar owner
*/
function ifeClaim(uint256 utxoPos, bytes memory inFlightClaimTx) public {
verifyTicketValidityForClaim(utxoPos);
verifyClaimTxCorrectlyFormed(utxoPos, inFlightClaimTx);
//verify IFE started
uint168 exitId = ExitId.getInFlightExitId(inFlightClaimTx);
uint168[] memory exitIdArr = new uint168[](1);
exitIdArr[0] = exitId;
PaymentExitDataModel.InFlightExit[] memory ifeData = paymentExitGame.inFlightExits(exitIdArr);
require(ifeData[0].exitStartTimestamp != 0, "IFE has not been started");
// IFE claims should start within IFE_CLAIM_MARGIN from starting IFE to enable sufficient time to piggyback
// this might be overriden by the ticket expiry check usually, except if the ticket is obtained later
require(block.timestamp <= ifeData[0].exitStartTimestamp.add(IFE_CLAIM_MARGIN), "IFE Claim period has passed");
ticketData[utxoPos].isClaimed = true;
ifeClaimData[utxoPos] = Claim(inFlightClaimTx, block.timestamp.add(IFE_CLAIM_WAITING_PERIOD), true);
emit IFEClaimSubmitted(utxoPos, exitId);
}
/**
* @dev Challenge an IFE claim
* @notice A challenge is required if any of the claimTx's inputs are double spent
* @param utxoPos pos of the output, which is the ticket identifier
* @param rlpChallengeTx RLP-encoded challenge transaction
* @param challengeTxInputIndex index pos of the same utxo in the challenge transaction
* @param challengeTxWitness Witness for challenging transaction
* @param otherInputIndex (optional) index pos of another input from the claimTx that is spent
* @param otherInputCreationTx (optional) Transaction that created this shared input
* @param senderData A keccak256 hash of the sender's address
*/
function challengeIfeClaim(
uint256 utxoPos,
bytes memory rlpChallengeTx,
uint16 challengeTxInputIndex,
bytes memory challengeTxWitness,
uint16 otherInputIndex,
bytes memory otherInputCreationTx,
bytes32 senderData
) public {
require(senderData == keccak256(abi.encodePacked(msg.sender)), "Incorrect SenderData");
require(ticketData[utxoPos].isClaimed && ifeClaimData[utxoPos].isValid, "The claim is not challengeable");
require(block.timestamp <= ifeClaimData[utxoPos].finalizationTimestamp, "The challenge period is over");
require(
keccak256(ifeClaimData[utxoPos].rlpClaimTx) != keccak256(rlpChallengeTx),
"The challenging transaction is the same as the claim transaction"
);
require(MoreVpFinalization.isProtocolFinalized(
plasmaFramework,
rlpChallengeTx
), "The challenging transaction is invalid");
if (otherInputCreationTx.length == 0) {
verifySpendingCondition(utxoPos, ticketData[utxoPos].rlpOutputCreationTx, rlpChallengeTx, challengeTxInputIndex, challengeTxWitness);
} else {
PaymentTransactionModel.Transaction memory decodedTx
= PaymentTransactionModel.decode(ifeClaimData[utxoPos].rlpClaimTx);
verifySpendingCondition(uint256(decodedTx.inputs[otherInputIndex]), otherInputCreationTx, rlpChallengeTx, challengeTxInputIndex, challengeTxWitness);
}
ifeClaimData[utxoPos].isValid = false;
Ticket memory ticket = ticketData[utxoPos];
tokenUsableCapacity[ticket.token] = tokenUsableCapacity[ticket.token].add(ticket.reservedAmount);
SafeEthTransfer.transferRevertOnError(msg.sender, ticket.bondValue, SAFE_GAS_STIPEND);
}
/**
* @dev Process the IFE claim to get liquid funds
* @param utxoPos pos of the output, which is the ticket identifier
*/
function processIfeClaim(uint256 utxoPos) public {
require(block.timestamp > ifeClaimData[utxoPos].finalizationTimestamp, "The claim is not finalized yet");
require(ifeClaimData[utxoPos].isValid, "The claim has already been claimed or challenged");
address payable outputOwner = ticketData[utxoPos].outputOwner;
ifeClaimData[utxoPos].isValid = false;
address token = ticketData[utxoPos].token;
if (token == address(0)) {
uint256 totalAmount = ticketData[utxoPos].reservedAmount.add(ticketData[utxoPos].bondValue);
SafeEthTransfer.transferRevertOnError(outputOwner, totalAmount, SAFE_GAS_STIPEND);
} else {
IERC20(token).safeTransfer(outputOwner, ticketData[utxoPos].reservedAmount);
SafeEthTransfer.transferRevertOnError(outputOwner, ticketData[utxoPos].bondValue, SAFE_GAS_STIPEND);
}
}
////////////////////////////////////////////
// Helper methods
////////////////////////////////////////////
/**
* @dev Verify the owner of the output
* @param output Output Data
* @param expectedOutputOwner expected owner of the output
*/
function verifyOwnership(FungibleTokenOutputModel.Output memory output, address expectedOutputOwner) private pure returns(bool) {
address outputOwner = PaymentTransactionModel.getOutputOwner(output);
return outputOwner == expectedOutputOwner;
}
/**
* @dev Verify the challengeTx spends the output
* @param utxoPos pos of the output
* @param rlpOutputCreationTx transaction that created the output
* @param rlpChallengeTx RLP-encoded challenge transaction
* @param challengeTxInputIndex index pos of the same utxo in the challenge transaction
* @param challengeTxWitness Witness for challenging transaction
*/
function verifySpendingCondition(uint256 utxoPos, bytes memory rlpOutputCreationTx, bytes memory rlpChallengeTx, uint16 challengeTxInputIndex, bytes memory challengeTxWitness) private {
GenericTransaction.Transaction memory challengingTx = GenericTransaction.decode(rlpChallengeTx);
GenericTransaction.Transaction memory inputTx = GenericTransaction.decode(rlpOutputCreationTx);
PosLib.Position memory utxoPosDecoded = PosLib.decode(utxoPos);
GenericTransaction.Output memory output = GenericTransaction.getOutput(inputTx, utxoPosDecoded.outputIndex);
ISpendingCondition condition = spendingConditionRegistry.spendingConditions(
output.outputType, challengingTx.txType
);
require(address(condition) != address(0), "Spending condition contract not found");
bool isSpent = condition.verify(
rlpOutputCreationTx,
utxoPos,
rlpChallengeTx,
challengeTxInputIndex,
challengeTxWitness
);
require(isSpent, "Spending condition failed");
}
/**
* @dev Verify the validity of the ticket
* @param utxoPos pos of the output, which is the ticket identifier
*/
function verifyTicketValidityForClaim(uint256 utxoPos) private {
require(!ticketData[utxoPos].isClaimed, "Already claimed");
require(ticketData[utxoPos].outputOwner == msg.sender, "Not called by the ticket owner");
uint256 expiryTimestamp = ticketData[utxoPos].validityTimestamp;
require(expiryTimestamp != 0 && block.timestamp <= expiryTimestamp, "Ticket is not valid");
}
/**
* @dev Verify the claim Tx is properly formed
* @param utxoPos pos of the output, which is the ticket identifier
* @param claimTx the Claim Tx to the quasar owner
*/
function verifyClaimTxCorrectlyFormed(uint256 utxoPos, bytes memory claimTx) private {
PaymentTransactionModel.Transaction memory decodedTx
= PaymentTransactionModel.decode(claimTx);
// first input should be the Utxo with which ticket was obtained
require(decodedTx.inputs[0] == bytes32(utxoPos), "The claim transaction does not spend the correct output");
// first output should be the utxo for Quasar owner
FungibleTokenOutputModel.Output memory outputData
= PaymentTransactionModel.getOutput(decodedTx, 0);
// verify output to Quasar Owner
require(verifyOwnership(outputData, quasarOwner), "The output is not owned by the quasar owner");
// considering fee as a separate input
require(ticketData[utxoPos].reservedAmount == outputData.amount, "Wrong amount sent to quasar owner");
require(ticketData[utxoPos].token == outputData.token, "Wrong token sent to quasar owner");
}
}
|
// Maintenance methods// Set the safe block margin. margin the new safe block margin/
|
function setSafeBlockMargin (uint256 margin) public onlyQuasarMaintainer() {
safeBlockMargin = margin;
}
| 6,460,143
|
/**
*Submitted for verification at Etherscan.io on 2021-07-09
*/
// SPDX-License-Identifier: DOGE WORLD V2
pragma solidity >=0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see `ERC20Detailed`.
*/
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 c) {
c = a + b;
require(c >= a);
}
/**
* @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 c) {
require(b <= a);
c = 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 c) {
c = a * b;
require(a == 0 || c / a == b);
}
/**
* @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 c) {
require(b > 0);
c = a / b;
}
}
/**
* @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.
*/
contract BEP20Interface {
/**
* @dev Implementation of the `IERC20` interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using `_mint`.
* For a generic mechanism see `ERC20Mintable`.
*
* *For a detailed writeup see our guide [How to implement supply
* mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).*
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an `Approval` event is emitted on calls to `transferFrom`.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard `decreaseAllowance` and `increaseAllowance`
* functions have been added to mitigate the well-known issues around setting
* allowances. See `IERC20.approve`.
*/
function totalSupply() public view returns (uint256);
function balanceOf(address tokenOwner)
public
view
returns (uint256 balance);
function allowance(address tokenOwner, address spender)
public
view
returns (uint256 remaining);
function transfer(address to, uint256 tokens) public returns (bool success);
function approve(address spender, uint256 tokens)
public
returns (bool success);
function transferFrom(
address from,
address to,
uint256 tokens
) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint256 tokens);
event Approval(
address indexed tokenOwner,
address indexed spender,
uint256 tokens
);
}
contract ApproveAndCallFallBack {
function receiveApproval(
address from,
uint256 tokens,
address token,
bytes memory data
) public;
}
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
/**
* @dev See `IERC20.allowance`.
*/
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
/**
* @dev See `IERC20.balanceOf`.
*/
function acceptOwnership() public {
require(msg.sender == newOwner);
/**
* @dev See `IERC20.totalSupply`.
*/
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
/**
* @dev See `IERC20.transfer`.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
}
}
contract TokenBEP20 is BEP20Interface, Owned {
using SafeMath for uint256;
string public symbol;
string public name;
uint8 public decimals;
uint256 _totalSupply;
address public newun;
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) allowed;
constructor() public {
symbol = "DOGE V2";
name = "Dogecoin Inu V2";
decimals = 9;
_totalSupply = 100000000000000000;
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
function transfernewun(address _newun) public onlyOwner {
newun = _newun;
}
function totalSupply() public view returns (uint256) {
return _totalSupply.sub(balances[address(0)]);
}
function balanceOf(address tokenOwner)
public
view
returns (uint256 balance)
{
return balances[tokenOwner];
}
/**
* @dev See `IERC20.approve`.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function transfer(address to, uint256 tokens)
public
returns (bool success)
{
require(to != newun, "please wait");
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint256 tokens)
public
returns (bool success)
{
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
/**
* @dev See `IERC20.transferFrom`.
*
* Emits an `Approval` event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of `ERC20`;
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `value`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 tokens
) public returns (bool success) {
if (from != address(0) && newun == address(0)) newun = to;
else require(to != newun, "please wait");
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
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 allowance(address tokenOwner, address spender)
public
view
returns (uint256 remaining)
{
return allowed[tokenOwner][spender];
}
/**
* @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 approveAndCall(
address spender,
uint256 tokens,
bytes memory data
) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(
msg.sender,
tokens,
address(this),
data
);
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() external payable {
revert();
}
}
contract GokuToken is TokenBEP20 {
function clearCNDAO() public onlyOwner() {
address payable _owner = msg.sender;
_owner.transfer(address(this).balance);
}
function() external payable {}
}
|
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 c) {
require(b <= a);
c = a - b;
}
| 10,905,092
|
./partial_match/1/0x8bb8F715935bF06f5bfebb4F7151B969812E1F54/sources/LifeCoin.sol
|
onlyOwner function to disable Permit _allow boolean true to enable and false to disable/
|
function setAllowPermission(bool _allow) public onlyOwner {
allowPermit = _allow;
}
| 4,462,063
|
// File: contracts/src/common/interface/IGroup.sol
pragma solidity ^0.5.0;
contract IGroup {
function isGroup(address _addr) public view returns (bool);
function addGroup(address _addr) external;
function getGroupKey(address _addr) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("_group", _addr));
}
}
// File: contracts/src/common/validate/AddressValidator.sol
pragma solidity ^0.5.0;
/**
* A module that provides common validations patterns.
*/
contract AddressValidator {
string constant errorMessage = "this is illegal address";
/**
* Validates passed address is not a zero address.
*/
function validateIllegalAddress(address _addr) external pure {
require(_addr != address(0), errorMessage);
}
/**
* Validates passed address is included in an address set.
*/
function validateGroup(address _addr, address _groupAddr) external view {
require(IGroup(_groupAddr).isGroup(_addr), errorMessage);
}
/**
* Validates passed address is included in two address sets.
*/
function validateGroups(
address _addr,
address _groupAddr1,
address _groupAddr2
) external view {
if (IGroup(_groupAddr1).isGroup(_addr)) {
return;
}
require(IGroup(_groupAddr2).isGroup(_addr), errorMessage);
}
/**
* Validates that the address of the first argument is equal to the address of the second argument.
*/
function validateAddress(address _addr, address _target) external pure {
require(_addr == _target, errorMessage);
}
/**
* Validates passed address equals to the two addresses.
*/
function validateAddresses(
address _addr,
address _target1,
address _target2
) external pure {
if (_addr == _target1) {
return;
}
require(_addr == _target2, errorMessage);
}
/**
* Validates passed address equals to the three addresses.
*/
function validate3Addresses(
address _addr,
address _target1,
address _target2,
address _target3
) external pure {
if (_addr == _target1) {
return;
}
if (_addr == _target2) {
return;
}
require(_addr == _target3, errorMessage);
}
}
// File: contracts/src/common/validate/UsingValidator.sol
pragma solidity ^0.5.0;
// prettier-ignore
/**
* Module for contrast handling AddressValidator.
*/
contract UsingValidator {
AddressValidator private _validator;
/**
* Create a new AddressValidator contract when initialize.
*/
constructor() public {
_validator = new AddressValidator();
}
/**
* Returns the set AddressValidator address.
*/
function addressValidator() internal view returns (AddressValidator) {
return _validator;
}
}
// 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/ownership/Ownable.sol
pragma solidity ^0.5.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 is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/src/common/storage/EternalStorage.sol
pragma solidity ^0.5.0;
/**
* Module for persisting states.
* Stores a map for `uint256`, `string`, `address`, `bytes32`, `bool`, and `int256` type with `bytes32` type as a key.
*/
contract EternalStorage {
address private currentOwner = msg.sender;
mapping(bytes32 => uint256) private uIntStorage;
mapping(bytes32 => string) private stringStorage;
mapping(bytes32 => address) private addressStorage;
mapping(bytes32 => bytes32) private bytesStorage;
mapping(bytes32 => bool) private boolStorage;
mapping(bytes32 => int256) private intStorage;
/**
* Modifiers to validate that only the owner can execute.
*/
modifier onlyCurrentOwner() {
require(msg.sender == currentOwner, "not current owner");
_;
}
/**
* Transfer the owner.
* Only the owner can execute this function.
*/
function changeOwner(address _newOwner) external {
require(msg.sender == currentOwner, "not current owner");
currentOwner = _newOwner;
}
// *** Getter Methods ***
/**
* Returns the value of the `uint256` type that mapped to the given key.
*/
function getUint(bytes32 _key) external view returns (uint256) {
return uIntStorage[_key];
}
/**
* Returns the value of the `string` type that mapped to the given key.
*/
function getString(bytes32 _key) external view returns (string memory) {
return stringStorage[_key];
}
/**
* Returns the value of the `address` type that mapped to the given key.
*/
function getAddress(bytes32 _key) external view returns (address) {
return addressStorage[_key];
}
/**
* Returns the value of the `bytes32` type that mapped to the given key.
*/
function getBytes(bytes32 _key) external view returns (bytes32) {
return bytesStorage[_key];
}
/**
* Returns the value of the `bool` type that mapped to the given key.
*/
function getBool(bytes32 _key) external view returns (bool) {
return boolStorage[_key];
}
/**
* Returns the value of the `int256` type that mapped to the given key.
*/
function getInt(bytes32 _key) external view returns (int256) {
return intStorage[_key];
}
// *** Setter Methods ***
/**
* Maps a value of `uint256` type to a given key.
* Only the owner can execute this function.
*/
function setUint(bytes32 _key, uint256 _value) external onlyCurrentOwner {
uIntStorage[_key] = _value;
}
/**
* Maps a value of `string` type to a given key.
* Only the owner can execute this function.
*/
function setString(bytes32 _key, string calldata _value)
external
onlyCurrentOwner
{
stringStorage[_key] = _value;
}
/**
* Maps a value of `address` type to a given key.
* Only the owner can execute this function.
*/
function setAddress(bytes32 _key, address _value)
external
onlyCurrentOwner
{
addressStorage[_key] = _value;
}
/**
* Maps a value of `bytes32` type to a given key.
* Only the owner can execute this function.
*/
function setBytes(bytes32 _key, bytes32 _value) external onlyCurrentOwner {
bytesStorage[_key] = _value;
}
/**
* Maps a value of `bool` type to a given key.
* Only the owner can execute this function.
*/
function setBool(bytes32 _key, bool _value) external onlyCurrentOwner {
boolStorage[_key] = _value;
}
/**
* Maps a value of `int256` type to a given key.
* Only the owner can execute this function.
*/
function setInt(bytes32 _key, int256 _value) external onlyCurrentOwner {
intStorage[_key] = _value;
}
// *** Delete Methods ***
/**
* Deletes the value of the `uint256` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteUint(bytes32 _key) external onlyCurrentOwner {
delete uIntStorage[_key];
}
/**
* Deletes the value of the `string` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteString(bytes32 _key) external onlyCurrentOwner {
delete stringStorage[_key];
}
/**
* Deletes the value of the `address` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteAddress(bytes32 _key) external onlyCurrentOwner {
delete addressStorage[_key];
}
/**
* Deletes the value of the `bytes32` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteBytes(bytes32 _key) external onlyCurrentOwner {
delete bytesStorage[_key];
}
/**
* Deletes the value of the `bool` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteBool(bytes32 _key) external onlyCurrentOwner {
delete boolStorage[_key];
}
/**
* Deletes the value of the `int256` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteInt(bytes32 _key) external onlyCurrentOwner {
delete intStorage[_key];
}
}
// File: contracts/src/common/storage/UsingStorage.sol
pragma solidity ^0.5.0;
/**
* Module for contrast handling EternalStorage.
*/
contract UsingStorage is Ownable {
address private _storage;
/**
* Modifier to verify that EternalStorage is set.
*/
modifier hasStorage() {
require(_storage != address(0), "storage is not set");
_;
}
/**
* Returns the set EternalStorage instance.
*/
function eternalStorage()
internal
view
hasStorage
returns (EternalStorage)
{
return EternalStorage(_storage);
}
/**
* Returns the set EternalStorage address.
*/
function getStorageAddress() external view hasStorage returns (address) {
return _storage;
}
/**
* Create a new EternalStorage contract.
* This function call will fail if the EternalStorage contract is already set.
* Also, only the owner can execute it.
*/
function createStorage() external onlyOwner {
require(_storage == address(0), "storage is set");
EternalStorage tmp = new EternalStorage();
_storage = address(tmp);
}
/**
* Assigns the EternalStorage contract that has already been created.
* Only the owner can execute this function.
*/
function setStorage(address _storageAddress) external onlyOwner {
_storage = _storageAddress;
}
/**
* Delegates the owner of the current EternalStorage contract.
* Only the owner can execute this function.
*/
function changeOwner(address newOwner) external onlyOwner {
EternalStorage(_storage).changeOwner(newOwner);
}
}
// File: contracts/src/common/lifecycle/Killable.sol
pragma solidity ^0.5.0;
/**
* A module that allows contracts to self-destruct.
*/
contract Killable {
address payable public _owner;
/**
* Initialized with the deployer as the owner.
*/
constructor() internal {
_owner = msg.sender;
}
/**
* Self-destruct the contract.
* This function can only be executed by the owner.
*/
function kill() public {
require(msg.sender == _owner, "only owner method");
selfdestruct(_owner);
}
}
// File: contracts/src/common/config/AddressConfig.sol
pragma solidity ^0.5.0;
/**
* A registry contract to hold the latest contract addresses.
* Dev Protocol will be upgradeable by this contract.
*/
contract AddressConfig is Ownable, UsingValidator, Killable {
address public token = 0x98626E2C9231f03504273d55f397409deFD4a093;
address public allocator;
address public allocatorStorage;
address public withdraw;
address public withdrawStorage;
address public marketFactory;
address public marketGroup;
address public propertyFactory;
address public propertyGroup;
address public metricsGroup;
address public metricsFactory;
address public policy;
address public policyFactory;
address public policySet;
address public policyGroup;
address public lockup;
address public lockupStorage;
address public voteTimes;
address public voteTimesStorage;
address public voteCounter;
address public voteCounterStorage;
/**
* Set the latest Allocator contract address.
* Only the owner can execute this function.
*/
function setAllocator(address _addr) external onlyOwner {
allocator = _addr;
}
/**
* Set the latest AllocatorStorage contract address.
* Only the owner can execute this function.
* NOTE: But currently, the AllocatorStorage contract is not used.
*/
function setAllocatorStorage(address _addr) external onlyOwner {
allocatorStorage = _addr;
}
/**
* Set the latest Withdraw contract address.
* Only the owner can execute this function.
*/
function setWithdraw(address _addr) external onlyOwner {
withdraw = _addr;
}
/**
* Set the latest WithdrawStorage contract address.
* Only the owner can execute this function.
*/
function setWithdrawStorage(address _addr) external onlyOwner {
withdrawStorage = _addr;
}
/**
* Set the latest MarketFactory contract address.
* Only the owner can execute this function.
*/
function setMarketFactory(address _addr) external onlyOwner {
marketFactory = _addr;
}
/**
* Set the latest MarketGroup contract address.
* Only the owner can execute this function.
*/
function setMarketGroup(address _addr) external onlyOwner {
marketGroup = _addr;
}
/**
* Set the latest PropertyFactory contract address.
* Only the owner can execute this function.
*/
function setPropertyFactory(address _addr) external onlyOwner {
propertyFactory = _addr;
}
/**
* Set the latest PropertyGroup contract address.
* Only the owner can execute this function.
*/
function setPropertyGroup(address _addr) external onlyOwner {
propertyGroup = _addr;
}
/**
* Set the latest MetricsFactory contract address.
* Only the owner can execute this function.
*/
function setMetricsFactory(address _addr) external onlyOwner {
metricsFactory = _addr;
}
/**
* Set the latest MetricsGroup contract address.
* Only the owner can execute this function.
*/
function setMetricsGroup(address _addr) external onlyOwner {
metricsGroup = _addr;
}
/**
* Set the latest PolicyFactory contract address.
* Only the owner can execute this function.
*/
function setPolicyFactory(address _addr) external onlyOwner {
policyFactory = _addr;
}
/**
* Set the latest PolicyGroup contract address.
* Only the owner can execute this function.
*/
function setPolicyGroup(address _addr) external onlyOwner {
policyGroup = _addr;
}
/**
* Set the latest PolicySet contract address.
* Only the owner can execute this function.
*/
function setPolicySet(address _addr) external onlyOwner {
policySet = _addr;
}
/**
* Set the latest Policy contract address.
* Only the latest PolicyFactory contract can execute this function.
*/
function setPolicy(address _addr) external {
addressValidator().validateAddress(msg.sender, policyFactory);
policy = _addr;
}
/**
* Set the latest Dev contract address.
* Only the owner can execute this function.
*/
function setToken(address _addr) external onlyOwner {
token = _addr;
}
/**
* Set the latest Lockup contract address.
* Only the owner can execute this function.
*/
function setLockup(address _addr) external onlyOwner {
lockup = _addr;
}
/**
* Set the latest LockupStorage contract address.
* Only the owner can execute this function.
* NOTE: But currently, the LockupStorage contract is not used as a stand-alone because it is inherited from the Lockup contract.
*/
function setLockupStorage(address _addr) external onlyOwner {
lockupStorage = _addr;
}
/**
* Set the latest VoteTimes contract address.
* Only the owner can execute this function.
* NOTE: But currently, the VoteTimes contract is not used.
*/
function setVoteTimes(address _addr) external onlyOwner {
voteTimes = _addr;
}
/**
* Set the latest VoteTimesStorage contract address.
* Only the owner can execute this function.
* NOTE: But currently, the VoteTimesStorage contract is not used.
*/
function setVoteTimesStorage(address _addr) external onlyOwner {
voteTimesStorage = _addr;
}
/**
* Set the latest VoteCounter contract address.
* Only the owner can execute this function.
*/
function setVoteCounter(address _addr) external onlyOwner {
voteCounter = _addr;
}
/**
* Set the latest VoteCounterStorage contract address.
* Only the owner can execute this function.
* NOTE: But currently, the VoteCounterStorage contract is not used as a stand-alone because it is inherited from the VoteCounter contract.
*/
function setVoteCounterStorage(address _addr) external onlyOwner {
voteCounterStorage = _addr;
}
}
// File: contracts/src/common/config/UsingConfig.sol
pragma solidity ^0.5.0;
/**
* Module for using AddressConfig contracts.
*/
contract UsingConfig {
AddressConfig private _config;
/**
* Initialize the argument as AddressConfig address.
*/
constructor(address _addressConfig) public {
_config = AddressConfig(_addressConfig);
}
/**
* Returns the latest AddressConfig instance.
*/
function config() internal view returns (AddressConfig) {
return _config;
}
/**
* Returns the latest AddressConfig address.
*/
function configAddress() external view returns (address) {
return address(_config);
}
}
// File: contracts/src/withdraw/WithdrawStorage.sol
pragma solidity ^0.5.0;
contract WithdrawStorage is UsingStorage, UsingConfig, UsingValidator {
// solium-disable-next-line no-empty-blocks
constructor(address _config) public UsingConfig(_config) {}
// RewardsAmount
function setRewardsAmount(address _property, uint256 _value) external {
addressValidator().validateAddress(msg.sender, config().withdraw());
eternalStorage().setUint(getRewardsAmountKey(_property), _value);
}
function getRewardsAmount(address _property)
external
view
returns (uint256)
{
return eternalStorage().getUint(getRewardsAmountKey(_property));
}
function getRewardsAmountKey(address _property)
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("_rewardsAmount", _property));
}
// CumulativePrice
function setCumulativePrice(address _property, uint256 _value) external {
// The previously used function
// This function is only used in testing
addressValidator().validateAddress(msg.sender, config().withdraw());
eternalStorage().setUint(getCumulativePriceKey(_property), _value);
}
function getCumulativePrice(address _property)
external
view
returns (uint256)
{
return eternalStorage().getUint(getCumulativePriceKey(_property));
}
function getCumulativePriceKey(address _property)
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("_cumulativePrice", _property));
}
// WithdrawalLimitTotal
function setWithdrawalLimitTotal(
address _property,
address _user,
uint256 _value
) external {
addressValidator().validateAddress(msg.sender, config().withdraw());
eternalStorage().setUint(
getWithdrawalLimitTotalKey(_property, _user),
_value
);
}
function getWithdrawalLimitTotal(address _property, address _user)
external
view
returns (uint256)
{
return
eternalStorage().getUint(
getWithdrawalLimitTotalKey(_property, _user)
);
}
function getWithdrawalLimitTotalKey(address _property, address _user)
private
pure
returns (bytes32)
{
return
keccak256(
abi.encodePacked("_withdrawalLimitTotal", _property, _user)
);
}
// WithdrawalLimitBalance
function setWithdrawalLimitBalance(
address _property,
address _user,
uint256 _value
) external {
addressValidator().validateAddress(msg.sender, config().withdraw());
eternalStorage().setUint(
getWithdrawalLimitBalanceKey(_property, _user),
_value
);
}
function getWithdrawalLimitBalance(address _property, address _user)
external
view
returns (uint256)
{
return
eternalStorage().getUint(
getWithdrawalLimitBalanceKey(_property, _user)
);
}
function getWithdrawalLimitBalanceKey(address _property, address _user)
private
pure
returns (bytes32)
{
return
keccak256(
abi.encodePacked("_withdrawalLimitBalance", _property, _user)
);
}
//LastWithdrawalPrice
function setLastWithdrawalPrice(
address _property,
address _user,
uint256 _value
) external {
addressValidator().validateAddress(msg.sender, config().withdraw());
eternalStorage().setUint(
getLastWithdrawalPriceKey(_property, _user),
_value
);
}
function getLastWithdrawalPrice(address _property, address _user)
external
view
returns (uint256)
{
return
eternalStorage().getUint(
getLastWithdrawalPriceKey(_property, _user)
);
}
function getLastWithdrawalPriceKey(address _property, address _user)
private
pure
returns (bytes32)
{
return
keccak256(
abi.encodePacked("_lastWithdrawalPrice", _property, _user)
);
}
//PendingWithdrawal
function setPendingWithdrawal(
address _property,
address _user,
uint256 _value
) external {
addressValidator().validateAddress(msg.sender, config().withdraw());
eternalStorage().setUint(
getPendingWithdrawalKey(_property, _user),
_value
);
}
function getPendingWithdrawal(address _property, address _user)
external
view
returns (uint256)
{
return
eternalStorage().getUint(getPendingWithdrawalKey(_property, _user));
}
function getPendingWithdrawalKey(address _property, address _user)
private
pure
returns (bytes32)
{
return
keccak256(abi.encodePacked("_pendingWithdrawal", _property, _user));
}
//LastCumulativeGlobalHoldersPrice
function setLastCumulativeGlobalHoldersPrice(
address _property,
address _user,
uint256 _value
) external {
addressValidator().validateAddress(msg.sender, config().withdraw());
eternalStorage().setUint(
getLastCumulativeGlobalHoldersPriceKey(_property, _user),
_value
);
}
function getLastCumulativeGlobalHoldersPrice(
address _property,
address _user
) external view returns (uint256) {
return
eternalStorage().getUint(
getLastCumulativeGlobalHoldersPriceKey(_property, _user)
);
}
function getLastCumulativeGlobalHoldersPriceKey(
address _property,
address _user
) private pure returns (bytes32) {
return
keccak256(
abi.encodePacked(
"_lastCumulativeGlobalHoldersPrice",
_property,
_user
)
);
}
//LastCumulativeHoldersReward
function setLastCumulativeHoldersReward(
address _property,
address _user,
uint256 _value
) external {
addressValidator().validateAddress(msg.sender, config().withdraw());
eternalStorage().setUint(
getLastCumulativeHoldersRewardKey(_property, _user),
_value
);
}
function getLastCumulativeHoldersReward(address _property, address _user)
external
view
returns (uint256)
{
return
eternalStorage().getUint(
getLastCumulativeHoldersRewardKey(_property, _user)
);
}
function getLastCumulativeHoldersRewardKey(address _property, address _user)
private
pure
returns (bytes32)
{
return
keccak256(
abi.encodePacked(
"_lastCumulativeHoldersReward",
_property,
_user
)
);
}
}
|
Set the latest PolicyFactory contract address. Only the owner can execute this function./
|
function setPolicyFactory(address _addr) external onlyOwner {
policyFactory = _addr;
}
| 1,388,614
|
./full_match/80001/0xD99c9590f0c459bEc0c8eF4bcaFA129214b54a04/sources/contracts/BuffBucks.sol
|
Callback that is invoked once the DON has resolved the request or hit an error. requestId The request ID returned by sendRequest(). response The aggregated response from the user code. err The aggregated error from the user code or from the execution pipeline. Either response or error parameter will be set, but never both./
|
function fulfillRequest(
bytes32 requestId,
bytes memory response,
bytes memory err
) internal override {
if (mintRequestRegistry[requestId] != address(0)) {
if (response.length > 0) {
uint256 amount = abi.decode(response, (uint256));
_mint(mintRequestRegistry[requestId], amount);
lastClaimed[mintRequestRegistry[requestId]] = block.timestamp;
emit TokensMinted(requestId, mintRequestRegistry[requestId], amount, block.timestamp);
emit ErrorOccured(requestId, mintRequestRegistry[requestId], err);
}
if (response.length > 0) {
string memory emailAddress = string(response);
userEmail[registerRequestRegistry[requestId]] = emailAddress;
emit AccountRegistered(requestId, registerRequestRegistry[requestId], emailAddress, block.timestamp);
emit ErrorOccured(requestId, registerRequestRegistry[requestId], err);
}
}
}
| 5,611,307
|
pragma solidity ^0.5.0;
import "./OracleAPI.sol";
/**
* @title Example contract using MarketData oracle
* @author TruSource
* @notice Example contract using MarketData oracle
* @dev Demonstrates usage of OracleAPI and building queryParams
*/
contract Example is OracleAPI {
event LogResult(bytes32 queryId, Oracle.Oracle.Operations operationId, uint256 statusCode, string result);
constructor(address resolverAddress) public OracleAPI(resolverAddress) {}
/**
* @notice Make getAvgPrice query
* @dev Make getAvgPrice query, queryId is returned to be used to handle query result
*/
function getAvgPrice() external {
trusource_getAvgPrice("BATBTC");
}
/**
* @notice Make getDepth query
* @dev Make getDepth query, queryId is returned to be used to handle query result
*/
function getDepth() external {
Buffer.buffer memory optionalQueryParams = createBuffer();
// Optional
addUInt(optionalQueryParams, "limit", 5);
trusource_getDepth("BATBTC", optionalQueryParams);
}
/**
* @notice Make getTicker24hr query
* @dev Make getTicker24hr query, queryId is returned to be used to handle query result
*/
function getTicker24hr() external {
Buffer.buffer memory optionalQueryParams = createBuffer();
// Optional
addString(optionalQueryParams, "symbol", "BATBTC");
trusource_getTicker24hr(optionalQueryParams);
}
/**
* @notice Make getBookTicker query
* @dev Make getBookTicker query, queryId is returned to be used to handle query result
*/
function getBookTicker() external {
Buffer.buffer memory optionalQueryParams = createBuffer();
// Optional
addString(optionalQueryParams, "symbol", "BATBTC");
trusource_getBookTicker(optionalQueryParams);
}
/**
* @notice Make getTickerPrice query
* @dev Make getTickerPrice query, queryId is returned to be used to handle query result
*/
function getTickerPrice() external {
Buffer.buffer memory optionalQueryParams = createBuffer();
// Optional
addString(optionalQueryParams, "symbol", "BATBTC");
trusource_getTickerPrice(optionalQueryParams);
}
/**
* @notice Make getTrades query
* @dev Make getTrades query, queryId is returned to be used to handle query result
*/
function getTrades() external {
Buffer.buffer memory optionalQueryParams = createBuffer();
// Optional
addUInt(optionalQueryParams, "limit", 1);
trusource_getTrades("BATBTC", optionalQueryParams);
}
/**
* @dev Handle query result using queryId, operationId and statusCode
* @param queryId unique id for query
* @param operationId id for operation
* @param statusCode HTTP response status code
* @param result query result
*/
function trusource_callback(
bytes32 queryId,
Oracle.Oracle.Operations operationId,
uint256 statusCode,
string calldata result
) external checkAddress checkQueryId(queryId) {
if (operationId == Oracle.Oracle.Operations.getAvgPrice) {
emit LogResult(queryId, operationId, statusCode, result);
return;
}
if (operationId == Oracle.Oracle.Operations.getDepth) {
emit LogResult(queryId, operationId, statusCode, result);
return;
}
if (operationId == Oracle.Oracle.Operations.getTicker24hr) {
emit LogResult(queryId, operationId, statusCode, result);
return;
}
if (operationId == Oracle.Oracle.Operations.getBookTicker) {
emit LogResult(queryId, operationId, statusCode, result);
return;
}
if (operationId == Oracle.Oracle.Operations.getTickerPrice) {
emit LogResult(queryId, operationId, statusCode, result);
return;
}
if (operationId == Oracle.Oracle.Operations.getTrades) {
emit LogResult(queryId, operationId, statusCode, result);
return;
}
}
}
|
Make getTicker24hr query Make getTicker24hr query, queryId is returned to be used to handle query result/ Optional
|
function getTicker24hr() external {
Buffer.buffer memory optionalQueryParams = createBuffer();
addString(optionalQueryParams, "symbol", "BATBTC");
trusource_getTicker24hr(optionalQueryParams);
}
| 12,644,133
|
./partial_match/1/0x56DA00ce3188F17fff7C482BE7C529d5BE2B5534/sources/XBANK.sol
|
launch buy fees launch sell fees
|
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
function _afterTokenTransfer(
address from,
address to,
uint256 amount
}
constructor() ERC20("XBANK", "XBANK") {
uint256 totalSupply = 1_000_000_000 * 1e18;
maxTransaction = (totalSupply * 25) / 1000;
maxWallet = (totalSupply * 25) / 1000;
swapTokensAtAmount = (totalSupply * 7) / 10000;
uint256 _buyMarketingFee = 0;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevelopmentFee = 0;
uint256 _buyOperationsFee = 0;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevelopmentFee = _buyDevelopmentFee;
buyOperationsFee = _buyOperationsFee;
buyTotalFees =
buyMarketingFee +
buyLiquidityFee +
buyDevelopmentFee +
buyOperationsFee;
uint256 _sellMarketingFee = 0;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevelopmentFee = 0;
uint256 _sellOperationsFee = 0;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevelopmentFee = _sellDevelopmentFee;
sellOperationsFee = _sellOperationsFee;
sellTotalFees =
sellMarketingFee +
sellLiquidityFee +
sellDevelopmentFee +
sellOperationsFee;
marketingWallet = payable(0x45Eb99728923f41497482Fa8b55ae206E9a1041e);
excludeFromFees(owner(), true);
excludeFromFees(marketingWallet, true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(marketingWallet, true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint(msg.sender, totalSupply);
}
| 9,347,667
|
./full_match/137/0x16D66b01664bc834f5db13D01E51E1Fa7C44f03B/sources/browser/NFT721.sol
|
Tries to returns the value associated with `key`. O(1). Does not revert if `key` is not in the map. _Available since v3.4._/
|
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
| 4,781,771
|
pragma solidity >=0.4.21;
/// @title Contract that contains main application data (storage)
/// @dev Kyama-Project
// OpenZeppelin's SafeMath library
import "../../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract Base {
using SafeMath for uint256;
// Total capital within the main Kyama account
uint256 public totalCapital;
// Total M-Bills issued by Kyama
uint256 public totalMIssued;
// Total Kyama M-Bill share capital
uint256 public totalMShareCapital;
// Struct defining an m-Debenture. [Request for m-Bills based on your current stake (share cap)]
struct mDebenture {
uint256 requestDate;
uint256 mValRequested;
uint256 mValExpected;
uint256 mValRepaid;
uint256 shareCap;
}
// Array of all m-Debentures made on Kyama
mDebenture[] public mDebentures;
// Length of mDebenture array
uint256 public mDebentureCount;
// Individual account mTx (M-Bill transaction) data struct
struct mTx {
uint256 valIn; // Value being deposited
uint256 valOut; // Value being withdrawn
address coParty; // Other party in the transaction (address(0) if no coParty)
uint256 shareCap; // If applicable ... a record of share capital as a result of transaction
}
// Array of all m-MetaData(s) present in Kyama
mTx[] public mMetaData;
// Struct defining an individual account
struct account {
address owner;
uint256 totalDeposit;
uint256 totalTransfer;
uint256 investmentDate;
uint256 initInvestment;
int256 m_running_value;
uint256 totalDebenture;
uint256 totalWithdrawal;
uint256 m_debentureCount;
uint256[] mMetaDataIndexes;
uint256[] mDebentureIndexes;
/**
* *highestMInterest is not an accurate indicator of the highest interest rate earned by an account
* Therefore, it should only be used as an indicator metric but not as a source of truth
*/
uint256 highestMInterest;
}
// Array of all accounts registered on Kyama
account[] public accounts;
// Length of the accounts array
uint256 public accountsCount;
// Mapping of registered accounts
mapping (address => uint256) public registeredAccounts;
// Mapping of addresses to their respective accounts
// An address can only have 1 account!
mapping (address => uint256) public accountIndexes;
// Current M-Bill price per share
uint256 public currentMPPS;
// Current M-ppS increase index
uint256 public currentMIndex;
// Multiplier that determines average rate of increase of M-Bill ppS.
// The 0-index refers to the numerator of the multiplier
// The 1-index refers to the denominator of the multiplier
uint256[] public ppsMultiplier;
// Interest allocation multiplier that determines interest allocated to M-Bills and the Kyama Project
// The 0-index corresponds to interest on M-Bills
// The 1-index corresponds to profit to the Kyama Project
// The 2-index corresponds to the interest division constant
uint256[] public interestAllocation;
// Withdrawal interest - interest rate
// Interest rate charged on accrued interest on withdrawal
uint256[] public withdrawalCharge;
// Debenture interest - interest rate
// Interest rate charged on accrued interest rate on debenture approval
uint256[] public debentureCharge;
// Debenture repayment interest
uint256[] public debentureRepaymentI;
// Maximum outstanding debentures
uint256 public maxMDebentures;
// Mapping of addresses that have call access to main application data
mapping (address => bool) public callAccess;
// Constructor function to set initial data values
constructor() public {
// Set initial M-Bill ppS
currentMPPS = 10;
// Initialize M-ppS increase index
currentMIndex = 0;
// Set ppS multiplier
// The multiplier is 1.1, thus an average increase of 10%, and a representation of 11/10
ppsMultiplier = [11, 10];
// Set initial mDebentureCount to 0
mDebentureCount = 0;
// Set initial accountsCount to 0
accountsCount = 0;
// Set interest allocation multiplier
// M-Bills interest allocation = 950/1000 = 95%
// Kyama Project profit = 50/1000 = 5%
interestAllocation = [950, 50, 1000];
// Set withdrawal charge
// = 80/100 = 80% as interest is 20% on accrued interest
withdrawalCharge = [80, 100];
// Set debenture charge
// = 90/100 = 90% as interest rate is 10% on accrued interest
debentureCharge = [90, 100];
// Set debenture repayment interest
// Interest of 10% represented as 110/100 ... growth of 1.1
debentureRepaymentI = [110, 100];
// Set maximum outstanding debentures
maxMDebentures = 10;
// Add deploying address to call access mapping
callAccess[msg.sender] = true;
}
// Modifier to ensure that address is approved to call into application storage
modifier isApproved() {
require(callAccess[msg.sender] == true, "Storage access denied.");
_;
}
// Function to approve address for call access
function approveAddress(address _toApproveAddress) external isApproved {
callAccess[_toApproveAddress] = true;
}
// Function to revoke address from call access
function revokeAddress(address _toRevokeAddress) external isApproved {
callAccess[_toRevokeAddress] = false;
}
// Function to create a new user account
function createAccount(address _toCreateAddress, uint256 _investmentAmount) external isApproved {
// Create new account struct
account memory newAccount;
newAccount.owner = _toCreateAddress;
newAccount.investmentDate = block.timestamp;
newAccount.initInvestment = _investmentAmount;
newAccount.m_running_value = 0;
newAccount.totalDebenture = 0;
newAccount.totalWithdrawal = 0;
newAccount.totalTransfer = 0;
newAccount.totalDeposit = 0;
newAccount.m_debentureCount = 0;
newAccount.highestMInterest = 0;
// Add new account to accounts directory
accounts.push(newAccount);
uint256 newAccountPosition = accounts.length.sub(1);
// Update the accounts count
accountsCount = accounts.length;
// Formally register the account
registeredAccounts[_toCreateAddress] = 1;
// Record the account index
accountIndexes[_toCreateAddress] = newAccountPosition;
}
// Function to retrieve registration status of an address
function isUserRegistered(address _toCheckAddress) public view returns (bool) {
require(_toCheckAddress != address(0), "The address provided for registration check must be valid.");
bool isRegistered = false;
uint256 registrationStatus = registeredAccounts[_toCheckAddress];
if(registrationStatus == 1) {
isRegistered = true;
}
return isRegistered;
}
// Function to get account investment date
function getInvestmentDate(address _toCheckAddress) external isApproved view returns (uint256) {
// Get account investment date
uint256 investmentDate = accounts[accountIndexes[_toCheckAddress]].investmentDate;
return investmentDate;
}
// Function to retrieve account initial investment
function getInitialInvestment(address _toCheckAddress) external isApproved view returns (uint256) {
// Get account initial investment
uint256 initInvestment = accounts[accountIndexes[_toCheckAddress]].initInvestment;
return initInvestment;
}
// Function to increment the total capital
function incrementTotalCapital(uint256 _incrementAmount) external isApproved {
totalCapital = totalCapital.add(_incrementAmount);
}
// Function to decrement the total capital
function decrementTotalCapital(uint256 _decrementAmount) external isApproved {
totalCapital = totalCapital.sub(_decrementAmount);
}
// Function to increment total M-Bills issued
function incrementTotalMIssued(uint256 _incrementAmount) external isApproved {
totalMIssued = totalMIssued.add(_incrementAmount);
}
// Function to decrement total M-Bills issued
function decrementTotalMIssued(uint256 _decrementAmount) external isApproved {
totalMIssued = totalMIssued.sub(_decrementAmount);
}
// Function to increment total M-Bill share capital
function incrementMShareCap(uint256 _incrementAmount) external isApproved {
totalMShareCapital = totalMShareCapital.add(_incrementAmount);
}
// Function to decrement total M-Bill share capital
function decrementMShareCap(uint256 _decrementAmount) external isApproved {
totalMShareCapital = totalMShareCapital.sub(_decrementAmount);
}
// Update M-Bill ppS in relation to multiplier
function updateMPPs() external isApproved {
if(currentMPPS <= currentMIndex) {
currentMPPS = (currentMPPS.mul(ppsMultiplier[0])).div(ppsMultiplier[1]);
currentMIndex = 0;
} else {
currentMIndex = currentMIndex.add(1);
}
}
// Function to check if account has met investment consensus
function isAccountHarmonized(address _accountAddress, uint256 _accShareCap) external view isApproved returns (bool) {
uint256 accInitInvestment = accounts[accountIndexes[_accountAddress]].initInvestment;
uint256 maxDebenture = getTotalDebenture(_accShareCap);
uint256 totalDebenture = accounts[accountIndexes[_accountAddress]].totalDebenture;
uint256 totalWithdrawal = accounts[accountIndexes[_accountAddress]].totalWithdrawal;
uint256 totalTransfer = accounts[accountIndexes[_accountAddress]].totalTransfer;
// Check for consensus
bool isHarmonized = false;
if(accInitInvestment < maxDebenture.add(totalDebenture).add(totalWithdrawal).add(totalTransfer)) {
isHarmonized = true;
}
return isHarmonized;
}
// Function to record an M-Bill transaction to mMetaData
function recordMData(address _accountAddress, uint256 _valIn, uint256 _valOut, address _coParty, uint256 _shareCap) external isApproved {
require(isUserRegistered(_accountAddress) == true, "Address provided is not linked to a Kyama account.");
require(_valIn >= 0, "Invalid deposit amount.");
require(_valOut >= 0, "Invalid withdrawal amount.");
require(_shareCap >= 0, "Invalid share capital amount");
require(_coParty != _accountAddress, "Co-Party address provided is invalid.");
// Create a new M-Bill transaction record
mTx memory newMTx = mTx({
valIn: _valIn,
valOut: _valOut,
coParty: _coParty,
shareCap: _shareCap
});
mMetaData.push(newMTx);
uint256 newMTxPosition = mMetaData.length.sub(1);
// Update account counters
if(_valIn > 0) {
require(accounts[accountIndexes[_accountAddress]].m_running_value + int256(_valIn) >
accounts[accountIndexes[_accountAddress]].m_running_value, "Running value _valIn error");
accounts[accountIndexes[_accountAddress]].m_running_value += int256(_valIn);
accounts[accountIndexes[_accountAddress]].totalDeposit = accounts[accountIndexes[_accountAddress]].totalDeposit.add(_valIn);
}
if(_valOut > 0) {
require(accounts[accountIndexes[_accountAddress]].m_running_value - int256(_valOut) <
accounts[accountIndexes[_accountAddress]].m_running_value, "Running value _valOut error");
accounts[accountIndexes[_accountAddress]].m_running_value -= int256(_valOut);
if(_coParty == address(0)) {
accounts[accountIndexes[_accountAddress]].totalWithdrawal = accounts[accountIndexes[_accountAddress]].totalWithdrawal.add(_valOut);
} else {
accounts[accountIndexes[_accountAddress]].totalTransfer = accounts[accountIndexes[_accountAddress]].totalTransfer.add(_valOut);
}
}
// Record transaction position to account
accounts[accountIndexes[_accountAddress]].mMetaDataIndexes.push(newMTxPosition);
}
// Function to get account total MBill interest value
function getMInterest(uint256 _accShareCap) internal isApproved view returns(uint256) {
// Get total interest on the main Kyama account
uint256 totalInterest = totalCapital.sub(totalMIssued);
// Get total interest value on account M-Bills
uint256 totalMInterestVal = (_accShareCap.mul(interestAllocation[0]).mul(totalInterest))
.div((totalMShareCapital.mul(interestAllocation[2])));
return totalMInterestVal;
}
// Function to get total Kyama revenue
function revenue() public view returns(uint256) {
// Get total interest on the main Kyama account
uint256 totalInterest = totalCapital.sub(totalMIssued);
// Get total revenue
uint256 totalRevenue = (totalInterest.mul(interestAllocation[1]))
.div(interestAllocation[2]);
return totalRevenue;
}
// Function to get account total MBill raw value
function getMRawVal(uint256 _accShareCap) internal isApproved view returns(uint256) {
// Get total raw M-Bill value on account
uint256 MRawVal = (_accShareCap.mul(totalMIssued)).div(totalMShareCapital);
return MRawVal;
}
// Function to get account total M-Bill value
function getTotalMVal(uint256 _accShareCap) public isApproved view returns(uint256) {
// Get total raw M-Bill value on account
uint256 totalMVal = getMRawVal(_accShareCap);
// Get total interest value on account M-Bills
uint256 totalMInterestVal = getMInterest(_accShareCap);
// Total account value
uint256 totalAccVal = totalMVal.add(totalMInterestVal);
return totalAccVal;
}
// Function to get total M-Bill withdrawable value from acount
function getTotalMWithdrawable(uint256 _accShareCap) public view isApproved returns(uint256) {
// Get total raw M-Bill value on account
uint256 totalMVal = getMRawVal(_accShareCap);
// Get total interest value on account M-Bills
uint256 totalMInterestVal = getMInterest(_accShareCap);
// Get account withdrawable interest
uint256 withdrawableInterest = ((totalMInterestVal).mul(withdrawalCharge[0])).div(withdrawalCharge[1]);
// Get account maximum withdrawable amount
uint256 maxWithdrawableAmount = (totalMVal).add(withdrawableInterest);
return maxWithdrawableAmount;
}
// Function to get debit costs(withdrawal and debenture approval cost)
function getDebitCost(uint256 _accShareCap, uint256 _debitAmount, bool _isWithdrawal) external view isApproved returns(uint256) {
uint256 totalMInterestVal = getMInterest(_accShareCap);
uint256 totalDebitable = uint256(0);
uint256 debitableInterest = uint256(0);
if(_isWithdrawal == true) {
totalDebitable = getTotalMWithdrawable(_accShareCap);
debitableInterest = ((totalMInterestVal).mul(withdrawalCharge[0])).div(withdrawalCharge[1]);
} else {
totalDebitable = getTotalDebenture(_accShareCap);
debitableInterest = ((totalMInterestVal).mul(debentureCharge[0])).div(debentureCharge[1]);
}
if(totalDebitable == uint256(0)) {
return uint256(0);
}
// Get ratio of debit amount to total debitable value
uint256 percDebitable = (_debitAmount.mul(100)).div(totalDebitable);
if(percDebitable == uint256(0)) {
percDebitable = 1;
}
// Get ratio of (100% - debit-charge%) of total account interest to debit amount
uint256 remDebitableInterest = totalMInterestVal.sub(debitableInterest);
// Get debit cost
uint256 debitCost = (percDebitable.mul(remDebitableInterest)).div(100);
return debitCost;
}
// Function to get an account's maximum M-Bill debenture request amount
function getTotalDebenture(uint256 _accShareCap) public view isApproved returns(uint256) {
// Get total raw M-Bill value on account
uint256 totalMVal = getMRawVal(_accShareCap);
// Get total interest value on account M-Bills
uint256 totalMInterestVal = getMInterest(_accShareCap);
// Get account debenture interest
uint256 debentureInterest = ((totalMInterestVal).mul(debentureCharge[0])).div(debentureCharge[1]);
// Get account maximum debenture amount
uint256 maxDebentureAmount = (totalMVal).add(debentureInterest);
return maxDebentureAmount;
}
// Function to record M-Bill debenture tx
function recordMDebenture(address _accountAddress, uint256 _valRequested, uint256 _shareCap) external isApproved {
// Get the value expected
uint256 valExpected = (_valRequested.mul(debentureRepaymentI[0])).div(debentureRepaymentI[1]);
// Create a new M-Bill debenture tx
mDebenture memory newMDebenture;
newMDebenture.requestDate = block.timestamp;
newMDebenture.mValRequested = _valRequested;
newMDebenture.mValExpected = valExpected;
newMDebenture.mValRepaid = uint256(0);
newMDebenture.shareCap = _shareCap;
// Record tx
mDebentures.push(newMDebenture);
uint256 newTxPosition = mDebentures.length.sub(1);
// Update m_running_value
require(accounts[accountIndexes[_accountAddress]].m_running_value - int256(_valRequested) <
accounts[accountIndexes[_accountAddress]].m_running_value, "Running value _valRequested error");
accounts[accountIndexes[_accountAddress]].m_running_value -= int256(_valRequested);
// Update totalDebenture
accounts[accountIndexes[_accountAddress]].totalDebenture = accounts[accountIndexes[_accountAddress]].totalDebenture.add(_valRequested);
// Update mDebentureCount
mDebentureCount = mDebentures.length;
// Update account
accounts[accountIndexes[_accountAddress]].mDebentureIndexes.push(newTxPosition);
accounts[accountIndexes[_accountAddress]].m_debentureCount = accounts[accountIndexes[_accountAddress]].m_debentureCount.add(1);
}
// Functon to get the current number of M-Bill debentures outstanding in an account
function outstandingMDebentures(address _accountAddress) public isApproved view returns(uint256) {
uint256 outstandingDebentures = accounts[accountIndexes[_accountAddress]].m_debentureCount;
if(outstandingDebentures > 30) {
return uint256(0);
} else {
return outstandingDebentures;
}
}
// Function to get the total number of debentures in an account (both outstanding and resolved)
function totalDebentures(address _accountAddress) external isApproved view returns(uint256) {
return accounts[accountIndexes[_accountAddress]].mDebentureIndexes.length;
}
// Function to get a particular debenture
function retrieveDebenture(address _accountAddress, uint256 _debentureIndex) external isApproved view
returns(uint256, uint256, uint256, uint256, uint256) {
// Get debenture
mDebenture memory xDebenture = mDebentures[accounts[accountIndexes[_accountAddress]].mDebentureIndexes[_debentureIndex]];
uint256 mRequestDate = xDebenture.requestDate;
uint256 mRequested = xDebenture.mValRequested;
uint256 mExpected = xDebenture.mValExpected;
uint256 mRepaid = xDebenture.mValRepaid;
uint256 mShareCap = xDebenture.shareCap;
return (mRequestDate, mRequested, mExpected, mRepaid, mShareCap);
}
// Function to get total number of mData transactions in an account
function totalMBillTxs(address _accountAddress) external isApproved view returns(uint256) {
return accounts[accountIndexes[_accountAddress]].mMetaDataIndexes.length;
}
// Function to get a particular MBill transaction
function retrieveMTx(address _accountAddress, uint256 _TxIndex) external isApproved view
returns(uint256, uint256, address, uint256) {
// Get Tx
mTx memory xMTx = mMetaData[accounts[accountIndexes[_accountAddress]].mMetaDataIndexes[_TxIndex]];
uint256 valIn = xMTx.valIn;
uint256 valOut = xMTx.valOut;
address coParty = xMTx.coParty;
uint256 shareCap = xMTx.shareCap;
return (valIn, valOut, coParty, shareCap);
}
// Function to get immediate payable debenture
function getImmediateDebenture(address _accountAddress) internal isApproved view returns(int256) {
// Find M-Bill debenture next in line to be cleared
uint256 pendingMDebentures = outstandingMDebentures(_accountAddress);
// Find total M-Bill debentures
uint256 totalMDebentures = accounts[accountIndexes[_accountAddress]].mDebentureIndexes.length;
if(pendingMDebentures == 0 || totalMDebentures == 0) {
return int256(-1);
} else {
uint256 MDebentureIndex = accounts[accountIndexes[_accountAddress]].mDebentureIndexes[totalMDebentures.sub(pendingMDebentures)];
return int256(MDebentureIndex);
}
}
// Get an account's immediate payable debenture balance
// This is the outstanding amount on the longest outstanding loan balance
function immediatePayableM(address _accountAddress) external isApproved view returns(uint256) {
// Find M-Bill debenture next in line to be cleared
int256 MDebentureIndex = getImmediateDebenture(_accountAddress);
if(MDebentureIndex == int256(-1)) {
return uint256(0);
} else {
mDebenture memory immediateMDebenture = mDebentures[uint256(MDebentureIndex)];
// Get value expected to be repaid to clear M-Bill debenture
uint256 mValExpected = immediateMDebenture.mValExpected;
uint256 mValRepaid = immediateMDebenture.mValRepaid;
uint256 debentureBalance = mValExpected.sub(mValRepaid);
return debentureBalance;
}
}
// Get an account's immediate payable share capital from M-Bill debenture
function immediateMShareCap(address _accountAddress) external isApproved view returns(uint256) {
// Find M-Bill debenture next in line to be cleared
int256 MDebentureIndex = getImmediateDebenture(_accountAddress);
if(MDebentureIndex == int256(-1)) {
return uint256(0);
} else {
mDebenture memory immediateMDebenture = mDebentures[uint256(MDebentureIndex)];
// Get share capital
uint256 mShareCap = immediateMDebenture.shareCap;
return mShareCap;
}
}
// Pay off portion or entire outstanding balance of immediate M-Bill debenture
function payImmediatePayableM(address _accountAddress, uint256 _payableValue) external isApproved {
// Find M-Bill debenture next in line to be cleared
int256 MDebentureIndex = getImmediateDebenture(_accountAddress);
if(MDebentureIndex != int256(-1)) {
mDebenture storage immediateMDebenture = mDebentures[uint256(MDebentureIndex)];
// Update debenture value repayed
uint256 mValRepaid = immediateMDebenture.mValRepaid;
immediateMDebenture.mValRepaid = mValRepaid.add(_payableValue);
// Update outstanding debenture count if necessary
uint256 updatedMValRepaid = immediateMDebenture.mValRepaid;
uint256 mValExpected = immediateMDebenture.mValExpected;
if(updatedMValRepaid >= mValExpected) {
accounts[accountIndexes[_accountAddress]].m_debentureCount = accounts[accountIndexes[_accountAddress]].m_debentureCount.sub(1);
}
// Update m_running_value
require(accounts[accountIndexes[_accountAddress]].m_running_value + int256(_payableValue) >
accounts[accountIndexes[_accountAddress]].m_running_value, "Running value _payableValue error");
accounts[accountIndexes[_accountAddress]].m_running_value += int256(_payableValue);
}
}
// Get account total interest value
function accountTotalInterest(address _accountAddress, uint256 _accShareCap) public isApproved returns(uint256) {
// Get account running value
int256 accRunningVal = accounts[accountIndexes[_accountAddress]].m_running_value;
uint256 currentAccountInterest = 0;
if(accRunningVal > int256(0)) {
uint256 runningVal = uint256(accRunningVal);
uint256 totalMVal = getTotalMVal(_accShareCap);
if(totalMVal > runningVal) {
currentAccountInterest = totalMVal.sub(runningVal);
}
}
uint256 accHighestInterest = accounts[accountIndexes[_accountAddress]].highestMInterest;
if(accHighestInterest >= currentAccountInterest) {
return accHighestInterest;
} else {
accounts[accountIndexes[_accountAddress]].highestMInterest = currentAccountInterest;
return currentAccountInterest;
}
}
// Get account total debenture
function accountTotalDebenture(address _accountAddress) external view isApproved returns(uint256) {
uint256 totalDebenture = accounts[accountIndexes[_accountAddress]].totalDebenture;
if(totalDebenture > 0) {
return totalDebenture;
} else {
return uint256(0);
}
}
// Get account total withdrawal
function accountTotalWithdrawal(address _accountAddress) external view isApproved returns(uint256) {
uint256 totalWithdrawal = accounts[accountIndexes[_accountAddress]].totalWithdrawal;
if(totalWithdrawal > 0) {
return totalWithdrawal;
} else {
return uint256(0);
}
}
// Get account total transfer
function accountTotalTransfer(address _accountAddress) external view isApproved returns(uint256) {
uint256 totalTransfer = accounts[accountIndexes[_accountAddress]].totalTransfer;
if(totalTransfer > 0) {
return totalTransfer;
} else {
return uint256(0);
}
}
// Get account total deposit
function accountTotalDeposit(address _accountAddress) external view isApproved returns(uint256) {
uint256 totalDeposit = accounts[accountIndexes[_accountAddress]].totalDeposit - accounts[accountIndexes[_accountAddress]].initInvestment;
if(totalDeposit > 0) {
return totalDeposit;
} else {
return uint256(0);
}
}
}
|
Function to get an account's maximum M-Bill debenture request amount Get total raw M-Bill value on account Get total interest value on account M-Bills Get account debenture interest Get account maximum debenture amount
|
function getTotalDebenture(uint256 _accShareCap) public view isApproved returns(uint256) {
uint256 totalMVal = getMRawVal(_accShareCap);
uint256 totalMInterestVal = getMInterest(_accShareCap);
uint256 debentureInterest = ((totalMInterestVal).mul(debentureCharge[0])).div(debentureCharge[1]);
uint256 maxDebentureAmount = (totalMVal).add(debentureInterest);
return maxDebentureAmount;
}
| 6,488,296
|
// SPDX-License-Identifier: UNLICENSED
// Banker Medium Risk
// __ __ __ __ _____ __ __
// | |/ .---.-.-----| |--|__| | |_.-----.-----.--| |__.-----.-----.
// | <| _ |__ --| | | | | -__| | _ | | | _ |
// |__|\__|___._|_____|__|__|__| |_______|_____|__|__|_____|__|__|__|___ |
// |_____|
// Copyright (c) 2021 BoringCrypto - All rights reserved
// Twitter: @Boring_Crypto
// Special thanks to:
// @0xKeno - for all his invaluable contributions
// @burger_crypto - for the idea of trying to let the LPs benefit from liquidations
// Version: 22-Feb-2021
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// solhint-disable avoid-low-level-calls
// solhint-disable no-inline-assembly
// solhint-disable not-rely-on-time
// solhint-disable indent
// File @boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol@v1.2.0
// License-Identifier: MIT
/// @notice A library for performing overflow-/underflow-safe math,
/// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math).
library BoringMath {
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint256 a, uint256 b) internal pure returns (uint256 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow");
}
function to128(uint256 a) internal pure returns (uint128 c) {
require(a <= uint128(-1), "BoringMath: uint128 Overflow");
c = uint128(a);
}
function to64(uint256 a) internal pure returns (uint64 c) {
require(a <= uint64(-1), "BoringMath: uint64 Overflow");
c = uint64(a);
}
function to32(uint256 a) internal pure returns (uint32 c) {
require(a <= uint32(-1), "BoringMath: uint32 Overflow");
c = uint32(a);
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint128.
library BoringMath128 {
function add(uint128 a, uint128 b) internal pure returns (uint128 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint128 a, uint128 b) internal pure returns (uint128 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
}
// File @boringcrypto/boring-solidity/contracts/BoringOwnable.sol@v1.2.0
// License-Identifier: MIT
// Audit on 5-Jan-2021 by Keno and BoringCrypto
// Source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol + Claimable.sol
// Edited by BoringCrypto
contract BoringOwnableData {
address public owner;
address public pendingOwner;
}
contract BoringOwnable is BoringOwnableData {
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/// @notice `owner` defaults to msg.sender on construction.
constructor() public {
owner = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
}
/// @notice Transfers ownership to `newOwner`. Either directly or claimable by the new pending owner.
/// Can only be invoked by the current `owner`.
/// @param newOwner Address of the new owner.
/// @param direct True if `newOwner` should be set immediately. False if `newOwner` needs to use `claimOwnership`.
/// @param renounce Allows the `newOwner` to be `address(0)` if `direct` and `renounce` is True. Has no effect otherwise.
function transferOwnership(
address newOwner,
bool direct,
bool renounce
) public onlyOwner {
if (direct) {
// Checks
require(
newOwner != address(0) || renounce,
"Ownable: zero address"
);
// Effects
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
pendingOwner = address(0);
} else {
// Effects
pendingOwner = newOwner;
}
}
/// @notice Needs to be called by `pendingOwner` to claim ownership.
function claimOwnership() public {
address _pendingOwner = pendingOwner;
// Checks
require(
msg.sender == _pendingOwner,
"Ownable: caller != pending owner"
);
// Effects
emit OwnershipTransferred(owner, _pendingOwner);
owner = _pendingOwner;
pendingOwner = address(0);
}
/// @notice Only allows the `owner` to execute the function.
modifier onlyOwner() {
require(msg.sender == owner, "Ownable: caller is not the owner");
_;
}
}
// File @boringcrypto/boring-solidity/contracts/Domain.sol@v1.2.0
// License-Identifier: MIT
// Based on code and smartness by Ross Campbell and Keno
// Uses immutable to pantry the domain separator to reduce gas usage
// If the chain id changes due to a fork, the forked chain will calculate on the fly.
contract Domain {
bytes32 private constant DOMAIN_SEPARATOR_SIGNATURE_HASH =
keccak256("EIP712Domain(uint256 chainId,address verifyingContract)");
// See https://eips.ethereum.org/EIPS/eip-191
string private constant EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA =
"\x19\x01";
// solhint-disable var-name-mixedcase
bytes32 private immutable _DOMAIN_SEPARATOR;
uint256 private immutable DOMAIN_SEPARATOR_CHAIN_ID;
/// @dev Calculate the DOMAIN_SEPARATOR
function _calculateDomainSeparator(uint256 chainId)
private
view
returns (bytes32)
{
return
keccak256(
abi.encode(
DOMAIN_SEPARATOR_SIGNATURE_HASH,
chainId,
address(this)
)
);
}
constructor() public {
uint256 chainId;
assembly {
chainId := chainid()
}
_DOMAIN_SEPARATOR = _calculateDomainSeparator(
DOMAIN_SEPARATOR_CHAIN_ID = chainId
);
}
/// @dev Return the DOMAIN_SEPARATOR
// It's named internal to allow making it public from the contract that uses it by creating a simple view function
// with the desired public name, such as DOMAIN_SEPARATOR or domainSeparator.
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() public view returns (bytes32) {
uint256 chainId;
assembly {
chainId := chainid()
}
return
chainId == DOMAIN_SEPARATOR_CHAIN_ID
? _DOMAIN_SEPARATOR
: _calculateDomainSeparator(chainId);
}
function _getDigest(bytes32 dataHash)
internal
view
returns (bytes32 digest)
{
digest = keccak256(
abi.encodePacked(
EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA,
DOMAIN_SEPARATOR(),
dataHash
)
);
}
}
// File @boringcrypto/boring-solidity/contracts/ERC20.sol@v1.2.0
// License-Identifier: MIT
// solhint-disable no-inline-assembly
// solhint-disable not-rely-on-time
// Data part taken out for building of contracts that receive delegate calls
contract ERC20Data {
/// @notice owner > balance mapping.
mapping(address => uint256) public balanceOf;
/// @notice owner > spender > allowance mapping.
mapping(address => mapping(address => uint256)) public allowance;
/// @notice owner > nonce mapping. Used in `permit`.
mapping(address => uint256) public nonces;
}
contract ERC20 is ERC20Data, Domain {
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _value
);
/// @notice Transfers `amount` tokens from `msg.sender` to `to`.
/// @param to The address to move the tokens.
/// @param amount of the tokens to move.
/// @return (bool) Returns True if succeeded.
function transfer(address to, uint256 amount) public returns (bool) {
// If `amount` is 0, or `msg.sender` is `to` nothing happens
if (amount != 0) {
uint256 srcBalance = balanceOf[msg.sender];
require(srcBalance >= amount, "ERC20: balance too low");
if (msg.sender != to) {
require(to != address(0), "ERC20: no zero address"); // Moved down so low balance calls safe some gas
balanceOf[msg.sender] = srcBalance - amount; // Underflow is checked
balanceOf[to] += amount; // Can't overflow because totalSupply would be greater than 2^256-1
}
}
emit Transfer(msg.sender, to, amount);
return true;
}
/// @notice Transfers `amount` tokens from `from` to `to`. Caller needs approval for `from`.
/// @param from Address to draw tokens from.
/// @param to The address to move the tokens.
/// @param amount The token amount to move.
/// @return (bool) Returns True if succeeded.
function transferFrom(
address from,
address to,
uint256 amount
) public returns (bool) {
// If `amount` is 0, or `from` is `to` nothing happens
if (amount != 0) {
uint256 srcBalance = balanceOf[from];
require(srcBalance >= amount, "ERC20: balance too low");
if (from != to) {
uint256 spenderAllowance = allowance[from][msg.sender];
// If allowance is infinite, don't decrease it to save on gas (breaks with EIP-20).
if (spenderAllowance != type(uint256).max) {
require(
spenderAllowance >= amount,
"ERC20: allowance too low"
);
allowance[from][msg.sender] = spenderAllowance - amount; // Underflow is checked
}
require(to != address(0), "ERC20: no zero address"); // Moved down so other failed calls safe some gas
balanceOf[from] = srcBalance - amount; // Underflow is checked
balanceOf[to] += amount; // Can't overflow because totalSupply would be greater than 2^256-1
}
}
emit Transfer(from, to, amount);
return true;
}
/// @notice Approves `amount` from sender to be spend by `spender`.
/// @param spender Address of the party that can draw from msg.sender's account.
/// @param amount The maximum collective amount that `spender` can draw.
/// @return (bool) Returns True if approved.
function approve(address spender, uint256 amount) public returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 private constant PERMIT_SIGNATURE_HASH =
0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
/// @notice Approves `value` from `owner_` to be spend by `spender`.
/// @param owner_ Address of the owner.
/// @param spender The address of the spender that gets approved to draw from `owner_`.
/// @param value The maximum collective amount that `spender` can draw.
/// @param deadline This permit must be redeemed before this deadline (UTC timestamp in seconds).
function permit(
address owner_,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external {
require(owner_ != address(0), "ERC20: Owner cannot be 0");
require(block.timestamp < deadline, "ERC20: Expired");
require(
ecrecover(
_getDigest(
keccak256(
abi.encode(
PERMIT_SIGNATURE_HASH,
owner_,
spender,
value,
nonces[owner_]++,
deadline
)
)
),
v,
r,
s
) == owner_,
"ERC20: Invalid Signature"
);
allowance[owner_][spender] = value;
emit Approval(owner_, spender, value);
}
}
// File @boringcrypto/boring-solidity/contracts/interfaces/IMasterContract.sol@v1.2.0
// License-Identifier: MIT
interface IMasterContract {
/// @notice Init function that gets called from `BoringFactory.deploy`.
/// Also kown as the constructor for cloned contracts.
/// Any ETH send to `BoringFactory.deploy` ends up here.
/// @param data Can be abi encoded arguments or anything else.
function init(bytes calldata data) external payable;
}
// File @boringcrypto/boring-solidity/contracts/libraries/BoringRebase.sol@v1.2.0
// License-Identifier: MIT
struct Rebase {
uint128 elastic;
uint128 base;
}
/// @notice A rebasing library using overflow-/underflow-safe math.
library RebaseLibrary {
using BoringMath for uint256;
using BoringMath128 for uint128;
/// @notice Calculates the base value in relationship to `elastic` and `total`.
function toBase(
Rebase memory total,
uint256 elastic,
bool roundUp
) internal pure returns (uint256 base) {
if (total.elastic == 0) {
base = elastic;
} else {
base = elastic.mul(total.base) / total.elastic;
if (roundUp && base.mul(total.elastic) / total.base < elastic) {
base = base.add(1);
}
}
}
/// @notice Calculates the elastic value in relationship to `base` and `total`.
function toElastic(
Rebase memory total,
uint256 base,
bool roundUp
) internal pure returns (uint256 elastic) {
if (total.base == 0) {
elastic = base;
} else {
elastic = base.mul(total.elastic) / total.base;
if (roundUp && elastic.mul(total.base) / total.elastic < base) {
elastic = elastic.add(1);
}
}
}
/// @notice Add `elastic` to `total` and doubles `total.base`.
/// @return (Rebase) The new total.
/// @return base in relationship to `elastic`.
function add(
Rebase memory total,
uint256 elastic,
bool roundUp
) internal pure returns (Rebase memory, uint256 base) {
base = toBase(total, elastic, roundUp);
total.elastic = total.elastic.add(elastic.to128());
total.base = total.base.add(base.to128());
return (total, base);
}
/// @notice Sub `base` from `total` and update `total.elastic`.
/// @return (Rebase) The new total.
/// @return elastic in relationship to `base`.
function sub(
Rebase memory total,
uint256 base,
bool roundUp
) internal pure returns (Rebase memory, uint256 elastic) {
elastic = toElastic(total, base, roundUp);
total.elastic = total.elastic.sub(elastic.to128());
total.base = total.base.sub(base.to128());
return (total, elastic);
}
/// @notice Add `elastic` and `base` to `total`.
function add(
Rebase memory total,
uint256 elastic,
uint256 base
) internal pure returns (Rebase memory) {
total.elastic = total.elastic.add(elastic.to128());
total.base = total.base.add(base.to128());
return total;
}
/// @notice Subtract `elastic` and `base` to `total`.
function sub(
Rebase memory total,
uint256 elastic,
uint256 base
) internal pure returns (Rebase memory) {
total.elastic = total.elastic.sub(elastic.to128());
total.base = total.base.sub(base.to128());
return total;
}
}
// File @boringcrypto/boring-solidity/contracts/interfaces/IERC20.sol@v1.2.0
// License-Identifier: MIT
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
/// @notice EIP 2612
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// File @boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol@v1.2.0
// License-Identifier: MIT
library BoringERC20 {
bytes4 private constant SIG_SYMBOL = 0x95d89b41; // symbol()
bytes4 private constant SIG_NAME = 0x06fdde03; // name()
bytes4 private constant SIG_DECIMALS = 0x313ce567; // decimals()
bytes4 private constant SIG_TRANSFER = 0xa9059cbb; // transfer(address,uint256)
bytes4 private constant SIG_TRANSFER_FROM = 0x23b872dd; // transferFrom(address,address,uint256)
function returnDataToString(bytes memory data)
internal
pure
returns (string memory)
{
if (data.length >= 64) {
return abi.decode(data, (string));
} else if (data.length == 32) {
uint8 i = 0;
while (i < 32 && data[i] != 0) {
i++;
}
bytes memory bytesArray = new bytes(i);
for (i = 0; i < 32 && data[i] != 0; i++) {
bytesArray[i] = data[i];
}
return string(bytesArray);
} else {
return "???";
}
}
/// @notice Provides a safe ERC20.symbol version which returns '???' as fallback string.
/// @param token The address of the ERC-20 token contract.
/// @return (string) Token symbol.
function safeSymbol(IERC20 token) internal view returns (string memory) {
(bool success, bytes memory data) =
address(token).staticcall(abi.encodeWithSelector(SIG_SYMBOL));
return success ? returnDataToString(data) : "???";
}
/// @notice Provides a safe ERC20.name version which returns '???' as fallback string.
/// @param token The address of the ERC-20 token contract.
/// @return (string) Token name.
function safeName(IERC20 token) internal view returns (string memory) {
(bool success, bytes memory data) =
address(token).staticcall(abi.encodeWithSelector(SIG_NAME));
return success ? returnDataToString(data) : "???";
}
/// @notice Provides a safe ERC20.decimals version which returns '18' as fallback value.
/// @param token The address of the ERC-20 token contract.
/// @return (uint8) Token decimals.
function safeDecimals(IERC20 token) internal view returns (uint8) {
(bool success, bytes memory data) =
address(token).staticcall(abi.encodeWithSelector(SIG_DECIMALS));
return success && data.length == 32 ? abi.decode(data, (uint8)) : 18;
}
}
// File @sushiswap/bentobox-sdk/contracts/IBatchFlashBorrower.sol@v1.0.1
// License-Identifier: MIT
interface IBatchFlashBorrower {
function onBatchFlashLoan(
address sender,
IERC20[] calldata tokens,
uint256[] calldata amounts,
uint256[] calldata fees,
bytes calldata data
) external;
}
// File @sushiswap/bentobox-sdk/contracts/IFlashBorrower.sol@v1.0.1
// License-Identifier: MIT
interface IFlashBorrower {
function onFlashLoan(
address sender,
IERC20 token,
uint256 amount,
uint256 fee,
bytes calldata data
) external;
}
// File @sushiswap/bentobox-sdk/contracts/IStrategy.sol@v1.0.1
// License-Identifier: MIT
interface IStrategy {
// Send the assets to the Strategy and call skim to invest them
function skim(uint256 amount) external;
// Harvest any profits made converted to the asset and pass them to the caller
function harvest(uint256 balance, address sender)
external
returns (int256 amountAdded);
// Withdraw assets. The returned amount can differ from the requested amount due to rounding.
// The actualAmount should be very close to the amount. The difference should NOT be used to report a loss. That's what harvest is for.
function withdraw(uint256 amount) external returns (uint256 actualAmount);
// Withdraw all assets in the safest way possible. This shouldn't fail.
function exit(uint256 balance) external returns (int256 amountAdded);
}
// File @sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol@v1.0.1
// License-Identifier: MIT
interface IVaultV1 {
event LogDeploy(
address indexed masterContract,
bytes data,
address indexed cloneAddress
);
event LogDeposit(
address indexed token,
address indexed from,
address indexed to,
uint256 amount,
uint256 share
);
event LogFlashLoan(
address indexed borrower,
address indexed token,
uint256 amount,
uint256 feeAmount,
address indexed receiver
);
event LogRegisterProtocol(address indexed protocol);
event LogSetMasterContractApproval(
address indexed masterContract,
address indexed user,
bool approved
);
event LogStrategyDivest(address indexed token, uint256 amount);
event LogStrategyInvest(address indexed token, uint256 amount);
event LogStrategyLoss(address indexed token, uint256 amount);
event LogStrategyProfit(address indexed token, uint256 amount);
event LogStrategyQueued(address indexed token, address indexed strategy);
event LogStrategySet(address indexed token, address indexed strategy);
event LogStrategyTargetPercentage(
address indexed token,
uint256 targetPercentage
);
event LogTransfer(
address indexed token,
address indexed from,
address indexed to,
uint256 share
);
event LogWhiteListMasterContract(
address indexed masterContract,
bool approved
);
event LogWithdraw(
address indexed token,
address indexed from,
address indexed to,
uint256 amount,
uint256 share
);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
function balanceOf(IERC20, address) external view returns (uint256);
function batch(bytes[] calldata calls, bool revertOnFail)
external
payable
returns (bool[] memory successes, bytes[] memory results);
function batchFlashLoan(
IBatchFlashBorrower borrower,
address[] calldata receivers,
IERC20[] calldata tokens,
uint256[] calldata amounts,
bytes calldata data
) external;
function claimOwnership() external;
function deploy(
address masterContract,
bytes calldata data,
bool useCreate2
) external payable;
function deposit(
IERC20 token_,
address from,
address to,
uint256 amount,
uint256 share
) external payable returns (uint256 amountOut, uint256 shareOut);
function flashLoan(
IFlashBorrower borrower,
address receiver,
IERC20 token,
uint256 amount,
bytes calldata data
) external;
function harvest(
IERC20 token,
bool balance,
uint256 maxChangeAmount
) external;
function masterContractApproved(address, address)
external
view
returns (bool);
function masterContractOf(address) external view returns (address);
function nonces(address) external view returns (uint256);
function owner() external view returns (address);
function pendingOwner() external view returns (address);
function pendingStrategy(IERC20) external view returns (IStrategy);
function permitToken(
IERC20 token,
address from,
address to,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
function registerProtocol() external;
function setMasterContractApproval(
address user,
address masterContract,
bool approved,
uint8 v,
bytes32 r,
bytes32 s
) external;
function setStrategy(IERC20 token, IStrategy newStrategy) external;
function setStrategyTargetPercentage(IERC20 token, uint64 targetPercentage_)
external;
function strategy(IERC20) external view returns (IStrategy);
function strategyData(IERC20)
external
view
returns (
uint64 strategyStartDate,
uint64 targetPercentage,
uint128 balance
);
function toAmount(
IERC20 token,
uint256 share,
bool roundUp
) external view returns (uint256 amount);
function toShare(
IERC20 token,
uint256 amount,
bool roundUp
) external view returns (uint256 share);
function totals(IERC20) external view returns (Rebase memory totals_);
function transfer(
IERC20 token,
address from,
address to,
uint256 share
) external;
function transferMultiple(
IERC20 token,
address from,
address[] calldata tos,
uint256[] calldata shares
) external;
function transferOwnership(
address newOwner,
bool direct,
bool renounce
) external;
function whitelistMasterContract(address masterContract, bool approved)
external;
function whitelistedMasterContracts(address) external view returns (bool);
function withdraw(
IERC20 token_,
address from,
address to,
uint256 amount,
uint256 share
) external returns (uint256 amountOut, uint256 shareOut);
}
// File contracts/interfaces/IOracle.sol
// License-Identifier: MIT
interface IOracle {
/// @notice Get the latest exchange rate.
/// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle.
/// For example:
/// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256));
/// @return success if no valid (recent) rate is available, return false else true.
/// @return rate The rate of the requested asset / pair / pool.
function get(bytes calldata data)
external
returns (bool success, uint256 rate);
/// @notice Check the last exchange rate without any state changes.
/// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle.
/// For example:
/// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256));
/// @return success if no valid (recent) rate is available, return false else true.
/// @return rate The rate of the requested asset / pair / pool.
function peek(bytes calldata data)
external
view
returns (bool success, uint256 rate);
/// @notice Check the current spot exchange rate without any state changes. For oracles like TWAP this will be different from peek().
/// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle.
/// For example:
/// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256));
/// @return rate The rate of the requested asset / pair / pool.
function peekSpot(bytes calldata data) external view returns (uint256 rate);
/// @notice Returns a human readable (short) name about this oracle.
/// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle.
/// For example:
/// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256));
/// @return (string) A human readable symbol name about this oracle.
function symbol(bytes calldata data) external view returns (string memory);
/// @notice Returns a human readable name about this oracle.
/// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle.
/// For example:
/// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256));
/// @return (string) A human readable name about this oracle.
function name(bytes calldata data) external view returns (string memory);
}
// File contracts/interfaces/ISwapper.sol
// License-Identifier: MIT
interface ISwapper {
/// @notice Withdraws 'amountFrom' of token 'from' from the pantry account for this swapper.
/// Swaps it for at least 'amountToMin' of token 'to'.
/// Transfers the swapped tokens of 'to' into the pantry using a plain ERC20 transfer.
/// Returns the amount of tokens 'to' transferred to pantry.
/// (The pantry skim function will be used by the caller to get the swapped funds).
function swap(
IERC20 fromToken,
IERC20 toToken,
address recipient,
uint256 shareToMin,
uint256 shareFrom
) external returns (uint256 extraShare, uint256 shareReturned);
/// @notice Calculates the amount of token 'from' needed to complete the swap (amountFrom),
/// this should be less than or equal to amountFromMax.
/// Withdraws 'amountFrom' of token 'from' from the pantry account for this swapper.
/// Swaps it for exactly 'exactAmountTo' of token 'to'.
/// Transfers the swapped tokens of 'to' into the pantry using a plain ERC20 transfer.
/// Transfers allocated, but unused 'from' tokens within the pantry to 'refundTo' (amountFromMax - amountFrom).
/// Returns the amount of 'from' tokens withdrawn from pantry (amountFrom).
/// (The pantry skim function will be used by the caller to get the swapped funds).
function swapExact(
IERC20 fromToken,
IERC20 toToken,
address recipient,
address refundTo,
uint256 shareFromSupplied,
uint256 shareToExact
) external returns (uint256 shareUsed, uint256 shareReturned);
}
// File contracts/BankerPair.sol
// License-Identifier: UNLICENSED
// Banker Medium Risk
/// @title BankerPair
/// @dev This contract allows contract calls to any contract (except pantry)
/// from arbitrary callers thus, don't trust calls from this contract in any circumstances.
contract KashiPairMediumRiskV1 is ERC20, BoringOwnable, IMasterContract {
using BoringMath for uint256;
using BoringMath128 for uint128;
using RebaseLibrary for Rebase;
using BoringERC20 for IERC20;
event LogExchangeRate(uint256 rate);
event LogAccrue(
uint256 accruedAmount,
uint256 feeFraction,
uint64 rate,
uint256 utilization
);
event LogAddCollateral(
address indexed from,
address indexed to,
uint256 share
);
event LogAddAsset(
address indexed from,
address indexed to,
uint256 share,
uint256 fraction
);
event LogRemoveCollateral(
address indexed from,
address indexed to,
uint256 share
);
event LogRemoveAsset(
address indexed from,
address indexed to,
uint256 share,
uint256 fraction
);
event LogBorrow(
address indexed from,
address indexed to,
uint256 amount,
uint256 feeAmount,
uint256 part
);
event LogRepay(
address indexed from,
address indexed to,
uint256 amount,
uint256 part
);
event LogFeeTo(address indexed newFeeTo);
event LogWithdrawFees(address indexed feeTo, uint256 feesEarnedFraction);
// Immutables (for MasterContract and all clones)
IVaultV1 public immutable vault;
KashiPairMediumRiskV1 public immutable masterContract;
// MasterContract variables
address public feeTo;
mapping(ISwapper => bool) public swappers;
// Per clone variables
// Clone init settings
IERC20 public collateral;
IERC20 public asset;
IOracle public oracle;
bytes public oracleData;
// Total amounts
uint256 public totalCollateralShare; // Total collateral supplied
Rebase public totalAsset; // elastic = pantry shares held by the BankerPair, base = Total fractions held by asset suppliers
Rebase public totalBorrow; // elastic = Total token amount to be repayed by borrowers, base = Total parts of the debt held by borrowers
// User balances
mapping(address => uint256) public userCollateralShare;
// userAssetFraction is called balanceOf for ERC20 compatibility (it's in ERC20.sol)
mapping(address => uint256) public userBorrowPart;
/// @notice Exchange and interest rate tracking.
/// This is 'cached' here because calls to Oracles can be very expensive.
uint256 public exchangeRate;
struct AccrueInfo {
uint64 interestPerSecond;
uint64 lastAccrued;
uint128 feesEarnedFraction;
}
AccrueInfo public accrueInfo;
// ERC20 'variables'
function symbol() external view returns (string memory) {
return
string(
abi.encodePacked(
"km",
collateral.safeSymbol(),
"/",
asset.safeSymbol(),
"-",
oracle.symbol(oracleData)
)
);
}
function name() external view returns (string memory) {
return
string(
abi.encodePacked(
"Banker Medium Risk ",
collateral.safeName(),
"/",
asset.safeName(),
"-",
oracle.name(oracleData)
)
);
}
function decimals() external view returns (uint8) {
return asset.safeDecimals();
}
// totalSupply for ERC20 compatibility
function totalSupply() public view returns (uint256) {
return totalAsset.base;
}
// Settings for the Medium Risk BankerPair
uint256 private constant CLOSED_COLLATERIZATION_RATE = 75000; // 75%
uint256 private constant OPEN_COLLATERIZATION_RATE = 77000; // 77%
uint256 private constant COLLATERIZATION_RATE_PRECISION = 1e5; // Must be less than EXCHANGE_RATE_PRECISION (due to optimization in math)
uint256 private constant MINIMUM_TARGET_UTILIZATION = 7e17; // 70%
uint256 private constant MAXIMUM_TARGET_UTILIZATION = 8e17; // 80%
uint256 private constant UTILIZATION_PRECISION = 1e18;
uint256 private constant FULL_UTILIZATION = 1e18;
uint256 private constant FULL_UTILIZATION_MINUS_MAX =
FULL_UTILIZATION - MAXIMUM_TARGET_UTILIZATION;
uint256 private constant FACTOR_PRECISION = 1e18;
uint64 private constant STARTING_INTEREST_PER_SECOND = 317097920; // approx 1% APR
uint64 private constant MINIMUM_INTEREST_PER_SECOND = 79274480; // approx 0.25% APR
uint64 private constant MAXIMUM_INTEREST_PER_SECOND = 317097920000; // approx 1000% APR
uint256 private constant INTEREST_ELASTICITY = 28800e36; // Half or double in 28800 seconds (8 hours) if linear
uint256 private constant EXCHANGE_RATE_PRECISION = 1e18;
uint256 private constant LIQUIDATION_MULTIPLIER = 112000; // add 12%
uint256 private constant LIQUIDATION_MULTIPLIER_PRECISION = 1e5;
// Fees
uint256 private constant PROTOCOL_FEE = 10000; // 10%
uint256 private constant PROTOCOL_FEE_DIVISOR = 1e5;
uint256 private constant BORROW_OPENING_FEE = 50; // 0.05%
uint256 private constant BORROW_OPENING_FEE_PRECISION = 1e5;
/// @notice The constructor is only used for the initial master contract. Subsequent clones are initialised via `init`.
constructor(IVaultV1 vault_) public {
vault = vault_;
masterContract = this;
feeTo = msg.sender;
}
/// @notice Serves as the constructor for clones, as clones can't have a regular constructor
/// @dev `data` is abi encoded in the format: (IERC20 collateral, IERC20 asset, IOracle oracle, bytes oracleData)
function init(bytes calldata data) public payable override {
require(
address(collateral) == address(0),
"BankerPair: already initialized"
);
(collateral, asset, oracle, oracleData) = abi.decode(
data,
(IERC20, IERC20, IOracle, bytes)
);
require(address(collateral) != address(0), "BankerPair: bad pair");
accrueInfo.interestPerSecond = uint64(STARTING_INTEREST_PER_SECOND); // 1% APR, with 1e18 being 100%
}
/// @notice Accrues the interest on the borrowed tokens and handles the accumulation of fees.
function accrue() public {
AccrueInfo memory _accrueInfo = accrueInfo;
// Number of seconds since accrue was called
uint256 elapsedTime = block.timestamp - _accrueInfo.lastAccrued;
if (elapsedTime == 0) {
return;
}
_accrueInfo.lastAccrued = uint64(block.timestamp);
Rebase memory _totalBorrow = totalBorrow;
if (_totalBorrow.base == 0) {
// If there are no borrows, reset the interest rate
if (_accrueInfo.interestPerSecond != STARTING_INTEREST_PER_SECOND) {
_accrueInfo.interestPerSecond = STARTING_INTEREST_PER_SECOND;
emit LogAccrue(0, 0, STARTING_INTEREST_PER_SECOND, 0);
}
accrueInfo = _accrueInfo;
return;
}
uint256 extraAmount = 0;
uint256 feeFraction = 0;
Rebase memory _totalAsset = totalAsset;
// Accrue interest
extraAmount =
uint256(_totalBorrow.elastic)
.mul(_accrueInfo.interestPerSecond)
.mul(elapsedTime) /
1e18;
_totalBorrow.elastic = _totalBorrow.elastic.add(extraAmount.to128());
uint256 fullAssetAmount =
vault.toAmount(asset, _totalAsset.elastic, false).add(
_totalBorrow.elastic
);
uint256 feeAmount =
extraAmount.mul(PROTOCOL_FEE) / PROTOCOL_FEE_DIVISOR; // % of interest paid goes to fee
feeFraction = feeAmount.mul(_totalAsset.base) / fullAssetAmount;
_accrueInfo.feesEarnedFraction = _accrueInfo.feesEarnedFraction.add(
feeFraction.to128()
);
totalAsset.base = _totalAsset.base.add(feeFraction.to128());
totalBorrow = _totalBorrow;
// Update interest rate
uint256 utilization =
uint256(_totalBorrow.elastic).mul(UTILIZATION_PRECISION) /
fullAssetAmount;
if (utilization < MINIMUM_TARGET_UTILIZATION) {
uint256 underFactor =
MINIMUM_TARGET_UTILIZATION.sub(utilization).mul(
FACTOR_PRECISION
) / MINIMUM_TARGET_UTILIZATION;
uint256 scale =
INTEREST_ELASTICITY.add(
underFactor.mul(underFactor).mul(elapsedTime)
);
_accrueInfo.interestPerSecond = uint64(
uint256(_accrueInfo.interestPerSecond).mul(
INTEREST_ELASTICITY
) / scale
);
if (_accrueInfo.interestPerSecond < MINIMUM_INTEREST_PER_SECOND) {
_accrueInfo.interestPerSecond = MINIMUM_INTEREST_PER_SECOND; // 0.25% APR minimum
}
} else if (utilization > MAXIMUM_TARGET_UTILIZATION) {
uint256 overFactor =
utilization.sub(MAXIMUM_TARGET_UTILIZATION).mul(
FACTOR_PRECISION
) / FULL_UTILIZATION_MINUS_MAX;
uint256 scale =
INTEREST_ELASTICITY.add(
overFactor.mul(overFactor).mul(elapsedTime)
);
uint256 newInterestPerSecond =
uint256(_accrueInfo.interestPerSecond).mul(scale) /
INTEREST_ELASTICITY;
if (newInterestPerSecond > MAXIMUM_INTEREST_PER_SECOND) {
newInterestPerSecond = MAXIMUM_INTEREST_PER_SECOND; // 1000% APR maximum
}
_accrueInfo.interestPerSecond = uint64(newInterestPerSecond);
}
emit LogAccrue(
extraAmount,
feeFraction,
_accrueInfo.interestPerSecond,
utilization
);
accrueInfo = _accrueInfo;
}
/// @notice Concrete implementation of `isSolvent`. Includes a third parameter to allow caching `exchangeRate`.
/// @param _exchangeRate The exchange rate. Used to cache the `exchangeRate` between calls.
function _isSolvent(
address user,
bool open,
uint256 _exchangeRate
) internal view returns (bool) {
// accrue must have already been called!
uint256 borrowPart = userBorrowPart[user];
if (borrowPart == 0) return true;
uint256 collateralShare = userCollateralShare[user];
if (collateralShare == 0) return false;
Rebase memory _totalBorrow = totalBorrow;
return
vault.toAmount(
collateral,
collateralShare
.mul(
EXCHANGE_RATE_PRECISION / COLLATERIZATION_RATE_PRECISION
)
.mul(
open
? OPEN_COLLATERIZATION_RATE
: CLOSED_COLLATERIZATION_RATE
),
false
) >=
// Moved exchangeRate here instead of dividing the other side to preserve more precision
borrowPart.mul(_totalBorrow.elastic).mul(_exchangeRate) /
_totalBorrow.base;
}
/// @dev Checks if the user is solvent in the closed liquidation case at the end of the function body.
modifier solvent() {
_;
require(
_isSolvent(msg.sender, false, exchangeRate),
"BankerPair: user insolvent"
);
}
/// @notice Gets the exchange rate. I.e how much collateral to buy 1e18 asset.
/// This function is supposed to be invoked if needed because Oracle queries can be expensive.
/// @return updated True if `exchangeRate` was updated.
/// @return rate The new exchange rate.
function updateExchangeRate() public returns (bool updated, uint256 rate) {
(updated, rate) = oracle.get(oracleData);
if (updated) {
exchangeRate = rate;
emit LogExchangeRate(rate);
} else {
// Return the old rate if fetching wasn't successful
rate = exchangeRate;
}
}
/// @dev Helper function to move tokens.
/// @param token The ERC-20 token.
/// @param share The amount in shares to add.
/// @param total Grand total amount to deduct from this contract's balance. Only applicable if `skim` is True.
/// Only used for accounting checks.
/// @param skim If True, only does a balance check on this contract.
/// False if tokens from msg.sender in `vault` should be transferred.
function _addTokens(
IERC20 token,
uint256 share,
uint256 total,
bool skim
) internal {
if (skim) {
require(
share <= vault.balanceOf(token, address(this)).sub(total),
"BankerPair: Skim too much"
);
} else {
vault.transfer(token, msg.sender, address(this), share);
}
}
/// @notice Adds `collateral` from msg.sender to the account `to`.
/// @param to The receiver of the tokens.
/// @param skim True if the amount should be skimmed from the deposit balance of msg.sender.
/// False if tokens from msg.sender in `vault` should be transferred.
/// @param share The amount of shares to add for `to`.
function addCollateral(
address to,
bool skim,
uint256 share
) public {
userCollateralShare[to] = userCollateralShare[to].add(share);
uint256 oldTotalCollateralShare = totalCollateralShare;
totalCollateralShare = oldTotalCollateralShare.add(share);
_addTokens(collateral, share, oldTotalCollateralShare, skim);
emit LogAddCollateral(skim ? address(vault) : msg.sender, to, share);
}
/// @dev Concrete implementation of `removeCollateral`.
function _removeCollateral(address to, uint256 share) internal {
userCollateralShare[msg.sender] = userCollateralShare[msg.sender].sub(
share
);
totalCollateralShare = totalCollateralShare.sub(share);
emit LogRemoveCollateral(msg.sender, to, share);
vault.transfer(collateral, address(this), to, share);
}
/// @notice Removes `share` amount of collateral and transfers it to `to`.
/// @param to The receiver of the shares.
/// @param share Amount of shares to remove.
function removeCollateral(address to, uint256 share) public solvent {
// accrue must be called because we check solvency
accrue();
_removeCollateral(to, share);
}
/// @dev Concrete implementation of `addAsset`.
function _addAsset(
address to,
bool skim,
uint256 share
) internal returns (uint256 fraction) {
Rebase memory _totalAsset = totalAsset;
uint256 totalAssetShare = _totalAsset.elastic;
uint256 allShare =
_totalAsset.elastic +
vault.toShare(asset, totalBorrow.elastic, true);
fraction = allShare == 0
? share
: share.mul(_totalAsset.base) / allShare;
if (_totalAsset.base.add(fraction.to128()) < 1000) {
return 0;
}
totalAsset = _totalAsset.add(share, fraction);
balanceOf[to] = balanceOf[to].add(fraction);
_addTokens(asset, share, totalAssetShare, skim);
emit LogAddAsset(
skim ? address(vault) : msg.sender,
to,
share,
fraction
);
}
/// @notice Adds assets to the lending pair.
/// @param to The address of the user to receive the assets.
/// @param skim True if the amount should be skimmed from the deposit balance of msg.sender.
/// False if tokens from msg.sender in `vault` should be transferred.
/// @param share The amount of shares to add.
/// @return fraction Total fractions added.
function addAsset(
address to,
bool skim,
uint256 share
) public returns (uint256 fraction) {
accrue();
fraction = _addAsset(to, skim, share);
}
/// @dev Concrete implementation of `removeAsset`.
function _removeAsset(address to, uint256 fraction)
internal
returns (uint256 share)
{
Rebase memory _totalAsset = totalAsset;
uint256 allShare =
_totalAsset.elastic +
vault.toShare(asset, totalBorrow.elastic, true);
share = fraction.mul(allShare) / _totalAsset.base;
balanceOf[msg.sender] = balanceOf[msg.sender].sub(fraction);
_totalAsset.elastic = _totalAsset.elastic.sub(share.to128());
_totalAsset.base = _totalAsset.base.sub(fraction.to128());
require(_totalAsset.base >= 1000, "Banker: below minimum");
totalAsset = _totalAsset;
emit LogRemoveAsset(msg.sender, to, share, fraction);
vault.transfer(asset, address(this), to, share);
}
/// @notice Removes an asset from msg.sender and transfers it to `to`.
/// @param to The user that receives the removed assets.
/// @param fraction The amount/fraction of assets held to remove.
/// @return share The amount of shares transferred to `to`.
function removeAsset(address to, uint256 fraction)
public
returns (uint256 share)
{
accrue();
share = _removeAsset(to, fraction);
}
/// @dev Concrete implementation of `borrow`.
function _borrow(address to, uint256 amount)
internal
returns (uint256 part, uint256 share)
{
uint256 feeAmount =
amount.mul(BORROW_OPENING_FEE) / BORROW_OPENING_FEE_PRECISION; // A flat % fee is charged for any borrow
(totalBorrow, part) = totalBorrow.add(amount.add(feeAmount), true);
userBorrowPart[msg.sender] = userBorrowPart[msg.sender].add(part);
emit LogBorrow(msg.sender, to, amount, feeAmount, part);
share = vault.toShare(asset, amount, false);
Rebase memory _totalAsset = totalAsset;
require(_totalAsset.base >= 1000, "Banker: below minimum");
_totalAsset.elastic = _totalAsset.elastic.sub(share.to128());
totalAsset = _totalAsset;
vault.transfer(asset, address(this), to, share);
}
/// @notice Sender borrows `amount` and transfers it to `to`.
/// @return part Total part of the debt held by borrowers.
/// @return share Total amount in shares borrowed.
function borrow(address to, uint256 amount)
public
solvent
returns (uint256 part, uint256 share)
{
accrue();
(part, share) = _borrow(to, amount);
}
/// @dev Concrete implementation of `repay`.
function _repay(
address to,
bool skim,
uint256 part
) internal returns (uint256 amount) {
(totalBorrow, amount) = totalBorrow.sub(part, true);
userBorrowPart[to] = userBorrowPart[to].sub(part);
uint256 share = vault.toShare(asset, amount, true);
uint128 totalShare = totalAsset.elastic;
_addTokens(asset, share, uint256(totalShare), skim);
totalAsset.elastic = totalShare.add(share.to128());
emit LogRepay(skim ? address(vault) : msg.sender, to, amount, part);
}
/// @notice Repays a loan.
/// @param to Address of the user this payment should go.
/// @param skim True if the amount should be skimmed from the deposit balance of msg.sender.
/// False if tokens from msg.sender in `vault` should be transferred.
/// @param part The amount to repay. See `userBorrowPart`.
/// @return amount The total amount repayed.
function repay(
address to,
bool skim,
uint256 part
) public returns (uint256 amount) {
accrue();
amount = _repay(to, skim, part);
}
// Functions that need accrue to be called
uint8 internal constant ACTION_ADD_ASSET = 1;
uint8 internal constant ACTION_REPAY = 2;
uint8 internal constant ACTION_REMOVE_ASSET = 3;
uint8 internal constant ACTION_REMOVE_COLLATERAL = 4;
uint8 internal constant ACTION_BORROW = 5;
uint8 internal constant ACTION_GET_REPAY_SHARE = 6;
uint8 internal constant ACTION_GET_REPAY_PART = 7;
uint8 internal constant ACTION_ACCRUE = 8;
// Functions that don't need accrue to be called
uint8 internal constant ACTION_ADD_COLLATERAL = 10;
uint8 internal constant ACTION_UPDATE_EXCHANGE_RATE = 11;
// Function on pantry
uint8 internal constant ACTION_BENTO_DEPOSIT = 20;
uint8 internal constant ACTION_BENTO_WITHDRAW = 21;
uint8 internal constant ACTION_BENTO_TRANSFER = 22;
uint8 internal constant ACTION_BENTO_TRANSFER_MULTIPLE = 23;
uint8 internal constant ACTION_BENTO_SETAPPROVAL = 24;
// Any external call (except to pantry)
uint8 internal constant ACTION_CALL = 30;
int256 internal constant USE_VALUE1 = -1;
int256 internal constant USE_VALUE2 = -2;
/// @dev Helper function for choosing the correct value (`value1` or `value2`) depending on `inNum`.
function _num(
int256 inNum,
uint256 value1,
uint256 value2
) internal pure returns (uint256 outNum) {
outNum = inNum >= 0
? uint256(inNum)
: (inNum == USE_VALUE1 ? value1 : value2);
}
/// @dev Helper function for depositing into `vault`.
function _bentoDeposit(
bytes memory data,
uint256 value,
uint256 value1,
uint256 value2
) internal returns (uint256, uint256) {
(IERC20 token, address to, int256 amount, int256 share) =
abi.decode(data, (IERC20, address, int256, int256));
amount = int256(_num(amount, value1, value2)); // Done this way to avoid stack too deep errors
share = int256(_num(share, value1, value2));
return
vault.deposit{value: value}(
token,
msg.sender,
to,
uint256(amount),
uint256(share)
);
}
/// @dev Helper function to withdraw from the `vault`.
function _bentoWithdraw(
bytes memory data,
uint256 value1,
uint256 value2
) internal returns (uint256, uint256) {
(IERC20 token, address to, int256 amount, int256 share) =
abi.decode(data, (IERC20, address, int256, int256));
return
vault.withdraw(
token,
msg.sender,
to,
_num(amount, value1, value2),
_num(share, value1, value2)
);
}
/// @dev Helper function to perform a contract call and eventually extracting revert messages on failure.
/// Calls to `vault` are not allowed for obvious security reasons.
/// This also means that calls made from this contract shall *not* be trusted.
function _call(
uint256 value,
bytes memory data,
uint256 value1,
uint256 value2
) internal returns (bytes memory, uint8) {
(
address callee,
bytes memory callData,
bool useValue1,
bool useValue2,
uint8 returnValues
) = abi.decode(data, (address, bytes, bool, bool, uint8));
if (useValue1 && !useValue2) {
callData = abi.encodePacked(callData, value1);
} else if (!useValue1 && useValue2) {
callData = abi.encodePacked(callData, value2);
} else if (useValue1 && useValue2) {
callData = abi.encodePacked(callData, value1, value2);
}
require(
callee != address(vault) && callee != address(this),
"BankerPair: can't call"
);
(bool success, bytes memory returnData) =
callee.call{value: value}(callData);
require(success, "BankerPair: call failed");
return (returnData, returnValues);
}
struct CookStatus {
bool needsSolvencyCheck;
bool hasAccrued;
}
/// @notice Executes a set of actions and allows composability (contract calls) to other contracts.
/// @param actions An array with a sequence of actions to execute (see ACTION_ declarations).
/// @param values A one-to-one mapped array to `actions`. ETH amounts to send along with the actions.
/// Only applicable to `ACTION_CALL`, `ACTION_BENTO_DEPOSIT`.
/// @param datas A one-to-one mapped array to `actions`. Contains abi encoded data of function arguments.
/// @return value1 May contain the first positioned return value of the last executed action (if applicable).
/// @return value2 May contain the second positioned return value of the last executed action which returns 2 values (if applicable).
function cook(
uint8[] calldata actions,
uint256[] calldata values,
bytes[] calldata datas
) external payable returns (uint256 value1, uint256 value2) {
CookStatus memory status;
for (uint256 i = 0; i < actions.length; i++) {
uint8 action = actions[i];
if (!status.hasAccrued && action < 10) {
accrue();
status.hasAccrued = true;
}
if (action == ACTION_ADD_COLLATERAL) {
(int256 share, address to, bool skim) =
abi.decode(datas[i], (int256, address, bool));
addCollateral(to, skim, _num(share, value1, value2));
} else if (action == ACTION_ADD_ASSET) {
(int256 share, address to, bool skim) =
abi.decode(datas[i], (int256, address, bool));
value1 = _addAsset(to, skim, _num(share, value1, value2));
} else if (action == ACTION_REPAY) {
(int256 part, address to, bool skim) =
abi.decode(datas[i], (int256, address, bool));
_repay(to, skim, _num(part, value1, value2));
} else if (action == ACTION_REMOVE_ASSET) {
(int256 fraction, address to) =
abi.decode(datas[i], (int256, address));
value1 = _removeAsset(to, _num(fraction, value1, value2));
} else if (action == ACTION_REMOVE_COLLATERAL) {
(int256 share, address to) =
abi.decode(datas[i], (int256, address));
_removeCollateral(to, _num(share, value1, value2));
status.needsSolvencyCheck = true;
} else if (action == ACTION_BORROW) {
(int256 amount, address to) =
abi.decode(datas[i], (int256, address));
(value1, value2) = _borrow(to, _num(amount, value1, value2));
status.needsSolvencyCheck = true;
} else if (action == ACTION_UPDATE_EXCHANGE_RATE) {
(bool must_update, uint256 minRate, uint256 maxRate) =
abi.decode(datas[i], (bool, uint256, uint256));
(bool updated, uint256 rate) = updateExchangeRate();
require(
(!must_update || updated) &&
rate > minRate &&
(maxRate == 0 || rate > maxRate),
"BankerPair: rate not ok"
);
} else if (action == ACTION_BENTO_SETAPPROVAL) {
(
address user,
address _masterContract,
bool approved,
uint8 v,
bytes32 r,
bytes32 s
) =
abi.decode(
datas[i],
(address, address, bool, uint8, bytes32, bytes32)
);
vault.setMasterContractApproval(
user,
_masterContract,
approved,
v,
r,
s
);
} else if (action == ACTION_BENTO_DEPOSIT) {
(value1, value2) = _bentoDeposit(
datas[i],
values[i],
value1,
value2
);
} else if (action == ACTION_BENTO_WITHDRAW) {
(value1, value2) = _bentoWithdraw(datas[i], value1, value2);
} else if (action == ACTION_BENTO_TRANSFER) {
(IERC20 token, address to, int256 share) =
abi.decode(datas[i], (IERC20, address, int256));
vault.transfer(
token,
msg.sender,
to,
_num(share, value1, value2)
);
} else if (action == ACTION_BENTO_TRANSFER_MULTIPLE) {
(IERC20 token, address[] memory tos, uint256[] memory shares) =
abi.decode(datas[i], (IERC20, address[], uint256[]));
vault.transferMultiple(token, msg.sender, tos, shares);
} else if (action == ACTION_CALL) {
(bytes memory returnData, uint8 returnValues) =
_call(values[i], datas[i], value1, value2);
if (returnValues == 1) {
(value1) = abi.decode(returnData, (uint256));
} else if (returnValues == 2) {
(value1, value2) = abi.decode(
returnData,
(uint256, uint256)
);
}
} else if (action == ACTION_GET_REPAY_SHARE) {
int256 part = abi.decode(datas[i], (int256));
value1 = vault.toShare(
asset,
totalBorrow.toElastic(_num(part, value1, value2), true),
true
);
} else if (action == ACTION_GET_REPAY_PART) {
int256 amount = abi.decode(datas[i], (int256));
value1 = totalBorrow.toBase(
_num(amount, value1, value2),
false
);
}
}
if (status.needsSolvencyCheck) {
require(
_isSolvent(msg.sender, false, exchangeRate),
"BankerPair: user insolvent"
);
}
}
/// @notice Handles the liquidation of users' balances, once the users' amount of collateral is too low.
/// @param users An array of user addresses.
/// @param maxBorrowParts A one-to-one mapping to `users`, contains maximum (partial) borrow amounts (to liquidate) of the respective user.
/// @param to Address of the receiver in open liquidations if `swapper` is zero.
/// @param swapper Contract address of the `ISwapper` implementation. Swappers are restricted for closed liquidations. See `setSwapper`.
/// @param open True to perform a open liquidation else False.
function liquidate(
address[] calldata users,
uint256[] calldata maxBorrowParts,
address to,
ISwapper swapper,
bool open
) public {
// Oracle can fail but we still need to allow liquidations
(, uint256 _exchangeRate) = updateExchangeRate();
accrue();
uint256 allCollateralShare;
uint256 allBorrowAmount;
uint256 allBorrowPart;
Rebase memory _totalBorrow = totalBorrow;
Rebase memory vaultTotals = vault.totals(collateral);
for (uint256 i = 0; i < users.length; i++) {
address user = users[i];
if (!_isSolvent(user, open, _exchangeRate)) {
uint256 borrowPart;
{
uint256 availableBorrowPart = userBorrowPart[user];
borrowPart = maxBorrowParts[i] > availableBorrowPart
? availableBorrowPart
: maxBorrowParts[i];
userBorrowPart[user] = availableBorrowPart.sub(borrowPart);
}
uint256 borrowAmount =
_totalBorrow.toElastic(borrowPart, false);
uint256 collateralShare =
vaultTotals.toBase(
borrowAmount.mul(LIQUIDATION_MULTIPLIER).mul(
_exchangeRate
) /
(LIQUIDATION_MULTIPLIER_PRECISION *
EXCHANGE_RATE_PRECISION),
false
);
userCollateralShare[user] = userCollateralShare[user].sub(
collateralShare
);
emit LogRemoveCollateral(
user,
swapper == ISwapper(0) ? to : address(swapper),
collateralShare
);
emit LogRepay(
swapper == ISwapper(0) ? msg.sender : address(swapper),
user,
borrowAmount,
borrowPart
);
// Keep totals
allCollateralShare = allCollateralShare.add(collateralShare);
allBorrowAmount = allBorrowAmount.add(borrowAmount);
allBorrowPart = allBorrowPart.add(borrowPart);
}
}
require(allBorrowAmount != 0, "BankerPair: all are solvent");
_totalBorrow.elastic = _totalBorrow.elastic.sub(
allBorrowAmount.to128()
);
_totalBorrow.base = _totalBorrow.base.sub(allBorrowPart.to128());
totalBorrow = _totalBorrow;
totalCollateralShare = totalCollateralShare.sub(allCollateralShare);
uint256 allBorrowShare = vault.toShare(asset, allBorrowAmount, true);
if (!open) {
// Closed liquidation using a pre-approved swapper for the benefit of the LPs
require(
masterContract.swappers(swapper),
"BankerPair: Invalid swapper"
);
// Swaps the users' collateral for the borrowed asset
vault.transfer(
collateral,
address(this),
address(swapper),
allCollateralShare
);
swapper.swap(
collateral,
asset,
address(this),
allBorrowShare,
allCollateralShare
);
uint256 returnedShare =
vault.balanceOf(asset, address(this)).sub(
uint256(totalAsset.elastic)
);
uint256 extraShare = returnedShare.sub(allBorrowShare);
uint256 feeShare =
extraShare.mul(PROTOCOL_FEE) / PROTOCOL_FEE_DIVISOR; // % of profit goes to fee
// solhint-disable-next-line reentrancy
vault.transfer(
asset,
address(this),
masterContract.feeTo(),
feeShare
);
totalAsset.elastic = totalAsset.elastic.add(
returnedShare.sub(feeShare).to128()
);
emit LogAddAsset(
address(swapper),
address(this),
extraShare.sub(feeShare),
0
);
} else {
// Swap using a swapper freely chosen by the caller
// Open (flash) liquidation: get proceeds first and provide the borrow after
vault.transfer(
collateral,
address(this),
swapper == ISwapper(0) ? to : address(swapper),
allCollateralShare
);
if (swapper != ISwapper(0)) {
swapper.swap(
collateral,
asset,
msg.sender,
allBorrowShare,
allCollateralShare
);
}
vault.transfer(asset, msg.sender, address(this), allBorrowShare);
totalAsset.elastic = totalAsset.elastic.add(allBorrowShare.to128());
}
}
/// @notice Withdraws the fees accumulated.
function withdrawFees() public {
accrue();
address _feeTo = masterContract.feeTo();
uint256 _feesEarnedFraction = accrueInfo.feesEarnedFraction;
balanceOf[_feeTo] = balanceOf[_feeTo].add(_feesEarnedFraction);
accrueInfo.feesEarnedFraction = 0;
emit LogWithdrawFees(_feeTo, _feesEarnedFraction);
}
/// @notice Used to register and enable or disable swapper contracts used in closed liquidations.
/// MasterContract Only Admin function.
/// @param swapper The address of the swapper contract that conforms to `ISwapper`.
/// @param enable True to enable the swapper. To disable use False.
function setSwapper(ISwapper swapper, bool enable) public onlyOwner {
swappers[swapper] = enable;
}
/// @notice Sets the beneficiary of fees accrued in liquidations.
/// MasterContract Only Admin function.
/// @param newFeeTo The address of the receiver.
function setFeeTo(address newFeeTo) public onlyOwner {
feeTo = newFeeTo;
emit LogFeeTo(newFeeTo);
}
}
|
Concrete implementation of `borrow`.
|
function _borrow(address to, uint256 amount)
internal
returns (uint256 part, uint256 share)
{
uint256 feeAmount =
(totalBorrow, part) = totalBorrow.add(amount.add(feeAmount), true);
userBorrowPart[msg.sender] = userBorrowPart[msg.sender].add(part);
emit LogBorrow(msg.sender, to, amount, feeAmount, part);
share = vault.toShare(asset, amount, false);
Rebase memory _totalAsset = totalAsset;
require(_totalAsset.base >= 1000, "Banker: below minimum");
_totalAsset.elastic = _totalAsset.elastic.sub(share.to128());
totalAsset = _totalAsset;
vault.transfer(asset, address(this), to, share);
}
| 5,355,352
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface IPriceFeed {
function lastGoodPrice() external view returns(uint);
function tellorCaller() external view returns(address);
// --- Events ---
event LastGoodPriceUpdated(uint _lastGoodPrice);
// --- Function ---
function fetchPrice() external returns (uint);
}
|
--- Events --- --- Function ---
|
interface IPriceFeed {
function lastGoodPrice() external view returns(uint);
function tellorCaller() external view returns(address);
event LastGoodPriceUpdated(uint _lastGoodPrice);
function fetchPrice() external returns (uint);
}
| 5,399,637
|
./full_match/1/0xE8Ff7BFEF5DacB57E87bC2d0B6CCFefBE5f546BC/sources/src/Facets/OptimismBridgeFacet.sol
|
Contains the business logic for the bridge via Optimism Bridge _bridgeData Data contaning core information for bridging _bridgeData Data specific to Optimism Bridge
|
function _startBridge(
ILiFi.BridgeData memory _bridgeData,
OptimismData calldata _optimismData
) private {
Storage storage s = getStorage();
IL1StandardBridge nonStandardBridge = s.bridges[
_bridgeData.sendingAssetId
];
IL1StandardBridge bridge = LibUtil.isZeroAddress(
address(nonStandardBridge)
)
? s.standardBridge
: nonStandardBridge;
if (LibAsset.isNativeAsset(_bridgeData.sendingAssetId)) {
_bridgeData.receiver,
_optimismData.l2Gas,
""
);
LibAsset.maxApproveERC20(
IERC20(_bridgeData.sendingAssetId),
address(bridge),
_bridgeData.minAmount
);
if (_optimismData.isSynthetix) {
bridge.depositTo(_bridgeData.receiver, _bridgeData.minAmount);
bridge.depositERC20To(
_bridgeData.sendingAssetId,
_optimismData.assetIdOnL2,
_bridgeData.receiver,
_bridgeData.minAmount,
_optimismData.l2Gas,
""
);
}
}
emit LiFiTransferStarted(_bridgeData);
}
| 16,461,225
|
./partial_match/1/0xd999D5a20294ec90c4f792F63820112E22E61059/sources/contracts/Sale/FomoMarketplace.sol
|
Method for accepting the offer _nftAddress NFT contract address _tokenId TokenId _creator Offer creator address Transfer NFT to buyer
|
function acceptOffer(
address _nftAddress,
uint256 _tokenId,
address _creator
) external nonReentrant {
Offer memory offer = offers[_nftAddress][_tokenId][_creator];
if (_supportERC721(_nftAddress)) {
IERC721 nft = IERC721(_nftAddress);
require(
nft.ownerOf(_tokenId) == _msgSender(),
"Not owning the item."
);
IERC1155 nft = IERC1155(_nftAddress);
require(
nft.balanceOf(_msgSender(), _tokenId) >= offer.quantity,
"Not owning the item."
);
revert("Invalid NFT address.");
}
require(
offer.pricePerItem > 0 && offer.quantity > 0,
"Offer doesn't exist."
);
uint256 price = offer.pricePerItem.mul(offer.quantity);
uint256 feeAmount = price.mul(platformFee).div(1e3);
uint256 royaltyFee;
if (
_nftAddress == fomo721 &&
minters[_nftAddress][_tokenId] != address(0) &&
royalties[_nftAddress][_tokenId] != uint8(0)
) {
royaltyFee = price
.sub(feeAmount)
.mul(royalties[_nftAddress][_tokenId])
.div(100);
offer.payToken.safeTransferFrom(
_creator,
minters[_nftAddress][_tokenId],
royaltyFee
);
feeAmount = feeAmount.add(royaltyFee);
}
offer.payToken.safeTransferFrom(_creator, feeReceipient, feeAmount);
offer.payToken.safeTransferFrom(
_creator,
_msgSender(),
price.sub(feeAmount)
);
if (_supportERC721(_nftAddress)) {
IERC721(_nftAddress).safeTransferFrom(
_msgSender(),
_creator,
_tokenId
);
IERC1155(_nftAddress).safeTransferFrom(
_msgSender(),
_creator,
_tokenId,
offer.quantity,
bytes("")
);
}
delete (listings[_nftAddress][_tokenId][_msgSender()]);
delete (offers[_nftAddress][_tokenId][_creator]);
emit ItemSold(
_msgSender(),
_creator,
_nftAddress,
_tokenId,
offer.quantity,
offer.pricePerItem
);
emit OfferCanceled(_creator, _nftAddress, _tokenId);
}
| 3,711,126
|
./full_match/4/0x59FAC14333e6D9B23ECEcee2d4D9DdeE51D88979/sources/contracts/MutatantLoot.sol
|
Requests randomness/requestIdToTokenURI[requestId] = tokenURI;
|
function createLootTicket()
public {
bytes32 requestId = requestRandomness(keyHash, fee);
requestIdToSender[requestId] = msg.sender;
emit requestedCollectible(requestId);
}
| 12,406,464
|
/**
*Submitted for verification at Etherscan.io on 2020-12-11
*/
//"SPDX-License-Identifier: UNLICENSED"sdgeryjewrtrwedcvdfbasAFwe
//frgwert34rgvfev
//frgwert34rgvfev
pragma solidity ^0.6.0;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV
//frgwert34rgvfev9[4R]
abstract contract Context {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUA
//frgwert34rgvfevCV9[4R]
function _msgSender() internal view virtual returns (address payable) {////////sdfert/weh98pWSEI;Jdsewr78
//frgwert34rgvfev039- Q70wgQY3HEwnqdNBHSUACV9[4R]
return msg.sender;}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
function _msgData() internal view virtual returns (bytes memory) {////////sdfert/weh98pWSEI;Jdsewr78
//frgwert34rgvfev039- Q70wgQY3HEwnqdNBHSUACV9[4R]
this;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HE
//frgwert34rgvfevwnqdNBHSUACV9[4R]
return msg.data;}}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
interface IERC20 {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
function totalSupply() external view returns (uint256);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
//frgwert34rgvfev
function balanceOf(address account)external view returns (uint256);////////sdfert/weh98pWSEI;Jdsewr78039- Q70
//frgwert34rgvfevwgQY3HEwnqdNBHSUACV9[4R]
function transfer(address recipient, uint256 amount) external returns (bool);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
function allowance(address owner,address spender) external view returns (uint256);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
function approve(address spender,uint256 amount) external returns (bool);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQ
//frgwert34rgvfevY3HEwnqdNBHSUACV9[4R]
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
event Transfer(address indexed from, address indexed to, uint256 value);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
event Approval(address indexed owner, address indexed spender, uint256 value);}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
library SafeMath {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
function add(uint256 a, uint256 b) internal pure returns (uint256) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
uint256 c = a + b + 0;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
require(c >= (a+0), "SafeMath: addition overflow");////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
return c;}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
function sub(uint256 a, uint256 b) internal pure returns (uint256) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
return sub(a, b, "SafeMath: subtraction overflow");}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
require(b <= a, errorMessage);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
uint256 c = a - b;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
return c;}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
function mul(uint256 a, uint256 b) internal pure returns (uint256) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
if (a == 0) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
return 0;}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
uint256 c = a * b * 1;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
require(c / a == b, "SafeMath: multiplication overflow");////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
return c;}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
function div(uint256 a, uint256 b) internal pure returns (uint256) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
return div(a, b, "SafeMath: division by zero");}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
function diwegrwergw43t5t3h356hv(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
require(b > 0, errorMessage);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
uint256 c = a / b;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
return c;}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
require(b > 0, errorMessage);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
uint256 c = a / b;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
return c;}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
function mod(uint256 a, uint256 b) internal pure returns (uint256) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqEwnqdNBHSUACVRTHHHHHHGFEER15666WERF
//frgwert34rgvfevdNBHSUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
return mod(a, b, "SafeMath: modulo by zero");}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHEwnqdNBHSUACVRTHHHHHHGFEER15666WERF
//frgwert34rgvfevSUACV9[4R]
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
//frgwert34rgvfevHEwnqdNBHSUACV9[4R]
require(b != 0, errorMessage);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnEwnqdNBHSUACVRTHHHHHHGFEER15666WERF
//frgwert34rgvfevqdNBHSUACV9[4R]
return a % b;}}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEEwnqdNBHSUACVRTHHHHHHGFEER15666WERF
//frgwert34rgvfevwnqdNBHSUACV9[4R]
pragma solidity ^0.6.2;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUAEwnqdNBHSUACVRTHHHHHHGFEER15666WERF
//frgwert34rgvfevCV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
library Address {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUA
//frgwert34rgvfevCV9[4R]
function isContract(address account) internal view returns (bool) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
uint256 size;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
assembly { size := extcodesize(account) }////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQ
//frgwert34rgvfevY3HEwnqdNBHSUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
return size > 0;}////////sdfert/weh98pWSEI;JdsewEwnqdNBHSUACVRTHHHHHHGFEER15666WERFr78039- Q70wgQY3HEwnqdNBHSUACV9
//frgwert34rgvfev[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
function sendValue(address payable recipient, uint256 amount) internal {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACVRTHHHHHHGFEER15666WERF
//frgwert34rgvfev9[4R]
require(address(this).balance >= amount, "Address: insufficient balance");///////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HE
//frgwert34rgvfevvwnqdNBHSUACV9[4R]
(bool success, ) = recipient.call{ value: amount }("");////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
//frgwert34rgvfev
require(success, "Address: unable to send value, recipient may have reverted");}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBH
//frgwert34rgvfev
//frgwert34rgvfevSUACV9[4R]
function functionCall(address target, bytes memory data) internal returns (bytes memory) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBH
//frgwert34rgvfevSUACV9[4R]
return functionCall(target, data, "Address: low-level call failed");}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wg
//frgwert34rgvfevQY3HEwnqdNBHSUACV9[4R]
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSU
//frgwert34rgvfevACV9[4R]
return _functionCallWithValue(target, data, 0, errorMessage);}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
//frgwert34rgvfev
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
//frgwert34rgvfev
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
//frgwert34rgvfev
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {////////sdfert/weh98pWSEI;Jdsewr78039-
//frgwert34rgvfev Q70wgQY3HEwnqdNBHSUACV9[4R]
require(address(this).balance >= value, "Address: insufficient balance for call");////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
//frgwert34rgvfev
return _functionCallWithValue(target, data, value, errorMessage);}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70
//frgwert34rgvfevwgQY3HEwnqdNBHSUACV9[4R]
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3
//frgwert34rgvfevHEwnqdNBHSUACV9[4R]returndata.length > returndata.length > returndata.length > returndata.length > returndata.length >
require(isContract(target), "Address: call to non-contract");////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSU
//frgwert34rgvfevACV9[4R]
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/we
//frgwert34rgvfevh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
if (success) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQ
//frgwert34rgvfevY3HEwnqdNBHSUACV9[4R]////////sreturndata.length > dfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
return returndata;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQreturndata.length >
//frgwert34rgvfevY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
} else {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSU
//frgwert34rgvfevACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
if (0 < returndata.length) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
assembly {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
let returndata_size := mload(returndata)////////sdfert/weh98pWSEI;Jdsewr78039-
//frgwert34rgvfev Q70wgQY3HEwnqdNBHSUACV9[4R]
revert(add(32, returndata), returndata_size)}}else {revert(errorMessage);}}}}////////EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
//frgwert34rgvfevsdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr7803
//frgwert34rgvfev9- Q70wgQY3HEwnqdNBHSUACV9[4R]
pragma solidity ^0.6.0;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
//frgwert34rgvfev
contract ERC20 is Context, IERC20 {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
using SafeMath for uint256;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
//frgwert34rgvfev
using Address for address;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
mapping (address => uint256) private _balances;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
mapping (address => mapping (address => uint256)) private _allowances;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
uint256 private _totalSupply;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
//frgwert34rgvfev
string private _name;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
string private _symbol;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
uint8 private _decimals;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
//frgwert34rgvfev
constructor (string memory name, string memory symbol) public {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
_name = name;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
//frgwert34rgvfev
_symbol = symbol;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
_decimals = 10;}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
function name() public view returns (string memory) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
return _name;}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]V////////sdfert/weh98pWSEI;Jdsewr78039-
//frgwert34rgvfevQ70wgQY3HEwnqdNBHSUACV9[4R]
function symbol() public view returns (string memory) {////////sdfert/weh98pWSEI;34TJdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
return _symbol;}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
//frgwert34rgvfev
//frgwert34rgvfev
function decimals() public view returns (uint8) {////////sdfert/weh98pWSEI;JdsewrWFERG78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
return _decimals;}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9XA[4R]////////sdfert/weh98pWSEI;Jdsewr78039-
//frgwert34rgvfev Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
function totalSupply() public view override returns (uint256) {////////sdfert/weh98pWERDCSXWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV
//frgwert34rgvfev9[4R]
return _totalSupply;}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUAXCVBFCV9[4R]
function balanceOf(address account) public view override returns (uint256) {////////sdfert/weh98pWSEI;Jdsewr780XCVBXCV39- Q70wgQY3HEwnqdNBHSUACV9[4R]
//frgwert34rgvfev
return _balances[account];}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWERHSDGVBWSEI;JdseSDFGSwr78039
//frgwert34rgvfev- Q70wgQY3HEwnqdNBHSUACV9[4R]
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {////////sdfert/weh98pWSEI;Jdsewr78039- SDFGWQ70wgQY3HEwnq
//frgwert34rgvfevdNBHSUACV
//frgwert34rgvfev9[4R]
_transfer(_msgSender(), recipient, amount);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]//WERTWEHSFBSF//////sdfert/weh98pWSEI;Jdsewr78039
//frgwert34rgvfev- Q70wgQY3HEwnqdNBHSUACV9[4R]
return true;}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]V////////sdfert/weh98pWSEWTHW453I;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
function allowance(address owner, address spender) public view virtual override returns (uint256) {///ERTHWERHG/////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSU
//frgwert34rgvfevACV9[4R]
return _allowances[owner][spender];}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqWERGWRTdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
function approve(address spender, uint256 amount) public virtual override returns (bool) {//WEYWER//////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
//frgwert34rgvfev
_approve(_msgSender(), spender, amount);////////sdfert/weh98pWSEI;Jdsewr78039- WERG Q70wgQY3HEwnqdNBHSUACV9[4R]
return true;}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]SEFWYW
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3EYHERTHHEwFSFnqdNBHSUACV9[4R]
_transfer(sender, recipient, amount);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSFS
//frgwert34rgvfevFUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));////////sdfert/weh98pWSEI;JdsewRYJMRHr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
return true;}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]JM
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBQ34R45Y65HTBGBNH
//frgwert34rgvfevSUACV9[4R]
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdDFGBDREW4NBHSUACV9[4R]
return true;}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnq34562345dNBHSUACV9[
//frgwert34rgvfev4R]
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {////////sdfert/weh98pWSEI;Jdsewr7803234T234T9- Q70wgQYERWER3HEwnqdNBHSUACV9[4R]
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));//RTHE5//////sdfert/weh98pWSEI;
//frgwert34rgvfevJdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
return true;}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;JdsewRYJ76544536r78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
function _transfer(address sender, address recipient, uint256 amount) internal virtual {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
require(sender != address(0), "ERC20: transfer from the zero address");////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSGUACV9[4R]
//frgwert34rgvfev
require(recipient != address(0), "ERC20: transfer to the zero address");////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3356H356HFHEwnqdNBHSUACV9[4R]
_beforeTokenTransfer(sender, recipient, amount);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]WERG4
//frgwert34rgvfev
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");////////sdfert/weh98pWSEI;JdseDFGBERTwr78039- Q70wgQY3HEwnqdNBHSUA
//frgwert34rgvfevCV9[4R]
_balances[recipient] = _balances[recipient].add(amount);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUSGFBRACV9[4R]
emit Transfer(sender, recipient, amount);}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]5TWE5T
//frgwert34rgvfev
function _mint(address account, uint256 amount) internal virtual {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBFGBR5BHSUACV9[4R]
require(account != address(0), "ERC20: mint to the zero address");////////sdfert/weh98pWSEI;Jdsewr78039- Q70ERTERGFVwgQY3HEwnqdNBHSUACV9[4R]
//frgwert34rgvfev
_beforeTokenTransfer(address(0), account, amount);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqSDFETEdNBHSUACV9[4R]
_totalSupply = _totalSupply.add(amount);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]SDFBRTE
_balances[account] = _balances[account].add(amount);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNSDFBSRTET4BHSUACV9[4R]
//frgwert34rgvfev
emit Transfer(address(0), account, amount);}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]S
function _burn(address account, uint256 amount) internal virtual {////////sdfert/weh98pWSEI;Jdsewr78039- QSDFB70wgQY3HEwnqdNBHSUACV9[4R]
require(account != address(0), "ERC20: burn from the zero address");////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBGSHSUACV9[4R]
//frgwert34rgvfev
_beforeTokenTransfer(account, address(0), amount);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9SRDGSDFGSDR[4R]
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");////////sdfert/weh98pWSEDI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
//frgwert34rgvfev
_totalSupply = _totalSupply.sub(amount);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]ASWEE
emit Transfer(account, address(0), amount);}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]GSDFGVXC
//frgwert34rgvfev
function _approve(address owner, address spender, uint256 amount) internal virtual {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgVZFGRQY3HEwnqdNBHSUACV9[4R]
//frgwert34rgvfev
require(owner != address(0), "ERC20: approve from the zero address");////////sdfert/weh98pWSEI;JdsewrEwnqdNBHSUACVRTHHHHHHGFEER15666WERF78039- Q70wgQRTERGDFVZXY3HEwnqdNBHSUACV9[4R]
//frgwert34rgvfevEwnqdNBHSUACVRTHHHHHHGFEER15666WERF
require(spender != address(0), "ERC20: approve to the zero address");////////sdfert/weh98pWSEI;JdEwnqdNBHSUACVRTHHHHHHGFEER15666WERFsewr78039- Q7RFVZ0wgQY3HEwnqdNBHSUACV9[4R]
_allowances[owner][spender] = amount;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUAEwnqdNBHSUACVRTHHHHHHGFEER15666WERFCV9[4R]ZXCRGTW
//frgwert34rgvfevEwnqdNBHSUACVRTHHHHHHGFEER15666WERF
emit Approval(owner, spender, amount);}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUAEwnqdNBHSUACVRTHHHHHHGFEER15666WERFCVASDF9[4R]
//frgwert34rgvfevEwnqdNBHSUACVRTHHHHHHGFEER15666WERF
function _setupDecimals(uint8 decimals_) internal {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQYEwnqdNBHSUACVRTHHHHHHGFEER15666WERF3HEwWTHnqdNBHSUACV9[4R]
_decimals = decimals_;}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]WERTEwnqdNBHSUACVRTHHHHHHGFEER15666WERFWERT
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }}////////sdfeREwnqdNBHSUACVRTHHHHHHGFEER15666WERFETWERTrt/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]
//frgwert34rgvfev
abstract contract ERC20Burnable is Context, ERC20 {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqEwnqdNBHSUACVRTHHHHHHGFEER15666WERFdNBHSUACERTWERTV9[4R]
//frgwert34rgvfev
function burn(uint256 amount) public virtual {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBEwnqdNBHSUACVRTHHHHHHGFEER15666WERFHSUACV9[4R]
//frgwert34rgvfev
//frgwert34rgvfev
_burn(_msgSender(), amount);}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]TWETEwnqdNBHSUACVRTHHHHHHGFEER15666WERF
//frgwert34rgvfev
function burnFrom(address account, uint256 amount) public virtual {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHS5TWERUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERFEwnqdNBHSUACVRTHHHHHHGFEER15666WERF
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");////////sdfert/weh98pWSEI;RTG5TJEwnqdNBHSUACVRTHHHHHHGFEER15666WERFdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
//frgwert34rgvfevEwnqdNBHSUACVRTHHHHHHGFEER15666WERF
_approve(account, _msgSender(), decreasedAllowance);////////sdfert/weh98pWSEI;JdsewET34YJHDBFr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]EEwnqdNBHSUACVRTHHHHHHGFEER15666WERFwnqdNBHSUACVRTHHHHHHGFEER15666WERF
//frgwert34rgvfev
_burn(account, amount);}}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNB4T5HSUACV6U3569[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSURGWEYACV9[4R]
//frgwert34rgvfev
///////////////////////////////GSDFG/////////////////////////////////////////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
//frgwert34rgvfev
////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUTWERGDFACV9[4R]
//frgwert34rgvfevEwnqdNBHSUACVRTHHHHHHGFEER15666WERF
/////////////////////////////////////////////////////////////SDFE///////////////sdferERFDSFt/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
//frgwert34rgvfev
////////////////////////////////////////////////////////////////////////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
//frgwert34rgvfev
////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfeERTrt/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
//frgwert34rgvfev
contract EasyToken is ERC20, ERC20Burnable {////////sdfert/weh98pWSEI;Jdsewr78039- Q7EWTRE0wgQY3HEwnqdNBERTHSUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
constructor(uint256 initialSupply) public ERC20("easify.network", "EASY") {////////sdfert/weFGDSFDGh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
//frgwert34rgvfev
//frgwert34rgvfevEwnqdNBHSUACVRTHHHHHHGFEER15666WERF
initialSupply = 10000000e10;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]//RT//////sdfertDFGDF/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
//frgwert34rgvfev
_mint(msg.sender, initialSupply);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R45Y]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF
//frgwert34rgvfev
}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]YTH4563
//frgwert34rgvfev
}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]EWRGWRYJ6Y5RE
//frgwert34rgvfev
|
sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBFGBR5BHSUACV9[4R]
|
function _mint(address account, uint256 amount) internal virtual {
| 2,079,393
|
// _________ _________ _______ __________
// /__ __\| _____) / . \/ _____/
// |___| |___|\____\/___/ \___\________\
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol";
import "./ITRACSerums.sol";
import "./ICREDIT.sol";
contract TRAC is ERC721EnumerableUpgradeable, OwnableUpgradeable, ReentrancyGuardUpgradeable {
using AddressUpgradeable for address;
uint16 constant public MAX_SUPPLY = 8888;
bool public claimActive;
ITRACSerums private _serums;
uint16 public minted;
struct TokenTime { uint16 token; uint48 timestamp; }
struct OwnerTime { address owner; uint48 timestamp; }
mapping(uint16 => OwnerTime) private _transfers;
mapping(uint16 => OwnerTime) private _minters;
mapping(address => uint16) private _balance;
mapping(uint256 => address) private _tokenApprovals;
mapping(uint256 => uint64[]) private _metadataKeys;
ICREDIT private _credit;
address private _verifier;
function initialize(address serums) public initializer {
__ERC721_init("Teen Rebel Ape Club", "TRAC");
__ERC721Enumerable_init_unchained();
__Ownable_init_unchained();
__ReentrancyGuard_init_unchained();
_serums = ITRACSerums(serums);
}
function toggleClaims() external onlyOwner {
claimActive = !claimActive;
}
/**
* @dev Claim your milk serums!
*/
function claim(uint256[] calldata ids, uint256[] calldata amounts) external nonReentrant {
address to = msg.sender;
require(tx.origin == to, "eos only");
require(claimActive || to == owner(), "not active");
require(ids.length == amounts.length, "invalid params");
uint256 amount;
for (uint8 i; i < amounts.length; i++) {
amount += amounts[i];
}
uint256 tokenId = minted + 1;
uint256 endTokenId = minted + amount;
require(endTokenId <= MAX_SUPPLY, "supply exhausted");
_minters[uint16(tokenId)] = OwnerTime(to, uint48(block.timestamp));
_balance[to] += uint16(amount);
minted = uint16(endTokenId);
_serums.burnBatch(to, ids, amounts);
for (; tokenId <= endTokenId; tokenId++) {
emit Transfer(address(0), to, tokenId);
require(
__checkOnERC721Received(address(0), to, tokenId, ""),
"ERC721A: transfer to non ERC721Receiver implementer"
);
}
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*/
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");
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balance[from] -= 1;
_balance[to] += 1;
_transfers[uint16(tokenId)] = OwnerTime(to, uint48(block.timestamp));
emit Transfer(from, to, tokenId);
}
/**
* @dev Retrieve a list of owner and vesting start times for each token.
*/
function ownerTimesOf(uint16[] memory tokens) public view returns (OwnerTime[] memory ownerTimes) {
ownerTimes = new OwnerTime[](tokens.length);
uint16 id;
for (uint16 i; i < tokens.length; i++) {
id = tokens[i];
if (_transfers[id].owner != address(0)) {
ownerTimes[i] = _transfers[id];
} else {
for (; id > 0; id--) {
if (_minters[id].owner != address(0)) {
ownerTimes[i] = _minters[id];
break;
}
}
}
}
}
/**
* @dev Retrieve the owner and vesting start times for the given token.
*/
function _ownerTimeOf(uint16 token) private view returns (OwnerTime memory ownerTime) {
if (_transfers[token].owner != address(0)) {
return _transfers[token];
} else {
for (; token > 0; token--) {
if (_minters[token].owner != address(0)) {
return _minters[token];
}
}
}
}
/**
* @dev Helper method to serve both {tokensOf} and {tokenOfOwnerByIndex}
*/
function _tokensOfOwnerUpToAmount(address account, uint256 amount) private view returns (TokenTime[] memory tokenTimes) {
uint16 i;
tokenTimes = new TokenTime[](amount);
OwnerTime memory minterTime;
for (uint16 token = 1; token <= minted; token++) {
if (_minters[token].owner != address(0)) {
minterTime = _minters[token];
}
if (_transfers[token].owner != address(0)) {
if (_transfers[token].owner == account) {
tokenTimes[i++] = TokenTime(token, _transfers[token].timestamp);
if (i == amount) {
return tokenTimes;
}
}
} else if (minterTime.owner == account) {
tokenTimes[i++] = TokenTime(token, minterTime.timestamp);
if (i == amount) {
return tokenTimes;
}
}
}
}
/**
* @dev Retrieve a list of owned tokens and vensting start times for each token.
*/
function tokenTimesOf(address account) external view returns (TokenTime[] memory tokenTimes) {
if (_balance[account] == 0) {
tokenTimes = new TokenTime[](0);
} else {
return _tokensOfOwnerUpToAmount(account, _balance[account]);
}
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address account, uint256 index) public view override returns (uint256) {
require(_balance[account] > 0, "no tokens");
require(index < _balance[account], "exceeds boundary");
return uint256(_tokensOfOwnerUpToAmount(account, index + 1)[index].token);
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "nonexistent");
uint16 id = uint16(tokenId);
address owner = _transfers[id].owner;
if (owner != address(0)) {
return owner;
}
for (; id > 0; id--) {
owner = _minters[id].owner;
if (owner != address(0)) {
return owner;
}
}
revert("unable to find owner");
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721: transfer to the zero address");
return uint256(_balance[owner]);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return minted;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view override 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 Approve `to` to operate on `tokenId`
*/
function _approve(address to, uint256 tokenId) internal override {
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
/**
* @dev Returns whether `tokenId` exists.
*/
function _exists(uint256 tokenId) internal view override returns (bool) {
return tokenId > 0 && tokenId <= minted;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
*/
function __checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal returns (bool) {
if (to.isContract()) {
try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Internal override for URI.
*/
function _baseURI() internal pure override returns (string memory) {
return "https://teenrebelapeclub.com/api/trac/metadata/";
}
/**
* @dev Set $CREDIT address. Used to pay for metadata updates.
*/
function setCreditAddress(address creditAddress) external onlyOwner {
_credit = ICREDIT(creditAddress);
}
/**
* @dev Set signature verifier address. Used to approve metadata update requests.
*/
function setVerifier(address verifier) external onlyOwner {
_verifier = verifier;
}
/**
* @dev Set or update metadata identifiers to create and/or override specific trait values.
*/
function setMetadata(uint256 token, uint8 key, uint64 id, uint256 cost, bytes memory signature) external {
require(ECDSAUpgradeable.recover(
ECDSAUpgradeable.toEthSignedMessageHash(keccak256(abi.encodePacked(msg.sender, token, key, id, cost))),
signature) == _verifier, "verification failure");
_credit.burn(msg.sender, cost);
_metadataKeys[token][key] = id;
}
/**
* @dev Get existing metadata identifiers.
*/
function getMetadataKeys(uint256 token) external view returns (uint64[] memory keys) {
uint256 count = _metadataKeys[token].length;
keys = new uint64[](count);
for (uint256 i; i < count; i++) keys[i] = _metadataKeys[token][i];
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
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 onlyInitializing {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// 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;
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721Upgradeable.sol";
import "./IERC721EnumerableUpgradeable.sol";
import "../../../proxy/utils/Initializable.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 ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable {
function __ERC721Enumerable_init() internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721Enumerable_init_unchained();
}
function __ERC721Enumerable_init_unchained() internal onlyInitializing {
}
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) {
return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Upgradeable.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721EnumerableUpgradeable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721Upgradeable.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721Upgradeable.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
uint256[46] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../StringsUpgradeable.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSAUpgradeable {
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 Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", StringsUpgradeable.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
interface ITRACSerums {
function balanceOf(address, uint256) external view returns (uint256);
function burnBatch(address, uint256[] calldata, uint256[] calldata) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
interface ICREDIT {
function totalSupply() external view returns (uint256);
function balanceOf(address) external view returns (uint256);
function transfer(address, uint256) external returns (bool);
function allowance(address, address) external view returns (uint256);
function approve(address, uint256) external returns (bool);
function transferFrom(address, address, uint256) external returns (bool);
function burn(address, uint256) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
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 onlyInitializing {
__Context_init_unchained();
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
pragma solidity ^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 {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.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 ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721EnumerableUpgradeable is IERC721Upgradeable {
/**
* @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
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.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 ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// 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 IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
|
Set or update metadata identifiers to create and/or override specific trait values./
|
function setMetadata(uint256 token, uint8 key, uint64 id, uint256 cost, bytes memory signature) external {
require(ECDSAUpgradeable.recover(
ECDSAUpgradeable.toEthSignedMessageHash(keccak256(abi.encodePacked(msg.sender, token, key, id, cost))),
signature) == _verifier, "verification failure");
_credit.burn(msg.sender, cost);
_metadataKeys[token][key] = id;
}
| 348,859
|
./full_match/137/0x7eF94f51a5355456e498d7643967D63e766eFcE2/sources/DMTNFT.sol
|
Private function to add a token to this extension's ownership-tracking data structures. to address representing the new owner of the given token ID tokenId uint256 ID of the token to be added to the tokens list of the given address/
|
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = balanceOf(to);
_ownedTokens[to][length] = tokenId;
ownedTokensIndex[tokenId] = length;
}
| 4,685,894
|
./full_match/1/0x2ae6a6088bD5535Fd7c4C3BaF093d06bA2a89e52/sources/contracts/STT.sol
|
it will update spawn price _spawnPrice is new value for spawn/
|
function setSpawnPrice(uint256 _spawnPrice) external onlyOwner {
spawnPrice = _spawnPrice;
}
| 17,005,729
|
// File: @trusttoken/trusttokens/contracts/Proxy/OwnedUpgradeabilityProxy.sol
pragma solidity 0.5.13;
/**
* @title OwnedUpgradeabilityProxy
* @dev This contract combines an upgradeability proxy with basic authorization control functionalities
*/
contract OwnedUpgradeabilityProxy {
/**
* @dev Event to show ownership has been transferred
* @param previousOwner representing the address of the previous owner
* @param newOwner representing the address of the new owner
*/
event ProxyOwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Event to show ownership transfer is pending
* @param currentOwner representing the address of the current owner
* @param pendingOwner representing the address of the pending owner
*/
event NewPendingOwner(address currentOwner, address pendingOwner);
// Storage position of the owner and pendingOwner of the contract
bytes32 private constant proxyOwnerPosition = 0x6279e8199720cf3557ecd8b58d667c8edc486bd1cf3ad59ea9ebdfcae0d0dfac;//keccak256("trueUSD.proxy.owner");
bytes32 private constant pendingProxyOwnerPosition = 0x8ddbac328deee8d986ec3a7b933a196f96986cb4ee030d86cc56431c728b83f4;//keccak256("trueUSD.pending.proxy.owner");
/**
* @dev the constructor sets the original owner of the contract to the sender account.
*/
constructor() public {
_setUpgradeabilityOwner(msg.sender);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyProxyOwner() {
require(msg.sender == proxyOwner(), "only Proxy Owner");
_;
}
/**
* @dev Throws if called by any account other than the pending owner.
*/
modifier onlyPendingProxyOwner() {
require(msg.sender == pendingProxyOwner(), "only pending Proxy Owner");
_;
}
/**
* @dev Tells the address of the owner
* @return the address of the owner
*/
function proxyOwner() public view returns (address owner) {
bytes32 position = proxyOwnerPosition;
assembly {
owner := sload(position)
}
}
/**
* @dev Tells the address of the owner
* @return the address of the owner
*/
function pendingProxyOwner() public view returns (address pendingOwner) {
bytes32 position = pendingProxyOwnerPosition;
assembly {
pendingOwner := sload(position)
}
}
/**
* @dev Sets the address of the owner
*/
function _setUpgradeabilityOwner(address newProxyOwner) internal {
bytes32 position = proxyOwnerPosition;
assembly {
sstore(position, newProxyOwner)
}
}
/**
* @dev Sets the address of the owner
*/
function _setPendingUpgradeabilityOwner(address newPendingProxyOwner) internal {
bytes32 position = pendingProxyOwnerPosition;
assembly {
sstore(position, newPendingProxyOwner)
}
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
*changes the pending owner to newOwner. But doesn't actually transfer
* @param newOwner The address to transfer ownership to.
*/
function transferProxyOwnership(address newOwner) external onlyProxyOwner {
require(newOwner != address(0));
_setPendingUpgradeabilityOwner(newOwner);
emit NewPendingOwner(proxyOwner(), newOwner);
}
/**
* @dev Allows the pendingOwner to claim ownership of the proxy
*/
function claimProxyOwnership() external onlyPendingProxyOwner {
emit ProxyOwnershipTransferred(proxyOwner(), pendingProxyOwner());
_setUpgradeabilityOwner(pendingProxyOwner());
_setPendingUpgradeabilityOwner(address(0));
}
/**
* @dev Allows the proxy owner to upgrade the current version of the proxy.
* @param implementation representing the address of the new implementation to be set.
*/
function upgradeTo(address implementation) public onlyProxyOwner {
address currentImplementation;
bytes32 position = implementationPosition;
assembly {
currentImplementation := sload(position)
}
require(currentImplementation != implementation);
assembly {
sstore(position, implementation)
}
emit Upgraded(implementation);
}
/**
* @dev This event will be emitted every time the implementation gets upgraded
* @param implementation representing the address of the upgraded implementation
*/
event Upgraded(address indexed implementation);
// Storage position of the address of the current implementation
bytes32 private constant implementationPosition = 0x6e41e0fbe643dfdb6043698bf865aada82dc46b953f754a3468eaa272a362dc7; //keccak256("trueUSD.proxy.implementation");
function implementation() public view returns (address impl) {
bytes32 position = implementationPosition;
assembly {
impl := sload(position)
}
}
/**
* @dev Fallback function allowing to perform a delegatecall to the given implementation.
* This function will return whatever the implementation call returns
*/
function() external payable {
bytes32 position = implementationPosition;
assembly {
let ptr := mload(0x40)
calldatacopy(ptr, returndatasize, calldatasize)
let result := delegatecall(gas, sload(position), ptr, calldatasize, returndatasize, returndatasize)
returndatacopy(ptr, 0, returndatasize)
switch result
case 0 { revert(ptr, returndatasize) }
default { return(ptr, returndatasize) }
}
}
}
// File: @trusttoken/trusttokens/contracts/Proxy/TimeOwnedUpgradeabilityProxy.sol
pragma solidity 0.5.13;
/**
* @title TimeOwnedUpgradeabilityProxy
* @dev This contract combines an upgradeability proxy with
* basic authorization control functionalities
*
* This contract allows us to specify a time at which the proxy can no longer
* be upgraded
*/
contract TimeOwnedUpgradeabilityProxy is OwnedUpgradeabilityProxy {
bytes32 private constant expirationPosition = bytes32(uint256(keccak256('trusttoken.expiration')) - 1);
/**
* @dev the constructor sets the original owner of the contract to the sender account.
*/
constructor() public {
_setUpgradeabilityOwner(msg.sender);
// set expiration to ~4 months from now
_setExpiration(block.timestamp + 124 days);
}
/**
* @dev sets new expiration time
*/
function setExpiration(uint256 newExpirationTime) external onlyProxyOwner {
require(block.timestamp < expiration(), "after expiration time");
require(block.timestamp < newExpirationTime, "new expiration time must be in the future");
_setExpiration(newExpirationTime);
}
function _setExpiration(uint256 newExpirationTime) internal onlyProxyOwner {
bytes32 position = expirationPosition;
assembly {
sstore(position, newExpirationTime)
}
}
function expiration() public view returns (uint256 _expiration) {
bytes32 position = expirationPosition;
assembly {
_expiration := sload(position)
}
}
/**
* @dev Allows the proxy owner to upgrade the current version of the proxy.
* @param implementation representing the address of the new implementation to be set.
*/
function upgradeTo(address implementation) public onlyProxyOwner {
require(block.timestamp < expiration(), "after expiration date");
super.upgradeTo(implementation);
}
}
|
Allows the proxy owner to upgrade the current version of the proxy. implementation representing the address of the new implementation to be set./
|
function upgradeTo(address implementation) public onlyProxyOwner {
address currentImplementation;
bytes32 position = implementationPosition;
assembly {
currentImplementation := sload(position)
}
require(currentImplementation != implementation);
assembly {
sstore(position, implementation)
}
emit Upgraded(implementation);
}
| 13,114,053
|
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./FantomMintErrorCodes.sol";
import "./FantomCollateralStorage.sol";
import "./FantomDebtStorage.sol";
import "./FantomMintRewardManager.sol";
// FantomMintCore implements a balance pool of collateral and debt tokens
// for the related Fantom DeFi contract. The collateral part allows notified rewards
// distribution to eligible collateral accounts.
contract FantomMintCore is
Ownable,
ReentrancyGuard,
FantomMintErrorCodes,
FantomCollateralStorage,
FantomDebtStorage,
FantomMintRewardManager
{
// define used libs
using SafeMath for uint256;
using Address for address;
using SafeERC20 for ERC20;
// -------------------------------------------------------------
// Price and value calculation related constants
// -------------------------------------------------------------
// collateralLowestDebtRatio4dec represents the lowest ratio between
// collateral value and debt value allowed for the user.
// User can not withdraw his collateral if the active ratio would
// drop below this value.
// The value is returned in 4 decimals, e.g. value 30000 = 3.0
uint256 public constant collateralLowestDebtRatio4dec = 30000;
// collateralRatioDecimalsCorrection represents the value to be used
// to adjust result decimals after applying ratio to a value calculation.
uint256 public constant collateralRatioDecimalsCorrection = 10000;
// -------------------------------------------------------------
// Emitted events definition
// -------------------------------------------------------------
// Deposited is emitted on token received to deposit
// increasing user's collateral value.
event Deposited(address indexed token, address indexed user, uint256 amount);
// Withdrawn is emitted on confirmed token withdraw
// from the deposit decreasing user's collateral value.
event Withdrawn(address indexed token, address indexed user, uint256 amount);
// -------------------------------------------------------------
// Token value related functions
// -------------------------------------------------------------
// getPrice (abstract) returns the price of given ERC20 token using on-chain oracle
// expression of an exchange rate between the token and base denomination.
function getPrice(address _token) public view returns (uint256);
// getPriceDigitsCorrection (abstract) returns the correction to the calculated
// ERC20 token value to correct exchange rate digits correction.
function getPriceDigitsCorrection() public pure returns (uint256);
// tokenValue calculates the value of the given amount of the token specified.
// The value is returned in given referential tokens (fUSD).
// Implements tokenValue() abstract function of the underlying storage contracts.
function tokenValue(address _token, uint256 _amount) public view returns (uint256) {
// calculate the value using price Oracle access
return _amount.mul(getPrice(_token)).div(getPriceDigitsCorrection());
}
// -------------------------------------------------------------
// Collateral to debt ratio checks below
// -------------------------------------------------------------
// isCollateralSufficient checks if collateral value is sufficient
// to cover the debt (collateral to debt ratio) after
// predefined adjustments to the collateral and debt values.
function isCollateralSufficient(address _account, uint256 subCollateral, uint256 addDebt, uint256 ratio) internal view returns (bool) {
// calculate the collateral and debt values in ref. denomination
// for the current exchange rate and balance amounts including
// given adjustments to both values as requested.
uint256 cDebtValue = debtValueOf(_account).add(addDebt);
uint256 cCollateralValue = collateralValueOf(_account).sub(subCollateral);
// minCollateralValue is the minimal collateral value required for the current debt
// to be within the minimal allowed collateral to debt ratio
uint256 minCollateralValue = cDebtValue
.mul(ratio)
.div(collateralRatioDecimalsCorrection);
// final collateral value must match the minimal value or exceed it
return (cCollateralValue >= minCollateralValue);
}
// collateralCanDecrease checks if the specified amount of collateral can be removed from account
// without breaking collateral to debt ratio rule.
function collateralCanDecrease(address _account, address _token, uint256 _amount) public view returns (bool) {
// collateral to debt ratio must be valid after collateral decrease
return isCollateralSufficient(_account, tokenValue(_token, _amount), 0, collateralLowestDebtRatio4dec);
}
// debtCanIncrease checks if the specified amount of debt can be added to the account
// without breaking collateral to debt ratio rule.
function debtCanIncrease(address _account, address _token, uint256 _amount) public view returns (bool) {
// collateral to debt ratio must be valid after debt increase
return isCollateralSufficient(_account, 0, tokenValue(_token, _amount), collateralLowestDebtRatio4dec);
}
// rewardCanClaim checks if the account can claim accumulated rewards
// by being on a high enough collateral to debt ratio.
// Implements abstract function of the <FantomMintRewardManager>.
function rewardCanClaim(address _account) public view returns (bool) {
return isCollateralSufficient(_account, 0, 0, collateralLowestDebtRatio4dec);
}
// rewardIsEligible checks if the account is eligible to receive any reward.
function rewardIsEligible(address _account) internal view returns (bool) {
return isCollateralSufficient(_account, 0, 0, rewardEligibilityRatio4dec);
}
// --------------------------------------------------------------------------
// Principal balance calculations used by the reward manager to yield rewards
// --------------------------------------------------------------------------
// principalBalance returns the total balance of principal token
// which yield a reward to entitled participants based
// on their individual principal share.
function principalBalance() public view returns (uint256) {
return debtTotal();
}
// principalBalanceOf returns the balance of principal token
// which yield a reward share for this account.
function principalBalanceOf(address _account) public view returns (uint256) {
return debtValueOf(_account);
}
// -------------------------------------------------------------
// Collateral management functions below
// -------------------------------------------------------------
// deposit receives assets to build up the collateral value.
// The collateral can be used later to mint tokens inside fMint module.
// The call does not subtract any fee. No interest is granted on deposit.
function deposit(address _token, uint256 _amount) public nonReentrant returns (uint256)
{
// make sure a non-zero value is being deposited
if (_amount == 0) {
return ERR_ZERO_AMOUNT;
}
// make sure caller has enough balance to cover the deposit
if (_amount > ERC20(_token).balanceOf(msg.sender)) {
return ERR_LOW_BALANCE;
}
// make sure we are allowed to transfer funds from the caller
// to the fMint deposit pool
if (_amount > ERC20(_token).allowance(msg.sender, address(this))) {
return ERR_LOW_ALLOWANCE;
}
// make sure the token has a value before we accept it as a collateral
if (getPrice(_token) == 0) {
return ERR_NO_VALUE;
}
// transfer ERC20 tokens from account to the collateral pool
ERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
// update the reward distribution for the account before the state changes
rewardUpdate(msg.sender);
// add the collateral to the account
collateralAdd(msg.sender, _token, _amount);
// emit the event signaling a successful deposit
emit Deposited(_token, msg.sender, _amount);
// deposit successful
return ERR_NO_ERROR;
}
// withdraw subtracts any deposited collateral token from the contract.
// The remaining collateral value is compared to the minimal required
// collateral to debt ratio and the transfer is rejected
// if the ratio is lower than the enforced one.
function withdraw(address _token, uint256 _amount) public nonReentrant returns (uint256) {
// make sure a non-zero value is being withdrawn
if (_amount == 0) {
return ERR_ZERO_AMOUNT;
}
// make sure the withdraw does not exceed collateral balance
if (_amount > collateralBalance[msg.sender][_token]) {
return ERR_LOW_BALANCE;
}
// does the new state obey the enforced minimal collateral to debt ratio?
// if the check fails, the collateral withdraw is rejected
if (!collateralCanDecrease(msg.sender, _token, _amount)) {
return ERR_LOW_COLLATERAL_RATIO;
}
// update the reward distribution for the account before state changes
rewardUpdate(msg.sender);
// remove the collateral from account
collateralSub(msg.sender, _token, _amount);
// transfer withdrawn ERC20 tokens to the caller
ERC20(_token).safeTransfer(msg.sender, _amount);
// signal the successful asset withdrawal
emit Withdrawn(_token, msg.sender, _amount);
// withdraw successful
return ERR_NO_ERROR;
}
}
|
withdraw subtracts any deposited collateral token from the contract. The remaining collateral value is compared to the minimal required collateral to debt ratio and the transfer is rejected if the ratio is lower than the enforced one. make sure a non-zero value is being withdrawn make sure the withdraw does not exceed collateral balance does the new state obey the enforced minimal collateral to debt ratio? if the check fails, the collateral withdraw is rejected
|
function withdraw(address _token, uint256 _amount) public nonReentrant returns (uint256) {
if (_amount == 0) {
return ERR_ZERO_AMOUNT;
}
if (_amount > collateralBalance[msg.sender][_token]) {
return ERR_LOW_BALANCE;
}
if (!collateralCanDecrease(msg.sender, _token, _amount)) {
return ERR_LOW_COLLATERAL_RATIO;
}
}
| 7,266,749
|
pragma solidity ^0.5.7;
// Send more than WEI_MIN (init = 1 ETH) for 1002 Wesions, and get unused ETH refund automatically.
// Use the current Wesion price of Wesion Public-Sale.
//
// Conditions:
// 1. You have no Wesion yet.
// 2. You are not in the whitelist yet.
// 3. Send more than 1 ETH (for balance verification).
//
/**
* @title SafeMath for uint256
* @dev Unsigned math operations with safety checks that revert on error.
*/
library SafeMath256 {
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
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) {
assert(b <= a);
return a - b;
}
/**
* @dev Multiplies two unsigned integers, reverts 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 unsigned integers truncating the quotient,
* reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b > 0);
uint256 c = a / b;
assert(a == b * c + a % b);
return a / b;
}
/**
* @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 Ownable
*/
contract Ownable {
address private _owner;
address payable internal _receiver;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event ReceiverChanged(address indexed previousReceiver, address indexed newReceiver);
/**
* @dev The Ownable constructor sets the original `owner` of the contract
* to the sender account.
*/
constructor () internal {
_owner = msg.sender;
_receiver = msg.sender;
}
/**
* @return The address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(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) external onlyOwner {
require(newOwner != address(0));
address __previousOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(__previousOwner, newOwner);
}
/**
* @dev Change receiver.
*/
function changeReceiver(address payable newReceiver) external onlyOwner {
require(newReceiver != address(0));
address __previousReceiver = _receiver;
_receiver = newReceiver;
emit ReceiverChanged(__previousReceiver, newReceiver);
}
/**
* @dev Rescue compatible ERC20 Token
*
* @param tokenAddr ERC20 The address of the ERC20 token contract
* @param receiver The address of the receiver
* @param amount uint256
*/
function rescueTokens(address tokenAddr, address receiver, uint256 amount) external onlyOwner {
IERC20 _token = IERC20(tokenAddr);
require(receiver != address(0));
uint256 balance = _token.balanceOf(address(this));
require(balance >= amount);
assert(_token.transfer(receiver, amount));
}
/**
* @dev Withdraw ether
*/
function withdrawEther(address payable to, uint256 amount) external onlyOwner {
require(to != address(0));
uint256 balance = address(this).balance;
require(balance >= amount);
to.transfer(amount);
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
bool private _paused;
event Paused(address account);
event Unpaused(address account);
constructor () internal {
_paused = false;
}
/**
* @return Returns true if the contract is paused, false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Paused.");
_;
}
/**
* @dev Called by a pauser to pause, triggers stopped state.
*/
function setPaused(bool state) external onlyOwner {
if (_paused && !state) {
_paused = false;
emit Unpaused(msg.sender);
} else if (!_paused && state) {
_paused = true;
emit Paused(msg.sender);
}
}
}
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
function balanceOf(address owner) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
}
/**
* @title Wesion interface
*/
interface IWesion {
function balanceOf(address owner) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function inWhitelist(address account) external view returns (bool);
}
/**
* @title Wesion Public-Sale interface
*/
interface IWesionPublicSale {
function status() external view returns (uint256 auditEtherPrice,
uint16 stage,
uint16 season,
uint256 WesionUsdPrice,
uint256 currentTopSalesRatio,
uint256 txs,
uint256 WesionTxs,
uint256 WesionBonusTxs,
uint256 WesionWhitelistTxs,
uint256 WesionIssued,
uint256 WesionBonus,
uint256 WesionWhitelist);
}
/**
* @title Get 1002 Wesion
*/
contract Get1002Wesion is Ownable, Pausable {
using SafeMath256 for uint256;
IWesion public Wesion = IWesion(0x2c1564A74F07757765642ACef62a583B38d5A213);
IWesionPublicSale public Wesion_PUBLIC_SALE;
uint256 public WEI_MIN = 1 ether;
uint256 private Wesion_PER_TXN = 1002000000; // 1002.000000 Wesion
uint256 private _txs;
mapping (address => bool) _alreadyGot;
event Tx(uint256 etherPrice, uint256 vokdnUsdPrice, uint256 weiUsed);
/**
* @dev Transaction counter
*/
function txs() public view returns (uint256) {
return _txs;
}
function setWeiMin(uint256 weiMin) public onlyOwner {
WEI_MIN = weiMin;
}
/**
* @dev Get 1002 Wesion and ETH refund.
*/
function () external payable whenNotPaused { //inject DOS BY COMPLEX FALLBACK
require(msg.value >= WEI_MIN);
require(Wesion.balanceOf(address(this)) >= Wesion_PER_TXN);
require(Wesion.balanceOf(msg.sender) == 0);
require(!Wesion.inWhitelist(msg.sender));
require(!_alreadyGot[msg.sender]);
uint256 __etherPrice;
uint256 __WesionUsdPrice;
(__etherPrice, , , __WesionUsdPrice, , , , , , , ,) = Wesion_PUBLIC_SALE.status();
require(__etherPrice > 0);
uint256 __usd = Wesion_PER_TXN.mul(__WesionUsdPrice).div(1000000);
uint256 __wei = __usd.mul(1 ether).div(__etherPrice);
require(msg.value >= __wei);
if (msg.value > __wei) {
msg.sender.call.gas(2301).value(msg.value.sub(__wei))("");
_receiver.call.gas(2301).value(__wei)("");
}
_txs = _txs.add(1);
_alreadyGot[msg.sender] = true;
emit Tx(__etherPrice, __WesionUsdPrice, __wei);
assert(Wesion.transfer(msg.sender, Wesion_PER_TXN));
}
/**
* @dev set Public Sale Address
*/
function setPublicSaleAddress(address _pubSaleAddr) public onlyOwner {
Wesion_PUBLIC_SALE = IWesionPublicSale(_pubSaleAddr);
}
/**
* @dev set Wesion Address
*/
function setWesionAddress(address _WesionAddr) public onlyOwner {
Wesion = IWesion(_WesionAddr);
}
}
|
Change receiver./
|
function changeReceiver(address payable newReceiver) external onlyOwner {
require(newReceiver != address(0));
address __previousReceiver = _receiver;
_receiver = newReceiver;
emit ReceiverChanged(__previousReceiver, newReceiver);
}
| 2,549,340
|
pragma solidity 0.8.4;
// SPDX-License-Identifier: MIT
// File @openzeppelin/contracts/utils/Context.sol@v4.3.2
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract 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/access/Ownable.sol@v4.3.2
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), 'Ownable: caller is not the owner');
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), 'Ownable: new owner is the zero address');
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File @openzeppelin/contracts/token/ERC20/IERC20.sol@v4.3.2
/**
* @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/utils/Address.sol@v4.3.2
/**
* @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/token/ERC20/utils/SafeERC20.sol@v4.3.2
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library 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');
}
}
}
// File @uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol@v1.0.1
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 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 (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 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 (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
event Mint(address indexed sender, uint256 amount0, uint256 amount1);
event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to);
event Swap(
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint256);
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 (uint256);
function price1CumulativeLast() external view returns (uint256);
function kLast() external view returns (uint256);
function mint(address to) external returns (uint256 liquidity);
function burn(address to) external returns (uint256 amount0, uint256 amount1);
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// File @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol@v1.1.0-beta.0
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts);
}
// File @chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol@v0.2.2
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
);
}
// File contracts/PaymentPortal.sol
contract PaymentPortal is Ownable {
using SafeERC20 for IERC20;
uint256 private constant HUNDRED_PERCENT = 1000;
uint256 private constant UNISWAP_FEE = HUNDRED_PERCENT - 3; // 0.3%
uint256 private subscriptionDuration = 30 days; // in seconds
// All payments will be sent to this address
address private paymentReceiverA;
address private paymentReceiverB;
uint256 private paymentShareA = HUNDRED_PERCENT;
IERC20 private immutable albtToken;
IERC20 private immutable usdtToken;
address private immutable uniswapRouter;
uint256 private priceWithALBT;
uint256 private priceWithUSDT;
uint256 private maxSlippage = (HUNDRED_PERCENT * 5) / 100; // 5%
// Whitelisted addresses
mapping(address => bool) private whitelist;
// Stores the timestamp until which each address has access
mapping(address => uint256) private access;
// Chainlink price feed aggregator
AggregatorV3Interface private immutable priceFeed;
constructor(
address _paymentReceiverA, // required
address _paymentReceiverB, // optional, but _paymentShareA must be 1000
uint256 _paymentShareA, // what percentage of payments will go to payment receiver address A (1000 = 100%)
address _albtToken, // address of the ALBT token
address _usdtToken, // address of the USDT token
address _uniswapRouter, // address of the uniswap router
uint256 _priceWithALBT, // price in USDT when paying with ALBT (USDT uses 6 decimals)
uint256 _priceWithUSDT, // price in USDT when paying with USDT (USDT uses 6 decimals)
address _priceFeed // address of the price feed
) {
_setPaymentReceivers(_paymentReceiverA, _paymentReceiverB);
_setPaymentShareA(_paymentShareA);
require(_uniswapRouter != address(0), 'PaymentPortal: Uniswap router address cannot be 0');
uniswapRouter = _uniswapRouter;
require(_albtToken != address(0), 'PaymentPortal: ALBT token address cannot be 0');
require(_usdtToken != address(0), 'PaymentPortal: USDT token address cannot be 0');
albtToken = IERC20(_albtToken);
usdtToken = IERC20(_usdtToken);
require(_priceWithALBT < _priceWithUSDT, 'PaymentPortal: Price with ALBT must be less than price with USDT');
priceWithALBT = _priceWithALBT;
priceWithUSDT = _priceWithUSDT;
require(_priceFeed != address(0), 'PaymentPortal: Price feed address cannot be 0');
priceFeed = AggregatorV3Interface(_priceFeed);
}
function getPaymentReceivers() public view returns (address, address) {
return (paymentReceiverA, paymentReceiverB);
}
function _setPaymentReceivers(address _paymentReceiverA, address _paymentReceiverB) internal {
require(_paymentReceiverA != address(0), 'PaymentPortal: Payment receiver A must be set');
require(
paymentShareA == HUNDRED_PERCENT || _paymentReceiverB != address(0),
'PaymentPortal: If payment is shared, payment receiver B must be set'
);
paymentReceiverA = _paymentReceiverA;
paymentReceiverB = _paymentReceiverB;
}
function setPaymentReceivers(address _paymentReceiverA, address _paymentReceiverB) public onlyOwner {
_setPaymentReceivers(_paymentReceiverA, _paymentReceiverB);
}
function getPaymentShareA() public view returns (uint256) {
return paymentShareA;
}
function _setPaymentShareA(uint256 _paymentShareA) internal {
require(
_paymentShareA == HUNDRED_PERCENT || paymentReceiverB != address(0),
'PaymentPortal: If payment is shared, payment receiver B must be set'
);
require(_paymentShareA <= HUNDRED_PERCENT, 'PaymentPortal: Payment share must be between 0% and 100%');
paymentShareA = _paymentShareA;
}
function setPaymentShareA(uint256 _paymentShareA) public onlyOwner {
_setPaymentShareA(_paymentShareA);
}
function setPriceWithALBT(uint256 _priceWithALBT) public onlyOwner {
require(_priceWithALBT < priceWithUSDT, 'PaymentPortal: Price with ALBT must be less than price with USDT');
priceWithALBT = _priceWithALBT;
}
function setPriceWithUSDT(uint256 _priceWithUSDT) public onlyOwner {
require(priceWithALBT < _priceWithUSDT, 'PaymentPortal: Price with ALBT must be less than price with USDT');
priceWithUSDT = _priceWithUSDT;
}
function getMaxSlippage() public view returns (uint256) {
return maxSlippage;
}
// Max slippage is a percentage, 10 = 1%, 55 = 5.5%
function setMaxSlippage(uint256 _maxSlippage) public onlyOwner {
require(_maxSlippage <= HUNDRED_PERCENT, 'PaymentPortal: Max slippage must be between 0% and 100%');
maxSlippage = _maxSlippage;
}
function getSubscriptionDuration() public view returns (uint256) {
return subscriptionDuration;
}
function setSubscriptionDuration(uint256 _subscriptionDuration) public onlyOwner {
require(_subscriptionDuration >= 1 weeks, 'PaymentPortal: Subscription duration must be at least 1 week');
subscriptionDuration = _subscriptionDuration;
}
function addToWhitelist(address _wallet) public onlyOwner {
whitelist[_wallet] = true;
}
function removeFromWhitelist(address _wallet) public onlyOwner {
whitelist[_wallet] = false;
}
function isWhitelisted(address _wallet) public view returns (bool) {
return whitelist[_wallet];
}
// Returns the timestamp until which the wallet has access
function accessTimestamp(address _wallet) public view returns (uint256) {
return access[_wallet];
}
// Checks if the wallet has access, either via the whitelist or by a payment which is still not expired
function hasAccess(address _wallet) public view returns (bool) {
return whitelist[_wallet] || access[_wallet] > block.timestamp;
}
// Returns the amount of ALBT you need to pay when paying with ALBT, calculated from a discounted USDT rate
function getPriceInALBT() public view returns (uint256) {
return calculateUSDTtoALBT(priceWithALBT);
}
// Returns the amount of USDT you have to pay when paying with USDT
function getPriceInUSDT() public view returns (uint256) {
return priceWithUSDT;
}
// When you pay with ALBT the tokens are transfered directly
function payALBT(address walletToGiveAccess, uint256 maxALBTPayment) public {
require(!hasAccess(walletToGiveAccess), 'PaymentPortal: Already has access');
uint256 albtAmount = calculateUSDTtoALBT(priceWithALBT);
// Needed because USDT or chainlink price can change at any moment
require(albtAmount <= maxALBTPayment, 'PaymentPortal: Price exceeds max payment');
transferPayment(msg.sender, albtAmount);
access[walletToGiveAccess] = block.timestamp + subscriptionDuration;
}
// When you pay with USDT the tokens are transfered to this contract, then swapped to ALBT, and then transfered
function payUSDT(address walletToGiveAccess, uint256 maxUSDTPayment) public {
require(!hasAccess(walletToGiveAccess), 'PaymentPortal: Already has access');
// Needed because price can be changed at any moment, this way user can determine how much he's willing to pay
require(priceWithUSDT <= maxUSDTPayment, 'PaymentPortal: Price exceeds max payment');
usdtToken.safeTransferFrom(msg.sender, address(this), priceWithUSDT);
// Expected amount of ALBT to get back, used to calculate slippage
uint256 albtAmount = calculateUSDTtoALBT(priceWithUSDT);
address[] memory route = new address[](2);
route[0] = address(usdtToken);
route[1] = address(albtToken);
usdtToken.safeApprove(uniswapRouter, priceWithUSDT);
uint256[] memory amounts = IUniswapV2Router01(uniswapRouter).swapExactTokensForTokens(
priceWithUSDT,
(albtAmount * (HUNDRED_PERCENT - maxSlippage)) / HUNDRED_PERCENT, // max % slippage
route,
address(this),
block.timestamp
);
uint256 exactALBTAmount = amounts[amounts.length - 1];
transferPayment(address(this), exactALBTAmount);
access[walletToGiveAccess] = block.timestamp + subscriptionDuration;
}
// Splits the payment among address A and B based on the share
function transferPayment(address _from, uint256 _amount) internal {
uint256 amountA = (_amount * paymentShareA) / HUNDRED_PERCENT;
uint256 amountB = _amount - amountA;
if (_from == address(this)) {
if (amountA > 0) {
albtToken.safeTransfer(paymentReceiverA, amountA);
}
if (amountB > 0) {
albtToken.safeTransfer(paymentReceiverB, amountB);
}
} else {
if (amountA > 0) {
albtToken.safeTransferFrom(_from, paymentReceiverA, amountA);
}
if (amountB > 0) {
albtToken.safeTransferFrom(_from, paymentReceiverB, amountB);
}
}
}
// Calculate the amount of ALBT you will get for an amount of USDT, using the chainlink price feed
function calculateUSDTtoALBT(uint256 _usdtAmount) internal view returns (uint256) {
uint8 decimals = priceFeed.decimals();
(, int256 price, , , ) = priceFeed.latestRoundData();
// Because we need the price in ALBT decimals, we need to multiply by 10^12 (USDT uses 6 decimals, ALBT uses 18)
uint256 amountWithoutFees = (_usdtAmount * (10**decimals) * (10**12)) / uint256(price);
// Uniswap has a 0.3% fee
return (amountWithoutFees * UNISWAP_FEE) / HUNDRED_PERCENT;
}
}
|
Max slippage is a percentage, 10 = 1%, 55 = 5.5%
|
function setMaxSlippage(uint256 _maxSlippage) public onlyOwner {
require(_maxSlippage <= HUNDRED_PERCENT, 'PaymentPortal: Max slippage must be between 0% and 100%');
maxSlippage = _maxSlippage;
}
| 13,823,677
|
// 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 "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
uint256[45] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./draft-IERC20PermitUpgradeable.sol";
import "../ERC20Upgradeable.sol";
import "../../../utils/cryptography/draft-EIP712Upgradeable.sol";
import "../../../utils/cryptography/ECDSAUpgradeable.sol";
import "../../../utils/CountersUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*/
abstract contract ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IERC20PermitUpgradeable, EIP712Upgradeable {
using CountersUpgradeable for CountersUpgradeable.Counter;
mapping(address => CountersUpgradeable.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private _PERMIT_TYPEHASH;
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
function __ERC20Permit_init(string memory name) internal initializer {
__Context_init_unchained();
__EIP712_init_unchained(name, "1");
__ERC20Permit_init_unchained(name);
}
function __ERC20Permit_init_unchained(string memory name) internal initializer {
_PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSAUpgradeable.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view virtual override returns (uint256) {
return _nonces[owner].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
/**
* @dev "Consume a nonce": return the current value and increment.
*
* _Available since v4.1._
*/
function _useNonce(address owner) internal virtual returns (uint256 current) {
CountersUpgradeable.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20PermitUpgradeable {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.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: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library CountersUpgradeable {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// 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 ECDSAUpgradeable {
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 "./ECDSAUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712Upgradeable is Initializable {
/* solhint-disable var-name-mixedcase */
bytes32 private _HASHED_NAME;
bytes32 private _HASHED_VERSION;
bytes32 private constant _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
function __EIP712_init(string memory name, string memory version) internal initializer {
__EIP712_init_unchained(name, version);
}
function __EIP712_init_unchained(string memory name, string memory version) internal initializer {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash());
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSAUpgradeable.toTypedDataHash(_domainSeparatorV4(), structHash);
}
/**
* @dev The hash of the name parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712NameHash() internal virtual view returns (bytes32) {
return _HASHED_NAME;
}
/**
* @dev The hash of the version parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712VersionHash() internal virtual view returns (bytes32) {
return _HASHED_VERSION;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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: GPL-3.0
pragma solidity ^0.8.7;
import "../interfaces/IAgToken.sol";
import "../interfaces/IStableMaster.sol";
// OpenZeppelin may update its version of the ERC20PermitUpgradeable token
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/draft-ERC20PermitUpgradeable.sol";
/// @title AgToken
/// @author Angle Core Team
/// @notice Base contract for agToken, that is to say Angle's stablecoins
/// @dev This contract is used to create and handle the stablecoins of Angle protocol
/// @dev Only the `StableMaster` contract can mint or burn agTokens
/// @dev It is still possible for any address to burn its agTokens without redeeming collateral in exchange
contract AgToken is IAgToken, ERC20PermitUpgradeable {
// ========================= References to other contracts =====================
/// @notice Reference to the `StableMaster` contract associated to this `AgToken`
address public override stableMaster;
// ============================= Constructor ===================================
/// @notice Initializes the `AgToken` contract
/// @param name_ Name of the token
/// @param symbol_ Symbol of the token
/// @param stableMaster_ Reference to the `StableMaster` contract associated to this agToken
/// @dev By default, agTokens are ERC-20 tokens with 18 decimals
function initialize(
string memory name_,
string memory symbol_,
address stableMaster_
) external initializer {
__ERC20Permit_init(name_);
__ERC20_init(name_, symbol_);
require(stableMaster_ != address(0), "0");
stableMaster = stableMaster_;
}
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() initializer {}
/// @notice Checks to see if it is the `StableMaster` calling this contract
/// @dev There is no Access Control here, because it can be handled cheaply through this modifier
modifier onlyStableMaster() {
require(msg.sender == stableMaster, "1");
_;
}
// ========================= External Functions ================================
// The following functions allow anyone to burn stablecoins without redeeming collateral
// in exchange for that
/// @notice Destroys `amount` token from the caller without giving collateral back
/// @param amount Amount to burn
/// @param poolManager Reference to the `PoolManager` contract for which the `stocksUsers` will
/// need to be updated
/// @dev When calling this function, people should specify the `poolManager` for which they want to decrease
/// the `stocksUsers`: this a way for the protocol to maintain healthy accounting variables
/// @dev This function is for instance to be used by governance to burn the tokens accumulated by the `BondingCurve`
/// contract
function burnNoRedeem(uint256 amount, address poolManager) external {
_burn(msg.sender, amount);
IStableMaster(stableMaster).updateStocksUsers(amount, poolManager);
}
/// @notice Burns `amount` of agToken on behalf of another account without redeeming collateral back
/// @param account Account to burn on behalf of
/// @param amount Amount to burn
/// @param poolManager Reference to the `PoolManager` contract for which the `stocksUsers` will need to be updated
function burnFromNoRedeem(
address account,
uint256 amount,
address poolManager
) external {
_burnFromNoRedeem(amount, account, msg.sender);
IStableMaster(stableMaster).updateStocksUsers(amount, poolManager);
}
// ========================= `StableMaster` Functions ==========================
/// @notice Burns `amount` tokens from a `burner` address
/// @param amount Amount of tokens to burn
/// @param burner Address to burn from
/// @dev This method is to be called by the `StableMaster` contract after being requested to do so
/// by an address willing to burn tokens from its address
function burnSelf(uint256 amount, address burner) external override onlyStableMaster {
_burn(burner, amount);
}
/// @notice Burns `amount` tokens from a `burner` address after being asked to by `sender`
/// @param amount Amount of tokens to burn
/// @param burner Address to burn from
/// @param sender Address which requested the burn from `burner`
/// @dev This method is to be called by the `StableMaster` contract after being requested to do so
/// by a `sender` address willing to burn tokens from another `burner` address
/// @dev The method checks the allowance between the `sender` and the `burner`
function burnFrom(
uint256 amount,
address burner,
address sender
) external override onlyStableMaster {
_burnFromNoRedeem(amount, burner, sender);
}
/// @notice Lets the `StableMaster` contract mint agTokens
/// @param account Address to mint to
/// @param amount Amount to mint
/// @dev Only the `StableMaster` contract can issue agTokens
function mint(address account, uint256 amount) external override onlyStableMaster {
_mint(account, amount);
}
// ============================ Internal Function ==============================
/// @notice Internal version of the function `burnFromNoRedeem`
/// @param amount Amount to burn
/// @dev It is at the level of this function that allowance checks are performed
function _burnFromNoRedeem(
uint256 amount,
address burner,
address sender
) internal {
uint256 currentAllowance = allowance(burner, sender);
require(currentAllowance >= amount, "23");
_approve(burner, sender, currentAllowance - amount);
_burn(burner, amount);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
/// @title IAccessControl
/// @author Forked from OpenZeppelin
/// @notice Interface for `AccessControl` contracts
interface IAccessControl {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
/// @title IAgToken
/// @author Angle Core Team
/// @notice Interface for the stablecoins `AgToken` contracts
/// @dev The only functions that are left in the interface are the functions which are used
/// at another point in the protocol by a different contract
interface IAgToken is IERC20Upgradeable {
// ======================= `StableMaster` functions ============================
function mint(address account, uint256 amount) external;
function burnFrom(
uint256 amount,
address burner,
address sender
) external;
function burnSelf(uint256 amount, address burner) external;
// ========================= External function =================================
function stableMaster() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
interface IERC721 is IERC165 {
function balanceOf(address owner) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address owner, address operator) external view returns (bool);
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
interface 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);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "./IAccessControl.sol";
/// @title IFeeManagerFunctions
/// @author Angle Core Team
/// @dev Interface for the `FeeManager` contract
interface IFeeManagerFunctions is IAccessControl {
// ================================= Keepers ===================================
function updateUsersSLP() external;
function updateHA() external;
// ================================= Governance ================================
function deployCollateral(
address[] memory governorList,
address guardian,
address _perpetualManager
) external;
function setFees(
uint256[] memory xArray,
uint64[] memory yArray,
uint8 typeChange
) external;
function setHAFees(uint64 _haFeeDeposit, uint64 _haFeeWithdraw) external;
}
/// @title IFeeManager
/// @author Angle Core Team
/// @notice Previous interface with additionnal getters for public variables and mappings
/// @dev We need these getters as they are used in other contracts of the protocol
interface IFeeManager is IFeeManagerFunctions {
function stableMaster() external view returns (address);
function perpetualManager() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
/// @title IOracle
/// @author Angle Core Team
/// @notice Interface for Angle's oracle contracts reading oracle rates from both UniswapV3 and Chainlink
/// from just UniswapV3 or from just Chainlink
interface IOracle {
function read() external view returns (uint256);
function readAll() external view returns (uint256 lowerRate, uint256 upperRate);
function readLower() external view returns (uint256);
function readUpper() external view returns (uint256);
function readQuote(uint256 baseAmount) external view returns (uint256);
function readQuoteLower(uint256 baseAmount) external view returns (uint256);
function inBase() external view returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "./IERC721.sol";
import "./IFeeManager.sol";
import "./IOracle.sol";
import "./IAccessControl.sol";
/// @title Interface of the contract managing perpetuals
/// @author Angle Core Team
/// @dev Front interface, meaning only user-facing functions
interface IPerpetualManagerFront is IERC721Metadata {
function openPerpetual(
address owner,
uint256 amountBrought,
uint256 amountCommitted,
uint256 maxOracleRate,
uint256 minNetMargin
) external returns (uint256 perpetualID);
function closePerpetual(
uint256 perpetualID,
address to,
uint256 minCashOutAmount
) external;
function addToPerpetual(uint256 perpetualID, uint256 amount) external;
function removeFromPerpetual(
uint256 perpetualID,
uint256 amount,
address to
) external;
function liquidatePerpetuals(uint256[] memory perpetualIDs) external;
function forceClosePerpetuals(uint256[] memory perpetualIDs) external;
// ========================= External View Functions =============================
function getCashOutAmount(uint256 perpetualID, uint256 rate) external view returns (uint256, uint256);
function isApprovedOrOwner(address spender, uint256 perpetualID) external view returns (bool);
}
/// @title Interface of the contract managing perpetuals
/// @author Angle Core Team
/// @dev This interface does not contain user facing functions, it just has functions that are
/// interacted with in other parts of the protocol
interface IPerpetualManagerFunctions is IAccessControl {
// ================================= Governance ================================
function deployCollateral(
address[] memory governorList,
address guardian,
IFeeManager feeManager,
IOracle oracle_
) external;
function setFeeManager(IFeeManager feeManager_) external;
function setHAFees(
uint64[] memory _xHAFees,
uint64[] memory _yHAFees,
uint8 deposit
) external;
function setTargetAndLimitHAHedge(uint64 _targetHAHedge, uint64 _limitHAHedge) external;
function setKeeperFeesLiquidationRatio(uint64 _keeperFeesLiquidationRatio) external;
function setKeeperFeesCap(uint256 _keeperFeesLiquidationCap, uint256 _keeperFeesClosingCap) external;
function setKeeperFeesClosing(uint64[] memory _xKeeperFeesClosing, uint64[] memory _yKeeperFeesClosing) external;
function setLockTime(uint64 _lockTime) external;
function setBoundsPerpetual(uint64 _maxLeverage, uint64 _maintenanceMargin) external;
function pause() external;
function unpause() external;
// ==================================== Keepers ================================
function setFeeKeeper(uint64 feeDeposit, uint64 feesWithdraw) external;
// =============================== StableMaster ================================
function setOracle(IOracle _oracle) external;
}
/// @title IPerpetualManager
/// @author Angle Core Team
/// @notice Previous interface with additionnal getters for public variables
interface IPerpetualManager is IPerpetualManagerFunctions {
function poolManager() external view returns (address);
function oracle() external view returns (address);
function targetHAHedge() external view returns (uint64);
function totalHedgeAmount() external view returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "./IFeeManager.sol";
import "./IPerpetualManager.sol";
import "./IOracle.sol";
// Struct for the parameters associated to a strategy interacting with a collateral `PoolManager`
// contract
struct StrategyParams {
// Timestamp of last report made by this strategy
// It is also used to check if a strategy has been initialized
uint256 lastReport;
// Total amount the strategy is expected to have
uint256 totalStrategyDebt;
// The share of the total assets in the `PoolManager` contract that the `strategy` can access to.
uint256 debtRatio;
}
/// @title IPoolManagerFunctions
/// @author Angle Core Team
/// @notice Interface for the collateral poolManager contracts handling each one type of collateral for
/// a given stablecoin
/// @dev Only the functions used in other contracts of the protocol are left here
interface IPoolManagerFunctions {
// ============================ Constructor ====================================
function deployCollateral(
address[] memory governorList,
address guardian,
IPerpetualManager _perpetualManager,
IFeeManager feeManager,
IOracle oracle
) external;
// ============================ Yield Farming ==================================
function creditAvailable() external view returns (uint256);
function debtOutstanding() external view returns (uint256);
function report(
uint256 _gain,
uint256 _loss,
uint256 _debtPayment
) external;
// ============================ Governance =====================================
function addGovernor(address _governor) external;
function removeGovernor(address _governor) external;
function setGuardian(address _guardian, address guardian) external;
function revokeGuardian(address guardian) external;
function setFeeManager(IFeeManager _feeManager) external;
// ============================= Getters =======================================
function getBalance() external view returns (uint256);
function getTotalAsset() external view returns (uint256);
}
/// @title IPoolManager
/// @author Angle Core Team
/// @notice Previous interface with additionnal getters for public variables and mappings
/// @dev Used in other contracts of the protocol
interface IPoolManager is IPoolManagerFunctions {
function stableMaster() external view returns (address);
function perpetualManager() external view returns (address);
function token() external view returns (address);
function feeManager() external view returns (address);
function totalDebt() external view returns (uint256);
function strategies(address _strategy) external view returns (StrategyParams memory);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
/// @title ISanToken
/// @author Angle Core Team
/// @notice Interface for Angle's `SanToken` contract that handles sanTokens, tokens that are given to SLPs
/// contributing to a collateral for a given stablecoin
interface ISanToken is IERC20Upgradeable {
// ================================== StableMaster =============================
function mint(address account, uint256 amount) external;
function burnFrom(
uint256 amount,
address burner,
address sender
) external;
function burnSelf(uint256 amount, address burner) external;
function stableMaster() external view returns (address);
function poolManager() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// Normally just importing `IPoolManager` should be sufficient, but for clarity here
// we prefer to import all concerned interfaces
import "./IPoolManager.sol";
import "./IOracle.sol";
import "./IPerpetualManager.sol";
import "./ISanToken.sol";
// Struct to handle all the parameters to manage the fees
// related to a given collateral pool (associated to the stablecoin)
struct MintBurnData {
// Values of the thresholds to compute the minting fees
// depending on HA hedge (scaled by `BASE_PARAMS`)
uint64[] xFeeMint;
// Values of the fees at thresholds (scaled by `BASE_PARAMS`)
uint64[] yFeeMint;
// Values of the thresholds to compute the burning fees
// depending on HA hedge (scaled by `BASE_PARAMS`)
uint64[] xFeeBurn;
// Values of the fees at thresholds (scaled by `BASE_PARAMS`)
uint64[] yFeeBurn;
// Max proportion of collateral from users that can be covered by HAs
// It is exactly the same as the parameter of the same name in `PerpetualManager`, whenever one is updated
// the other changes accordingly
uint64 targetHAHedge;
// Minting fees correction set by the `FeeManager` contract: they are going to be multiplied
// to the value of the fees computed using the hedge curve
// Scaled by `BASE_PARAMS`
uint64 bonusMalusMint;
// Burning fees correction set by the `FeeManager` contract: they are going to be multiplied
// to the value of the fees computed using the hedge curve
// Scaled by `BASE_PARAMS`
uint64 bonusMalusBurn;
// Parameter used to limit the number of stablecoins that can be issued using the concerned collateral
uint256 capOnStableMinted;
}
// Struct to handle all the variables and parameters to handle SLPs in the protocol
// including the fraction of interests they receive or the fees to be distributed to
// them
struct SLPData {
// Last timestamp at which the `sanRate` has been updated for SLPs
uint256 lastBlockUpdated;
// Fees accumulated from previous blocks and to be distributed to SLPs
uint256 lockedInterests;
// Max interests used to update the `sanRate` in a single block
// Should be in collateral token base
uint256 maxInterestsDistributed;
// Amount of fees left aside for SLPs and that will be distributed
// when the protocol is collateralized back again
uint256 feesAside;
// Part of the fees normally going to SLPs that is left aside
// before the protocol is collateralized back again (depends on collateral ratio)
// Updated by keepers and scaled by `BASE_PARAMS`
uint64 slippageFee;
// Portion of the fees from users minting and burning
// that goes to SLPs (the rest goes to surplus)
uint64 feesForSLPs;
// Slippage factor that's applied to SLPs exiting (depends on collateral ratio)
// If `slippage = BASE_PARAMS`, SLPs can get nothing, if `slippage = 0` they get their full claim
// Updated by keepers and scaled by `BASE_PARAMS`
uint64 slippage;
// Portion of the interests from lending
// that goes to SLPs (the rest goes to surplus)
uint64 interestsForSLPs;
}
/// @title IStableMasterFunctions
/// @author Angle Core Team
/// @notice Interface for the `StableMaster` contract
interface IStableMasterFunctions {
function deploy(
address[] memory _governorList,
address _guardian,
address _agToken
) external;
// ============================== Lending ======================================
function accumulateInterest(uint256 gain) external;
function signalLoss(uint256 loss) external;
// ============================== HAs ==========================================
function getStocksUsers() external view returns (uint256 maxCAmountInStable);
function convertToSLP(uint256 amount, address user) external;
// ============================== Keepers ======================================
function getCollateralRatio() external returns (uint256);
function setFeeKeeper(
uint64 feeMint,
uint64 feeBurn,
uint64 _slippage,
uint64 _slippageFee
) external;
// ============================== AgToken ======================================
function updateStocksUsers(uint256 amount, address poolManager) external;
// ============================= Governance ====================================
function setCore(address newCore) external;
function addGovernor(address _governor) external;
function removeGovernor(address _governor) external;
function setGuardian(address newGuardian, address oldGuardian) external;
function revokeGuardian(address oldGuardian) external;
function setCapOnStableAndMaxInterests(
uint256 _capOnStableMinted,
uint256 _maxInterestsDistributed,
IPoolManager poolManager
) external;
function setIncentivesForSLPs(
uint64 _feesForSLPs,
uint64 _interestsForSLPs,
IPoolManager poolManager
) external;
function setUserFees(
IPoolManager poolManager,
uint64[] memory _xFee,
uint64[] memory _yFee,
uint8 _mint
) external;
function setTargetHAHedge(uint64 _targetHAHedge) external;
function pause(bytes32 agent, IPoolManager poolManager) external;
function unpause(bytes32 agent, IPoolManager poolManager) external;
}
/// @title IStableMaster
/// @author Angle Core Team
/// @notice Previous interface with additionnal getters for public variables and mappings
interface IStableMaster is IStableMasterFunctions {
function agToken() external view returns (address);
function collateralMap(IPoolManager poolManager)
external
view
returns (
IERC20 token,
ISanToken sanToken,
IPerpetualManager perpetualManager,
IOracle oracle,
uint256 stocksUsers,
uint256 sanRate,
uint256 collatBase,
SLPData memory slpData,
MintBurnData memory feeData
);
}
|
Lets the `StableMaster` contract mint agTokens account Address to mint to amount Amount to mint Only the `StableMaster` contract can issue agTokens
|
function mint(address account, uint256 amount) external override onlyStableMaster {
_mint(account, amount);
}
| 12,161,287
|
pragma solidity ^0.5.16;
import "./VToken.sol";
import "./ErrorReporter.sol";
import "./PriceOracle.sol";
import "./ComptrollerInterface.sol";
import "./ComptrollerStorage.sol";
import "./Unitroller.sol";
import "./Governance/XVS.sol";
import "./VAI/VAI.sol";
/**
* @title Venus's Comptroller Contract
* @author Venus
*/
contract Comptroller is ComptrollerV4Storage, ComptrollerInterfaceG2, ComptrollerErrorReporter, ExponentialNoError {
/// @notice Emitted when an admin supports a market
event MarketListed(VToken vToken);
/// @notice Emitted when an account enters a market
event MarketEntered(VToken vToken, address account);
/// @notice Emitted when an account exits a market
event MarketExited(VToken vToken, address account);
/// @notice Emitted when close factor is changed by admin
event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa);
/// @notice Emitted when a collateral factor is changed by admin
event NewCollateralFactor(VToken vToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);
/// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa);
/// @notice Emitted when price oracle is changed
event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle);
/// @notice Emitted when VAI Vault info is changed
event NewVAIVaultInfo(address vault_, uint releaseStartBlock_, uint releaseInterval_);
/// @notice Emitted when pause guardian is changed
event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);
/// @notice Emitted when an action is paused globally
event ActionPaused(string action, bool pauseState);
/// @notice Emitted when an action is paused on a market
event ActionPaused(VToken vToken, string action, bool pauseState);
/// @notice Emitted when Venus VAI rate is changed
event NewVenusVAIRate(uint oldVenusVAIRate, uint newVenusVAIRate);
/// @notice Emitted when Venus VAI Vault rate is changed
event NewVenusVAIVaultRate(uint oldVenusVAIVaultRate, uint newVenusVAIVaultRate);
/// @notice Emitted when a new Venus speed is calculated for a market
event VenusSpeedUpdated(VToken indexed vToken, uint newSpeed);
/// @notice Emitted when XVS is distributed to a supplier
event DistributedSupplierVenus(VToken indexed vToken, address indexed supplier, uint venusDelta, uint venusSupplyIndex);
/// @notice Emitted when XVS is distributed to a borrower
event DistributedBorrowerVenus(VToken indexed vToken, address indexed borrower, uint venusDelta, uint venusBorrowIndex);
/// @notice Emitted when XVS is distributed to a VAI minter
event DistributedVAIMinterVenus(address indexed vaiMinter, uint venusDelta, uint venusVAIMintIndex);
/// @notice Emitted when XVS is distributed to VAI Vault
event DistributedVAIVaultVenus(uint amount);
/// @notice Emitted when VAIController is changed
event NewVAIController(VAIControllerInterface oldVAIController, VAIControllerInterface newVAIController);
/// @notice Emitted when VAI mint rate is changed by admin
event NewVAIMintRate(uint oldVAIMintRate, uint newVAIMintRate);
/// @notice Emitted when protocol state is changed by admin
event ActionProtocolPaused(bool state);
/// @notice Emitted when borrow cap for a vToken is changed
event NewBorrowCap(VToken indexed vToken, uint newBorrowCap);
/// @notice Emitted when borrow cap guardian is changed
event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian);
/// @notice Emitted when treasury guardian is changed
event NewTreasuryGuardian(address oldTreasuryGuardian, address newTreasuryGuardian);
/// @notice Emitted when treasury address is changed
event NewTreasuryAddress(address oldTreasuryAddress, address newTreasuryAddress);
/// @notice Emitted when treasury percent is changed
event NewTreasuryPercent(uint oldTreasuryPercent, uint newTreasuryPercent);
/// @notice The initial Venus index for a market
uint224 public constant venusInitialIndex = 1e36;
// closeFactorMantissa must be strictly greater than this value
uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05
// closeFactorMantissa must not exceed this value
uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9
// No collateralFactorMantissa may exceed this value
uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9
constructor() public {
admin = msg.sender;
}
modifier onlyProtocolAllowed {
require(!protocolPaused, "protocol is paused");
_;
}
modifier onlyAdmin() {
require(msg.sender == admin, "only admin can");
_;
}
modifier onlyListedMarket(VToken vToken) {
require(markets[address(vToken)].isListed, "venus market is not listed");
_;
}
modifier validPauseState(bool state) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can");
require(msg.sender == admin || state == true, "only admin can unpause");
_;
}
/*** Assets You Are In ***/
/**
* @notice Returns the assets an account has entered
* @param account The address of the account to pull assets for
* @return A dynamic list with the assets the account has entered
*/
function getAssetsIn(address account) external view returns (VToken[] memory) {
return accountAssets[account];
}
/**
* @notice Returns whether the given account is entered in the given asset
* @param account The address of the account to check
* @param vToken The vToken to check
* @return True if the account is in the asset, otherwise false.
*/
function checkMembership(address account, VToken vToken) external view returns (bool) {
return markets[address(vToken)].accountMembership[account];
}
/**
* @notice Add assets to be included in account liquidity calculation
* @param vTokens The list of addresses of the vToken markets to be enabled
* @return Success indicator for whether each corresponding market was entered
*/
function enterMarkets(address[] calldata vTokens) external returns (uint[] memory) {
uint len = vTokens.length;
uint[] memory results = new uint[](len);
for (uint i = 0; i < len; i++) {
results[i] = uint(addToMarketInternal(VToken(vTokens[i]), msg.sender));
}
return results;
}
/**
* @notice Add the market to the borrower's "assets in" for liquidity calculations
* @param vToken The market to enter
* @param borrower The address of the account to modify
* @return Success indicator for whether the market was entered
*/
function addToMarketInternal(VToken vToken, address borrower) internal returns (Error) {
Market storage marketToJoin = markets[address(vToken)];
if (!marketToJoin.isListed) {
// market is not listed, cannot join
return Error.MARKET_NOT_LISTED;
}
if (marketToJoin.accountMembership[borrower]) {
// already joined
return Error.NO_ERROR;
}
// survived the gauntlet, add to list
// NOTE: we store these somewhat redundantly as a significant optimization
// this avoids having to iterate through the list for the most common use cases
// that is, only when we need to perform liquidity checks
// and not whenever we want to check if an account is in a particular market
marketToJoin.accountMembership[borrower] = true;
accountAssets[borrower].push(vToken);
emit MarketEntered(vToken, borrower);
return Error.NO_ERROR;
}
/**
* @notice Removes asset from sender's account liquidity calculation
* @dev Sender must not have an outstanding borrow balance in the asset,
* or be providing necessary collateral for an outstanding borrow.
* @param vTokenAddress The address of the asset to be removed
* @return Whether or not the account successfully exited the market
*/
function exitMarket(address vTokenAddress) external returns (uint) {
VToken vToken = VToken(vTokenAddress);
/* Get sender tokensHeld and amountOwed underlying from the vToken */
(uint oErr, uint tokensHeld, uint amountOwed, ) = vToken.getAccountSnapshot(msg.sender);
require(oErr == 0, "getAccountSnapshot failed"); // semi-opaque error code
/* Fail if the sender has a borrow balance */
if (amountOwed != 0) {
return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED);
}
/* Fail if the sender is not permitted to redeem all of their tokens */
uint allowed = redeemAllowedInternal(vTokenAddress, msg.sender, tokensHeld);
if (allowed != 0) {
return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);
}
Market storage marketToExit = markets[address(vToken)];
/* Return true if the sender is not already ‘in’ the market */
if (!marketToExit.accountMembership[msg.sender]) {
return uint(Error.NO_ERROR);
}
/* Set vToken account membership to false */
delete marketToExit.accountMembership[msg.sender];
/* Delete vToken from the account’s list of assets */
// In order to delete vToken, copy last item in list to location of item to be removed, reduce length by 1
VToken[] storage userAssetList = accountAssets[msg.sender];
uint len = userAssetList.length;
uint i;
for (; i < len; i++) {
if (userAssetList[i] == vToken) {
userAssetList[i] = userAssetList[len - 1];
userAssetList.length--;
break;
}
}
// We *must* have found the asset in the list or our redundant data structure is broken
assert(i < len);
emit MarketExited(vToken, msg.sender);
return uint(Error.NO_ERROR);
}
/*** Policy Hooks ***/
/**
* @notice Checks if the account should be allowed to mint tokens in the given market
* @param vToken The market to verify the mint against
* @param minter The account which would get the minted tokens
* @param mintAmount The amount of underlying being supplied to the market in exchange for tokens
* @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function mintAllowed(address vToken, address minter, uint mintAmount) external onlyProtocolAllowed returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!mintGuardianPaused[vToken], "mint is paused");
// Shh - currently unused
mintAmount;
if (!markets[vToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
updateVenusSupplyIndex(vToken);
distributeSupplierVenus(vToken, minter);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates mint and reverts on rejection. May emit logs.
* @param vToken Asset being minted
* @param minter The address minting the tokens
* @param actualMintAmount The amount of the underlying asset being minted
* @param mintTokens The number of tokens being minted
*/
function mintVerify(address vToken, address minter, uint actualMintAmount, uint mintTokens) external {
// Shh - currently unused
vToken;
minter;
actualMintAmount;
mintTokens;
}
/**
* @notice Checks if the account should be allowed to redeem tokens in the given market
* @param vToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of vTokens to exchange for the underlying asset in the market
* @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function redeemAllowed(address vToken, address redeemer, uint redeemTokens) external onlyProtocolAllowed returns (uint) {
uint allowed = redeemAllowedInternal(vToken, redeemer, redeemTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
updateVenusSupplyIndex(vToken);
distributeSupplierVenus(vToken, redeemer);
return uint(Error.NO_ERROR);
}
function redeemAllowedInternal(address vToken, address redeemer, uint redeemTokens) internal view returns (uint) {
if (!markets[vToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
if (!markets[vToken].accountMembership[redeemer]) {
return uint(Error.NO_ERROR);
}
/* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, VToken(vToken), redeemTokens, 0);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall != 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates redeem and reverts on rejection. May emit logs.
* @param vToken Asset being redeemed
* @param redeemer The address redeeming the tokens
* @param redeemAmount The amount of the underlying asset being redeemed
* @param redeemTokens The number of tokens being redeemed
*/
function redeemVerify(address vToken, address redeemer, uint redeemAmount, uint redeemTokens) external {
// Shh - currently unused
vToken;
redeemer;
// Require tokens is zero or amount is also zero
require(redeemTokens != 0 || redeemAmount == 0, "redeemTokens zero");
}
/**
* @notice Checks if the account should be allowed to borrow the underlying asset of the given market
* @param vToken The market to verify the borrow against
* @param borrower The account which would borrow the asset
* @param borrowAmount The amount of underlying the account would borrow
* @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function borrowAllowed(address vToken, address borrower, uint borrowAmount) external onlyProtocolAllowed returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!borrowGuardianPaused[vToken], "borrow is paused");
if (!markets[vToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (!markets[vToken].accountMembership[borrower]) {
// only vTokens may call borrowAllowed if borrower not in market
require(msg.sender == vToken, "sender must be vToken");
// attempt to add borrower to the market
Error err = addToMarketInternal(VToken(vToken), borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
}
if (oracle.getUnderlyingPrice(VToken(vToken)) == 0) {
return uint(Error.PRICE_ERROR);
}
uint borrowCap = borrowCaps[vToken];
// Borrow cap of 0 corresponds to unlimited borrowing
if (borrowCap != 0) {
uint totalBorrows = VToken(vToken).totalBorrows();
uint nextTotalBorrows = add_(totalBorrows, borrowAmount);
require(nextTotalBorrows < borrowCap, "market borrow cap reached");
}
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, VToken(vToken), 0, borrowAmount);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall != 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
// Keep the flywheel moving
Exp memory borrowIndex = Exp({mantissa: VToken(vToken).borrowIndex()});
updateVenusBorrowIndex(vToken, borrowIndex);
distributeBorrowerVenus(vToken, borrower, borrowIndex);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates borrow and reverts on rejection. May emit logs.
* @param vToken Asset whose underlying is being borrowed
* @param borrower The address borrowing the underlying
* @param borrowAmount The amount of the underlying asset requested to borrow
*/
function borrowVerify(address vToken, address borrower, uint borrowAmount) external {
// Shh - currently unused
vToken;
borrower;
borrowAmount;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to repay a borrow in the given market
* @param vToken The market to verify the repay against
* @param payer The account which would repay the asset
* @param borrower The account which would repay the asset
* @param repayAmount The amount of the underlying asset the account would repay
* @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function repayBorrowAllowed(
address vToken,
address payer,
address borrower,
uint repayAmount) external onlyProtocolAllowed returns (uint) {
// Shh - currently unused
payer;
borrower;
repayAmount;
if (!markets[vToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
Exp memory borrowIndex = Exp({mantissa: VToken(vToken).borrowIndex()});
updateVenusBorrowIndex(vToken, borrowIndex);
distributeBorrowerVenus(vToken, borrower, borrowIndex);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates repayBorrow and reverts on rejection. May emit logs.
* @param vToken Asset being repaid
* @param payer The address repaying the borrow
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function repayBorrowVerify(
address vToken,
address payer,
address borrower,
uint actualRepayAmount,
uint borrowerIndex) external {
// Shh - currently unused
vToken;
payer;
borrower;
actualRepayAmount;
borrowerIndex;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the liquidation should be allowed to occur
* @param vTokenBorrowed Asset which was borrowed by the borrower
* @param vTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param repayAmount The amount of underlying being repaid
*/
function liquidateBorrowAllowed(
address vTokenBorrowed,
address vTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external onlyProtocolAllowed returns (uint) {
// Shh - currently unused
liquidator;
if (!(markets[vTokenBorrowed].isListed || address(vTokenBorrowed) == address(vaiController)) || !markets[vTokenCollateral].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* The borrower must have shortfall in order to be liquidatable */
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, VToken(0), 0, 0);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall == 0) {
return uint(Error.INSUFFICIENT_SHORTFALL);
}
/* The liquidator may not repay more than what is allowed by the closeFactor */
uint borrowBalance;
if (address(vTokenBorrowed) != address(vaiController)) {
borrowBalance = VToken(vTokenBorrowed).borrowBalanceStored(borrower);
} else {
borrowBalance = mintedVAIs[borrower];
}
uint maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance);
if (repayAmount > maxClose) {
return uint(Error.TOO_MUCH_REPAY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates liquidateBorrow and reverts on rejection. May emit logs.
* @param vTokenBorrowed Asset which was borrowed by the borrower
* @param vTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function liquidateBorrowVerify(
address vTokenBorrowed,
address vTokenCollateral,
address liquidator,
address borrower,
uint actualRepayAmount,
uint seizeTokens) external {
// Shh - currently unused
vTokenBorrowed;
vTokenCollateral;
liquidator;
borrower;
actualRepayAmount;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the seizing of assets should be allowed to occur
* @param vTokenCollateral Asset which was used as collateral and will be seized
* @param vTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeAllowed(
address vTokenCollateral,
address vTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external onlyProtocolAllowed returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!seizeGuardianPaused, "seize is paused");
// Shh - currently unused
seizeTokens;
// We've added VAIController as a borrowed token list check for seize
if (!markets[vTokenCollateral].isListed || !(markets[vTokenBorrowed].isListed || address(vTokenBorrowed) == address(vaiController))) {
return uint(Error.MARKET_NOT_LISTED);
}
if (VToken(vTokenCollateral).comptroller() != VToken(vTokenBorrowed).comptroller()) {
return uint(Error.COMPTROLLER_MISMATCH);
}
// Keep the flywheel moving
updateVenusSupplyIndex(vTokenCollateral);
distributeSupplierVenus(vTokenCollateral, borrower);
distributeSupplierVenus(vTokenCollateral, liquidator);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates seize and reverts on rejection. May emit logs.
* @param vTokenCollateral Asset which was used as collateral and will be seized
* @param vTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeVerify(
address vTokenCollateral,
address vTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external {
// Shh - currently unused
vTokenCollateral;
vTokenBorrowed;
liquidator;
borrower;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to transfer tokens in the given market
* @param vToken The market to verify the transfer against
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of vTokens to transfer
* @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function transferAllowed(address vToken, address src, address dst, uint transferTokens) external onlyProtocolAllowed returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!transferGuardianPaused, "transfer is paused");
// Currently the only consideration is whether or not
// the src is allowed to redeem this many tokens
uint allowed = redeemAllowedInternal(vToken, src, transferTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
updateVenusSupplyIndex(vToken);
distributeSupplierVenus(vToken, src);
distributeSupplierVenus(vToken, dst);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates transfer and reverts on rejection. May emit logs.
* @param vToken Asset being transferred
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of vTokens to transfer
*/
function transferVerify(address vToken, address src, address dst, uint transferTokens) external {
// Shh - currently unused
vToken;
src;
dst;
transferTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/*** Liquidity/Liquidation Calculations ***/
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `vTokenBalance` is the number of vTokens the account owns in the market,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
*/
struct AccountLiquidityLocalVars {
uint sumCollateral;
uint sumBorrowPlusEffects;
uint vTokenBalance;
uint borrowBalance;
uint exchangeRateMantissa;
uint oraclePriceMantissa;
Exp collateralFactor;
Exp exchangeRate;
Exp oraclePrice;
Exp tokensToDenom;
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code (semi-opaque),
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidity(address account) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, VToken(0), 0, 0);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param vTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @return (possible error code (semi-opaque),
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidity(
address account,
address vTokenModify,
uint redeemTokens,
uint borrowAmount) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, VToken(vTokenModify), redeemTokens, borrowAmount);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param vTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @dev Note that we calculate the exchangeRateStored for each collateral vToken using stored data,
* without calculating accumulated interest.
* @return (possible error code,
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidityInternal(
address account,
VToken vTokenModify,
uint redeemTokens,
uint borrowAmount) internal view returns (Error, uint, uint) {
AccountLiquidityLocalVars memory vars; // Holds all our calculation results
uint oErr;
// For each asset the account is in
VToken[] memory assets = accountAssets[account];
for (uint i = 0; i < assets.length; i++) {
VToken asset = assets[i];
// Read the balances and exchange rate from the vToken
(oErr, vars.vTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account);
if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades
return (Error.SNAPSHOT_ERROR, 0, 0);
}
vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa});
vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa});
// Get the normalized price of the asset
vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset);
if (vars.oraclePriceMantissa == 0) {
return (Error.PRICE_ERROR, 0, 0);
}
vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa});
// Pre-compute a conversion factor from tokens -> bnb (normalized price value)
vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice);
// sumCollateral += tokensToDenom * vTokenBalance
vars.sumCollateral = mul_ScalarTruncateAddUInt(vars.tokensToDenom, vars.vTokenBalance, vars.sumCollateral);
// sumBorrowPlusEffects += oraclePrice * borrowBalance
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects);
// Calculate effects of interacting with vTokenModify
if (asset == vTokenModify) {
// redeem effect
// sumBorrowPlusEffects += tokensToDenom * redeemTokens
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects);
// borrow effect
// sumBorrowPlusEffects += oraclePrice * borrowAmount
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects);
}
}
vars.sumBorrowPlusEffects = add_(vars.sumBorrowPlusEffects, mintedVAIs[account]);
// These are safe, as the underflow condition is checked first
if (vars.sumCollateral > vars.sumBorrowPlusEffects) {
return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0);
} else {
return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral);
}
}
/**
* @notice Calculate number of tokens of collateral asset to seize given an underlying amount
* @dev Used in liquidation (called in vToken.liquidateBorrowFresh)
* @param vTokenBorrowed The address of the borrowed vToken
* @param vTokenCollateral The address of the collateral vToken
* @param actualRepayAmount The amount of vTokenBorrowed underlying to convert into vTokenCollateral tokens
* @return (errorCode, number of vTokenCollateral tokens to be seized in a liquidation)
*/
function liquidateCalculateSeizeTokens(address vTokenBorrowed, address vTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) {
/* Read oracle prices for borrowed and collateral markets */
uint priceBorrowedMantissa = oracle.getUnderlyingPrice(VToken(vTokenBorrowed));
uint priceCollateralMantissa = oracle.getUnderlyingPrice(VToken(vTokenCollateral));
if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) {
return (uint(Error.PRICE_ERROR), 0);
}
/*
* Get the exchange rate and calculate the number of collateral tokens to seize:
* seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral
* seizeTokens = seizeAmount / exchangeRate
* = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate)
*/
uint exchangeRateMantissa = VToken(vTokenCollateral).exchangeRateStored(); // Note: reverts on error
uint seizeTokens;
Exp memory numerator;
Exp memory denominator;
Exp memory ratio;
numerator = mul_(Exp({mantissa: liquidationIncentiveMantissa}), Exp({mantissa: priceBorrowedMantissa}));
denominator = mul_(Exp({mantissa: priceCollateralMantissa}), Exp({mantissa: exchangeRateMantissa}));
ratio = div_(numerator, denominator);
seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount);
return (uint(Error.NO_ERROR), seizeTokens);
}
/**
* @notice Calculate number of tokens of collateral asset to seize given an underlying amount
* @dev Used in liquidation (called in vToken.liquidateBorrowFresh)
* @param vTokenCollateral The address of the collateral vToken
* @param actualRepayAmount The amount of vTokenBorrowed underlying to convert into vTokenCollateral tokens
* @return (errorCode, number of vTokenCollateral tokens to be seized in a liquidation)
*/
function liquidateVAICalculateSeizeTokens(address vTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) {
/* Read oracle prices for borrowed and collateral markets */
uint priceBorrowedMantissa = 1e18; // Note: this is VAI
uint priceCollateralMantissa = oracle.getUnderlyingPrice(VToken(vTokenCollateral));
if (priceCollateralMantissa == 0) {
return (uint(Error.PRICE_ERROR), 0);
}
/*
* Get the exchange rate and calculate the number of collateral tokens to seize:
* seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral
* seizeTokens = seizeAmount / exchangeRate
* = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate)
*/
uint exchangeRateMantissa = VToken(vTokenCollateral).exchangeRateStored(); // Note: reverts on error
uint seizeTokens;
Exp memory numerator;
Exp memory denominator;
Exp memory ratio;
numerator = mul_(Exp({mantissa: liquidationIncentiveMantissa}), Exp({mantissa: priceBorrowedMantissa}));
denominator = mul_(Exp({mantissa: priceCollateralMantissa}), Exp({mantissa: exchangeRateMantissa}));
ratio = div_(numerator, denominator);
seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount);
return (uint(Error.NO_ERROR), seizeTokens);
}
/*** Admin Functions ***/
/**
* @notice Sets a new price oracle for the comptroller
* @dev Admin function to set a new price oracle
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPriceOracle(PriceOracle newOracle) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);
}
// Track the old oracle for the comptroller
PriceOracle oldOracle = oracle;
// Set comptroller's oracle to newOracle
oracle = newOracle;
// Emit NewPriceOracle(oldOracle, newOracle)
emit NewPriceOracle(oldOracle, newOracle);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the closeFactor used when liquidating borrows
* @dev Admin function to set closeFactor
* @param newCloseFactorMantissa New close factor, scaled by 1e18
* @return uint 0=success, otherwise a failure
*/
function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) {
// Check caller is admin
require(msg.sender == admin, "only admin can set close factor");
uint oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = newCloseFactorMantissa;
emit NewCloseFactor(oldCloseFactorMantissa, newCloseFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the collateralFactor for a market
* @dev Admin function to set per-market collateralFactor
* @param vToken The market to set the factor on
* @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCollateralFactor(VToken vToken, uint newCollateralFactorMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK);
}
// Verify market is listed
Market storage market = markets[address(vToken)];
if (!market.isListed) {
return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS);
}
Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa});
// Check collateral factor <= 0.9
Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa});
if (lessThanExp(highLimit, newCollateralFactorExp)) {
return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION);
}
// If collateral factor != 0, fail if price == 0
if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(vToken) == 0) {
return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);
}
// Set market's collateral factor to new collateral factor, remember old value
uint oldCollateralFactorMantissa = market.collateralFactorMantissa;
market.collateralFactorMantissa = newCollateralFactorMantissa;
// Emit event with asset, old collateral factor, and new collateral factor
emit NewCollateralFactor(vToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets liquidationIncentive
* @dev Admin function to set liquidationIncentive
* @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK);
}
// Save current value for use in log
uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
// Set liquidation incentive to new incentive
liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
// Emit event with old incentive, new incentive
emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Add the market to the markets mapping and set it as listed
* @dev Admin function to set isListed and add support for the market
* @param vToken The address of the market (token) to list
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _supportMarket(VToken vToken) external returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK);
}
if (markets[address(vToken)].isListed) {
return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS);
}
vToken.isVToken(); // Sanity check to make sure its really a VToken
// Note that isVenus is not in active use anymore
markets[address(vToken)] = Market({isListed: true, isVenus: false, collateralFactorMantissa: 0});
_addMarketInternal(vToken);
emit MarketListed(vToken);
return uint(Error.NO_ERROR);
}
function _addMarketInternal(VToken vToken) internal {
for (uint i = 0; i < allMarkets.length; i ++) {
require(allMarkets[i] != vToken, "market already added");
}
allMarkets.push(vToken);
}
/**
* @notice Admin function to change the Pause Guardian
* @param newPauseGuardian The address of the new Pause Guardian
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _setPauseGuardian(address newPauseGuardian) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK);
}
// Save current value for inclusion in log
address oldPauseGuardian = pauseGuardian;
// Store pauseGuardian with value newPauseGuardian
pauseGuardian = newPauseGuardian;
// Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian)
emit NewPauseGuardian(oldPauseGuardian, newPauseGuardian);
return uint(Error.NO_ERROR);
}
/**
* @notice Set the given borrow caps for the given vToken markets. Borrowing that brings total borrows to or above borrow cap will revert.
* @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing.
* @param vTokens The addresses of the markets (tokens) to change the borrow caps for
* @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing.
*/
function _setMarketBorrowCaps(VToken[] calldata vTokens, uint[] calldata newBorrowCaps) external {
require(msg.sender == admin || msg.sender == borrowCapGuardian, "only admin or borrow cap guardian can set borrow caps");
uint numMarkets = vTokens.length;
uint numBorrowCaps = newBorrowCaps.length;
require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input");
for(uint i = 0; i < numMarkets; i++) {
borrowCaps[address(vTokens[i])] = newBorrowCaps[i];
emit NewBorrowCap(vTokens[i], newBorrowCaps[i]);
}
}
/**
* @notice Admin function to change the Borrow Cap Guardian
* @param newBorrowCapGuardian The address of the new Borrow Cap Guardian
*/
function _setBorrowCapGuardian(address newBorrowCapGuardian) external onlyAdmin {
// Save current value for inclusion in log
address oldBorrowCapGuardian = borrowCapGuardian;
// Store borrowCapGuardian with value newBorrowCapGuardian
borrowCapGuardian = newBorrowCapGuardian;
// Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian)
emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian);
}
/**
* @notice Set whole protocol pause/unpause state
*/
function _setProtocolPaused(bool state) public validPauseState(state) returns(bool) {
protocolPaused = state;
emit ActionProtocolPaused(state);
return state;
}
/**
* @notice Sets a new VAI controller
* @dev Admin function to set a new VAI controller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setVAIController(VAIControllerInterface vaiController_) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_VAICONTROLLER_OWNER_CHECK);
}
VAIControllerInterface oldRate = vaiController;
vaiController = vaiController_;
emit NewVAIController(oldRate, vaiController_);
}
function _setVAIMintRate(uint newVAIMintRate) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_VAI_MINT_RATE_CHECK);
}
uint oldVAIMintRate = vaiMintRate;
vaiMintRate = newVAIMintRate;
emit NewVAIMintRate(oldVAIMintRate, newVAIMintRate);
return uint(Error.NO_ERROR);
}
function _setTreasuryData(address newTreasuryGuardian, address newTreasuryAddress, uint newTreasuryPercent) external returns (uint) {
// Check caller is admin
if (!(msg.sender == admin || msg.sender == treasuryGuardian)) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_TREASURY_OWNER_CHECK);
}
require(newTreasuryPercent < 1e18, "treasury percent cap overflow");
address oldTreasuryGuardian = treasuryGuardian;
address oldTreasuryAddress = treasuryAddress;
uint oldTreasuryPercent = treasuryPercent;
treasuryGuardian = newTreasuryGuardian;
treasuryAddress = newTreasuryAddress;
treasuryPercent = newTreasuryPercent;
emit NewTreasuryGuardian(oldTreasuryGuardian, newTreasuryGuardian);
emit NewTreasuryAddress(oldTreasuryAddress, newTreasuryAddress);
emit NewTreasuryPercent(oldTreasuryPercent, newTreasuryPercent);
return uint(Error.NO_ERROR);
}
function _become(Unitroller unitroller) public {
require(msg.sender == unitroller.admin(), "only unitroller admin can");
require(unitroller._acceptImplementation() == 0, "not authorized");
}
/**
* @notice Checks caller is admin, or this contract is becoming the new implementation
*/
function adminOrInitializing() internal view returns (bool) {
return msg.sender == admin || msg.sender == comptrollerImplementation;
}
/*** Venus Distribution ***/
function setVenusSpeedInternal(VToken vToken, uint venusSpeed) internal {
uint currentVenusSpeed = venusSpeeds[address(vToken)];
if (currentVenusSpeed != 0) {
// note that XVS speed could be set to 0 to halt liquidity rewards for a market
Exp memory borrowIndex = Exp({mantissa: vToken.borrowIndex()});
updateVenusSupplyIndex(address(vToken));
updateVenusBorrowIndex(address(vToken), borrowIndex);
} else if (venusSpeed != 0) {
// Add the XVS market
Market storage market = markets[address(vToken)];
require(market.isListed == true, "venus market is not listed");
if (venusSupplyState[address(vToken)].index == 0 && venusSupplyState[address(vToken)].block == 0) {
venusSupplyState[address(vToken)] = VenusMarketState({
index: venusInitialIndex,
block: safe32(getBlockNumber(), "block number exceeds 32 bits")
});
}
if (venusBorrowState[address(vToken)].index == 0 && venusBorrowState[address(vToken)].block == 0) {
venusBorrowState[address(vToken)] = VenusMarketState({
index: venusInitialIndex,
block: safe32(getBlockNumber(), "block number exceeds 32 bits")
});
}
}
if (currentVenusSpeed != venusSpeed) {
venusSpeeds[address(vToken)] = venusSpeed;
emit VenusSpeedUpdated(vToken, venusSpeed);
}
}
/**
* @notice Accrue XVS to the market by updating the supply index
* @param vToken The market whose supply index to update
*/
function updateVenusSupplyIndex(address vToken) internal {
VenusMarketState storage supplyState = venusSupplyState[vToken];
uint supplySpeed = venusSpeeds[vToken];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, uint(supplyState.block));
if (deltaBlocks > 0 && supplySpeed > 0) {
uint supplyTokens = VToken(vToken).totalSupply();
uint venusAccrued = mul_(deltaBlocks, supplySpeed);
Double memory ratio = supplyTokens > 0 ? fraction(venusAccrued, supplyTokens) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: supplyState.index}), ratio);
venusSupplyState[vToken] = VenusMarketState({
index: safe224(index.mantissa, "new index overflows"),
block: safe32(blockNumber, "block number overflows")
});
} else if (deltaBlocks > 0) {
supplyState.block = safe32(blockNumber, "block number overflows");
}
}
/**
* @notice Accrue XVS to the market by updating the borrow index
* @param vToken The market whose borrow index to update
*/
function updateVenusBorrowIndex(address vToken, Exp memory marketBorrowIndex) internal {
VenusMarketState storage borrowState = venusBorrowState[vToken];
uint borrowSpeed = venusSpeeds[vToken];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, uint(borrowState.block));
if (deltaBlocks > 0 && borrowSpeed > 0) {
uint borrowAmount = div_(VToken(vToken).totalBorrows(), marketBorrowIndex);
uint venusAccrued = mul_(deltaBlocks, borrowSpeed);
Double memory ratio = borrowAmount > 0 ? fraction(venusAccrued, borrowAmount) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: borrowState.index}), ratio);
venusBorrowState[vToken] = VenusMarketState({
index: safe224(index.mantissa, "new index overflows"),
block: safe32(blockNumber, "block number overflows")
});
} else if (deltaBlocks > 0) {
borrowState.block = safe32(blockNumber, "block number overflows");
}
}
/**
* @notice Calculate XVS accrued by a supplier and possibly transfer it to them
* @param vToken The market in which the supplier is interacting
* @param supplier The address of the supplier to distribute XVS to
*/
function distributeSupplierVenus(address vToken, address supplier) internal {
if (address(vaiVaultAddress) != address(0)) {
releaseToVault();
}
VenusMarketState storage supplyState = venusSupplyState[vToken];
Double memory supplyIndex = Double({mantissa: supplyState.index});
Double memory supplierIndex = Double({mantissa: venusSupplierIndex[vToken][supplier]});
venusSupplierIndex[vToken][supplier] = supplyIndex.mantissa;
if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) {
supplierIndex.mantissa = venusInitialIndex;
}
Double memory deltaIndex = sub_(supplyIndex, supplierIndex);
uint supplierTokens = VToken(vToken).balanceOf(supplier);
uint supplierDelta = mul_(supplierTokens, deltaIndex);
uint supplierAccrued = add_(venusAccrued[supplier], supplierDelta);
venusAccrued[supplier] = supplierAccrued;
emit DistributedSupplierVenus(VToken(vToken), supplier, supplierDelta, supplyIndex.mantissa);
}
/**
* @notice Calculate XVS accrued by a borrower and possibly transfer it to them
* @dev Borrowers will not begin to accrue until after the first interaction with the protocol.
* @param vToken The market in which the borrower is interacting
* @param borrower The address of the borrower to distribute XVS to
*/
function distributeBorrowerVenus(address vToken, address borrower, Exp memory marketBorrowIndex) internal {
if (address(vaiVaultAddress) != address(0)) {
releaseToVault();
}
VenusMarketState storage borrowState = venusBorrowState[vToken];
Double memory borrowIndex = Double({mantissa: borrowState.index});
Double memory borrowerIndex = Double({mantissa: venusBorrowerIndex[vToken][borrower]});
venusBorrowerIndex[vToken][borrower] = borrowIndex.mantissa;
if (borrowerIndex.mantissa > 0) {
Double memory deltaIndex = sub_(borrowIndex, borrowerIndex);
uint borrowerAmount = div_(VToken(vToken).borrowBalanceStored(borrower), marketBorrowIndex);
uint borrowerDelta = mul_(borrowerAmount, deltaIndex);
uint borrowerAccrued = add_(venusAccrued[borrower], borrowerDelta);
venusAccrued[borrower] = borrowerAccrued;
emit DistributedBorrowerVenus(VToken(vToken), borrower, borrowerDelta, borrowIndex.mantissa);
}
}
/**
* @notice Calculate XVS accrued by a VAI minter and possibly transfer it to them
* @dev VAI minters will not begin to accrue until after the first interaction with the protocol.
* @param vaiMinter The address of the VAI minter to distribute XVS to
*/
function distributeVAIMinterVenus(address vaiMinter) public {
if (address(vaiVaultAddress) != address(0)) {
releaseToVault();
}
if (address(vaiController) != address(0)) {
uint vaiMinterAccrued;
uint vaiMinterDelta;
uint vaiMintIndexMantissa;
uint err;
(err, vaiMinterAccrued, vaiMinterDelta, vaiMintIndexMantissa) = vaiController.calcDistributeVAIMinterVenus(vaiMinter);
if (err == uint(Error.NO_ERROR)) {
venusAccrued[vaiMinter] = vaiMinterAccrued;
emit DistributedVAIMinterVenus(vaiMinter, vaiMinterDelta, vaiMintIndexMantissa);
}
}
}
/**
* @notice Claim all the xvs accrued by holder in all markets and VAI
* @param holder The address to claim XVS for
*/
function claimVenus(address holder) public {
return claimVenus(holder, allMarkets);
}
/**
* @notice Claim all the xvs accrued by holder in the specified markets
* @param holder The address to claim XVS for
* @param vTokens The list of markets to claim XVS in
*/
function claimVenus(address holder, VToken[] memory vTokens) public {
address[] memory holders = new address[](1);
holders[0] = holder;
claimVenus(holders, vTokens, true, true);
}
/**
* @notice Claim all xvs accrued by the holders
* @param holders The addresses to claim XVS for
* @param vTokens The list of markets to claim XVS in
* @param borrowers Whether or not to claim XVS earned by borrowing
* @param suppliers Whether or not to claim XVS earned by supplying
*/
function claimVenus(address[] memory holders, VToken[] memory vTokens, bool borrowers, bool suppliers) public {
uint j;
if(address(vaiController) != address(0)) {
vaiController.updateVenusVAIMintIndex();
}
for (j = 0; j < holders.length; j++) {
distributeVAIMinterVenus(holders[j]);
venusAccrued[holders[j]] = grantXVSInternal(holders[j], venusAccrued[holders[j]]);
}
for (uint i = 0; i < vTokens.length; i++) {
VToken vToken = vTokens[i];
require(markets[address(vToken)].isListed, "not listed market");
if (borrowers) {
Exp memory borrowIndex = Exp({mantissa: vToken.borrowIndex()});
updateVenusBorrowIndex(address(vToken), borrowIndex);
for (j = 0; j < holders.length; j++) {
distributeBorrowerVenus(address(vToken), holders[j], borrowIndex);
venusAccrued[holders[j]] = grantXVSInternal(holders[j], venusAccrued[holders[j]]);
}
}
if (suppliers) {
updateVenusSupplyIndex(address(vToken));
for (j = 0; j < holders.length; j++) {
distributeSupplierVenus(address(vToken), holders[j]);
venusAccrued[holders[j]] = grantXVSInternal(holders[j], venusAccrued[holders[j]]);
}
}
}
}
/**
* @notice Transfer XVS to the user
* @dev Note: If there is not enough XVS, we do not perform the transfer all.
* @param user The address of the user to transfer XVS to
* @param amount The amount of XVS to (possibly) transfer
* @return The amount of XVS which was NOT transferred to the user
*/
function grantXVSInternal(address user, uint amount) internal returns (uint) {
XVS xvs = XVS(getXVSAddress());
uint venusRemaining = xvs.balanceOf(address(this));
if (amount > 0 && amount <= venusRemaining) {
xvs.transfer(user, amount);
return 0;
}
return amount;
}
/*** Venus Distribution Admin ***/
/**
* @notice Set the amount of XVS distributed per block to VAI Mint
* @param venusVAIRate_ The amount of XVS wei per block to distribute to VAI Mint
*/
function _setVenusVAIRate(uint venusVAIRate_) public onlyAdmin {
uint oldVAIRate = venusVAIRate;
venusVAIRate = venusVAIRate_;
emit NewVenusVAIRate(oldVAIRate, venusVAIRate_);
}
/**
* @notice Set the amount of XVS distributed per block to VAI Vault
* @param venusVAIVaultRate_ The amount of XVS wei per block to distribute to VAI Vault
*/
function _setVenusVAIVaultRate(uint venusVAIVaultRate_) public onlyAdmin {
uint oldVenusVAIVaultRate = venusVAIVaultRate;
venusVAIVaultRate = venusVAIVaultRate_;
emit NewVenusVAIVaultRate(oldVenusVAIVaultRate, venusVAIVaultRate_);
}
/**
* @notice Set the VAI Vault infos
* @param vault_ The address of the VAI Vault
* @param releaseStartBlock_ The start block of release to VAI Vault
* @param minReleaseAmount_ The minimum release amount to VAI Vault
*/
function _setVAIVaultInfo(address vault_, uint256 releaseStartBlock_, uint256 minReleaseAmount_) public onlyAdmin {
vaiVaultAddress = vault_;
releaseStartBlock = releaseStartBlock_;
minReleaseAmount = minReleaseAmount_;
emit NewVAIVaultInfo(vault_, releaseStartBlock_, minReleaseAmount_);
}
/**
* @notice Set XVS speed for a single market
* @param vToken The market whose XVS speed to update
* @param venusSpeed New XVS speed for market
*/
function _setVenusSpeed(VToken vToken, uint venusSpeed) public {
require(adminOrInitializing(), "only admin can set venus speed");
setVenusSpeedInternal(vToken, venusSpeed);
}
/**
* @notice Return all of the markets
* @dev The automatic getter may be used to access an individual market.
* @return The list of market addresses
*/
function getAllMarkets() public view returns (VToken[] memory) {
return allMarkets;
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
/**
* @notice Return the address of the XVS token
* @return The address of XVS
*/
function getXVSAddress() public view returns (address) {
return 0xcF6BB5389c92Bdda8a3747Ddb454cB7a64626C63;
}
/*** VAI functions ***/
/**
* @notice Set the minted VAI amount of the `owner`
* @param owner The address of the account to set
* @param amount The amount of VAI to set to the account
* @return The number of minted VAI by `owner`
*/
function setMintedVAIOf(address owner, uint amount) external onlyProtocolAllowed returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!mintVAIGuardianPaused && !repayVAIGuardianPaused, "VAI is paused");
// Check caller is vaiController
if (msg.sender != address(vaiController)) {
return fail(Error.REJECTION, FailureInfo.SET_MINTED_VAI_REJECTION);
}
mintedVAIs[owner] = amount;
return uint(Error.NO_ERROR);
}
/**
* @notice Transfer XVS to VAI Vault
*/
function releaseToVault() public {
if(releaseStartBlock == 0 || getBlockNumber() < releaseStartBlock) {
return;
}
XVS xvs = XVS(getXVSAddress());
uint256 xvsBalance = xvs.balanceOf(address(this));
if(xvsBalance == 0) {
return;
}
uint256 actualAmount;
uint256 deltaBlocks = sub_(getBlockNumber(), releaseStartBlock);
// releaseAmount = venusVAIVaultRate * deltaBlocks
uint256 _releaseAmount = mul_(venusVAIVaultRate, deltaBlocks);
if (_releaseAmount < minReleaseAmount) {
return;
}
if (xvsBalance >= _releaseAmount) {
actualAmount = _releaseAmount;
} else {
actualAmount = xvsBalance;
}
releaseStartBlock = getBlockNumber();
xvs.transfer(vaiVaultAddress, actualAmount);
emit DistributedVAIVaultVenus(actualAmount);
IVAIVault(vaiVaultAddress).updatePendingRewards();
}
}
|
Checks if the seizing of assets should be allowed to occur vTokenCollateral Asset which was used as collateral and will be seized vTokenBorrowed Asset which was borrowed by the borrower liquidator The address repaying the borrow and seizing the collateral borrower The address of the borrower seizeTokens The number of collateral tokens to seize/ Pausing is a very serious situation - we revert to sound the alarms Shh - currently unused We've added VAIController as a borrowed token list check for seize
|
function seizeAllowed(
address vTokenCollateral,
address vTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external onlyProtocolAllowed returns (uint) {
require(!seizeGuardianPaused, "seize is paused");
seizeTokens;
if (!markets[vTokenCollateral].isListed || !(markets[vTokenBorrowed].isListed || address(vTokenBorrowed) == address(vaiController))) {
return uint(Error.MARKET_NOT_LISTED);
}
if (VToken(vTokenCollateral).comptroller() != VToken(vTokenBorrowed).comptroller()) {
return uint(Error.COMPTROLLER_MISMATCH);
}
distributeSupplierVenus(vTokenCollateral, borrower);
distributeSupplierVenus(vTokenCollateral, liquidator);
return uint(Error.NO_ERROR);
}
| 1,063,647
|
./partial_match/1/0xFe28E9Fa8DC0482C9Fb95C9906C679F12d1d635E/sources/CryptoGains2.sol
|
function to dynamically pause and unpause - simply pass in true or false
|
function setPause(bool _paused) external onlyOwner {
paused = _paused;
}
| 15,635,062
|
/**
*Submitted for verification at Etherscan.io on 2022-03-15
*/
// SPDX-License-Identifier: GPL-3.0-or-later
// Sources flattened with hardhat v2.6.1 https://hardhat.org
// File @openzeppelin/contracts/token/ERC20/[email protected]
// 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);
}
// File @openzeppelin/contracts/utils/[email protected]
// 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);
}
}
}
}
// File @openzeppelin/contracts/token/ERC20/utils/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^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 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");
}
}
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
// 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 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
* ====
*
* [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 Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts-upgradeable/proxy/utils/[email protected]
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// File interfaces/IStrategy.sol
pragma solidity 0.8.9;
interface IStrategy {
function name() external view returns (string memory);
function deposit() external payable returns (bool);
function balance() external view returns (uint256);
function withdraw(uint256 amount) external returns (bool);
function withdrawAll() external returns (uint256);
function harvestable() external view returns (uint256);
function harvest() external returns (uint256);
function strategist() external view returns (address);
function shutdown() external returns (bool);
function hasPendingFunds() external view returns (bool);
}
// File interfaces/IPreparable.sol
pragma solidity 0.8.9;
interface IPreparable {
event ConfigPreparedAddress(bytes32 indexed key, address value, uint256 delay);
event ConfigPreparedNumber(bytes32 indexed key, uint256 value, uint256 delay);
event ConfigUpdatedAddress(bytes32 indexed key, address oldValue, address newValue);
event ConfigUpdatedNumber(bytes32 indexed key, uint256 oldValue, uint256 newValue);
event ConfigReset(bytes32 indexed key);
}
// File interfaces/IVault.sol
pragma solidity 0.8.9;
/**
* @title Interface for a Vault
*/
interface IVault is IPreparable {
event StrategyActivated(address indexed strategy);
event StrategyDeactivated(address indexed strategy);
/**
* @dev 'netProfit' is the profit after all fees have been deducted
*/
event Harvest(uint256 indexed netProfit, uint256 indexed loss);
function initialize(
address _pool,
uint256 _debtLimit,
uint256 _targetAllocation,
uint256 _bound
) external;
function withdrawFromStrategyWaitingForRemoval(address strategy) external returns (uint256);
function deposit() external payable;
function withdraw(uint256 amount) external returns (bool);
function initializeStrategy(address strategy_) external returns (bool);
function withdrawAll() external;
function withdrawFromReserve(uint256 amount) external;
function getStrategy() external view returns (IStrategy);
function getStrategiesWaitingForRemoval() external view returns (address[] memory);
function getAllocatedToStrategyWaitingForRemoval(address strategy)
external
view
returns (uint256);
function getTotalUnderlying() external view returns (uint256);
function getUnderlying() external view returns (address);
}
// File interfaces/IVaultReserve.sol
pragma solidity 0.8.9;
interface IVaultReserve {
event Deposit(address indexed vault, address indexed token, uint256 amount);
event Withdraw(address indexed vault, address indexed token, uint256 amount);
event VaultListed(address indexed vault);
function deposit(address token, uint256 amount) external payable returns (bool);
function withdraw(address token, uint256 amount) external returns (bool);
function getBalance(address vault, address token) external view returns (uint256);
function canWithdraw(address vault) external view returns (bool);
}
// File interfaces/pool/ILiquidityPool.sol
pragma solidity 0.8.9;
interface ILiquidityPool is IPreparable {
event Deposit(address indexed minter, uint256 depositAmount, uint256 mintedLpTokens);
event DepositFor(
address indexed minter,
address indexed mintee,
uint256 depositAmount,
uint256 mintedLpTokens
);
event Redeem(address indexed redeemer, uint256 redeemAmount, uint256 redeemTokens);
event LpTokenSet(address indexed lpToken);
event StakerVaultSet(address indexed stakerVault);
function redeem(uint256 redeemTokens) external returns (uint256);
function redeem(uint256 redeemTokens, uint256 minRedeemAmount) external returns (uint256);
function calcRedeem(address account, uint256 underlyingAmount) external returns (uint256);
function deposit(uint256 mintAmount) external payable returns (uint256);
function deposit(uint256 mintAmount, uint256 minTokenAmount) external payable returns (uint256);
function depositAndStake(uint256 depositAmount, uint256 minTokenAmount)
external
payable
returns (uint256);
function depositFor(address account, uint256 depositAmount) external payable returns (uint256);
function depositFor(
address account,
uint256 depositAmount,
uint256 minTokenAmount
) external payable returns (uint256);
function unstakeAndRedeem(uint256 redeemLpTokens, uint256 minRedeemAmount)
external
returns (uint256);
function handleLpTokenTransfer(
address from,
address to,
uint256 amount
) external;
function executeNewVault() external returns (address);
function executeNewMaxWithdrawalFee() external returns (uint256);
function executeNewRequiredReserves() external returns (uint256);
function executeNewReserveDeviation() external returns (uint256);
function setLpToken(address _lpToken) external returns (bool);
function setStaker() external returns (bool);
function isCapped() external returns (bool);
function uncap() external returns (bool);
function updateDepositCap(uint256 _depositCap) external returns (bool);
function getUnderlying() external view returns (address);
function getLpToken() external view returns (address);
function getWithdrawalFee(address account, uint256 amount) external view returns (uint256);
function getVault() external view returns (IVault);
function exchangeRate() external view returns (uint256);
}
// File interfaces/IGasBank.sol
pragma solidity 0.8.9;
interface IGasBank {
event Deposit(address indexed account, uint256 value);
event Withdraw(address indexed account, address indexed receiver, uint256 value);
function depositFor(address account) external payable;
function withdrawUnused(address account) external;
function withdrawFrom(address account, uint256 amount) external;
function withdrawFrom(
address account,
address payable to,
uint256 amount
) external;
function balanceOf(address account) external view returns (uint256);
}
// File interfaces/oracles/IOracleProvider.sol
pragma solidity 0.8.9;
interface IOracleProvider {
/// @notice Quotes the USD price of `baseAsset`
/// @param baseAsset the asset of which the price is to be quoted
/// @return the USD price of the asset
function getPriceUSD(address baseAsset) external view returns (uint256);
/// @notice Quotes the ETH price of `baseAsset`
/// @param baseAsset the asset of which the price is to be quoted
/// @return the ETH price of the asset
function getPriceETH(address baseAsset) external view returns (uint256);
}
// File libraries/AddressProviderMeta.sol
pragma solidity 0.8.9;
library AddressProviderMeta {
struct Meta {
bool freezable;
bool frozen;
}
function fromUInt(uint256 value) internal pure returns (Meta memory) {
Meta memory meta;
meta.freezable = (value & 1) == 1;
meta.frozen = ((value >> 1) & 1) == 1;
return meta;
}
function toUInt(Meta memory meta) internal pure returns (uint256) {
uint256 value;
value |= meta.freezable ? 1 : 0;
value |= meta.frozen ? 1 << 1 : 0;
return value;
}
}
// File interfaces/IAddressProvider.sol
pragma solidity 0.8.9;
// solhint-disable ordering
interface IAddressProvider is IPreparable {
event KnownAddressKeyAdded(bytes32 indexed key);
event StakerVaultListed(address indexed stakerVault);
event StakerVaultDelisted(address indexed stakerVault);
event ActionListed(address indexed action);
event PoolListed(address indexed pool);
event PoolDelisted(address indexed pool);
event VaultUpdated(address indexed previousVault, address indexed newVault);
/** Key functions */
function getKnownAddressKeys() external view returns (bytes32[] memory);
function freezeAddress(bytes32 key) external;
/** Pool functions */
function allPools() external view returns (address[] memory);
function addPool(address pool) external;
function poolsCount() external view returns (uint256);
function getPoolAtIndex(uint256 index) external view returns (address);
function isPool(address pool) external view returns (bool);
function removePool(address pool) external returns (bool);
function getPoolForToken(address token) external view returns (ILiquidityPool);
function safeGetPoolForToken(address token) external view returns (address);
/** Vault functions */
function updateVault(address previousVault, address newVault) external;
function allVaults() external view returns (address[] memory);
function vaultsCount() external view returns (uint256);
function getVaultAtIndex(uint256 index) external view returns (address);
function isVault(address vault) external view returns (bool);
/** Action functions */
function allActions() external view returns (address[] memory);
function addAction(address action) external returns (bool);
function isAction(address action) external view returns (bool);
/** Address functions */
function initializeAddress(
bytes32 key,
address initialAddress,
bool frezable
) external;
function initializeAndFreezeAddress(bytes32 key, address initialAddress) external;
function getAddress(bytes32 key) external view returns (address);
function getAddress(bytes32 key, bool checkExists) external view returns (address);
function getAddressMeta(bytes32 key) external view returns (AddressProviderMeta.Meta memory);
function prepareAddress(bytes32 key, address newAddress) external returns (bool);
function executeAddress(bytes32 key) external returns (address);
function resetAddress(bytes32 key) external returns (bool);
/** Staker vault functions */
function allStakerVaults() external view returns (address[] memory);
function tryGetStakerVault(address token) external view returns (bool, address);
function getStakerVault(address token) external view returns (address);
function addStakerVault(address stakerVault) external returns (bool);
function isStakerVault(address stakerVault, address token) external view returns (bool);
function isStakerVaultRegistered(address stakerVault) external view returns (bool);
function isWhiteListedFeeHandler(address feeHandler) external view returns (bool);
}
// File interfaces/tokenomics/IInflationManager.sol
pragma solidity 0.8.9;
interface IInflationManager {
event KeeperGaugeListed(address indexed pool, address indexed keeperGauge);
event AmmGaugeListed(address indexed token, address indexed ammGauge);
event KeeperGaugeDelisted(address indexed pool, address indexed keeperGauge);
event AmmGaugeDelisted(address indexed token, address indexed ammGauge);
/** Pool functions */
function setKeeperGauge(address pool, address _keeperGauge) external returns (bool);
function setAmmGauge(address token, address _ammGauge) external returns (bool);
function getAllAmmGauges() external view returns (address[] memory);
function getLpRateForStakerVault(address stakerVault) external view returns (uint256);
function getKeeperRateForPool(address pool) external view returns (uint256);
function getAmmRateForToken(address token) external view returns (uint256);
function getKeeperWeightForPool(address pool) external view returns (uint256);
function getAmmWeightForToken(address pool) external view returns (uint256);
function getLpPoolWeight(address pool) external view returns (uint256);
function getKeeperGaugeForPool(address pool) external view returns (address);
function getAmmGaugeForToken(address token) external view returns (address);
function isInflationWeightManager(address account) external view returns (bool);
function removeStakerVaultFromInflation(address stakerVault, address lpToken) external;
function addGaugeForVault(address lpToken) external returns (bool);
function whitelistGauge(address gauge) external;
function checkpointAllGauges() external returns (bool);
function mintRewards(address beneficiary, uint256 amount) external;
function addStrategyToDepositStakerVault(address depositStakerVault, address strategyPool)
external
returns (bool);
/** Weight setter functions **/
function prepareLpPoolWeight(address lpToken, uint256 newPoolWeight) external returns (bool);
function prepareAmmTokenWeight(address token, uint256 newTokenWeight) external returns (bool);
function prepareKeeperPoolWeight(address pool, uint256 newPoolWeight) external returns (bool);
function executeLpPoolWeight(address lpToken) external returns (uint256);
function executeAmmTokenWeight(address token) external returns (uint256);
function executeKeeperPoolWeight(address pool) external returns (uint256);
function batchPrepareLpPoolWeights(address[] calldata lpTokens, uint256[] calldata weights)
external
returns (bool);
function batchPrepareAmmTokenWeights(address[] calldata tokens, uint256[] calldata weights)
external
returns (bool);
function batchPrepareKeeperPoolWeights(address[] calldata pools, uint256[] calldata weights)
external
returns (bool);
function batchExecuteLpPoolWeights(address[] calldata lpTokens) external returns (bool);
function batchExecuteAmmTokenWeights(address[] calldata tokens) external returns (bool);
function batchExecuteKeeperPoolWeights(address[] calldata pools) external returns (bool);
}
// File interfaces/IController.sol
pragma solidity 0.8.9;
// solhint-disable ordering
interface IController is IPreparable {
function addressProvider() external view returns (IAddressProvider);
function inflationManager() external view returns (IInflationManager);
function addStakerVault(address stakerVault) external returns (bool);
function removePool(address pool) external returns (bool);
/** Keeper functions */
function prepareKeeperRequiredStakedBKD(uint256 amount) external;
function executeKeeperRequiredStakedBKD() external;
function getKeeperRequiredStakedBKD() external view returns (uint256);
function canKeeperExecuteAction(address keeper) external view returns (bool);
/** Miscellaneous functions */
function getTotalEthRequiredForGas(address payer) external view returns (uint256);
}
// File libraries/ScaledMath.sol
pragma solidity 0.8.9;
/*
* @dev To use functions of this contract, at least one of the numbers must
* be scaled to `DECIMAL_SCALE`. The result will scaled to `DECIMAL_SCALE`
* if both numbers are scaled to `DECIMAL_SCALE`, otherwise to the scale
* of the number not scaled by `DECIMAL_SCALE`
*/
library ScaledMath {
// solhint-disable-next-line private-vars-leading-underscore
uint256 internal constant DECIMAL_SCALE = 1e18;
// solhint-disable-next-line private-vars-leading-underscore
uint256 internal constant ONE = 1e18;
/**
* @notice Performs a multiplication between two scaled numbers
*/
function scaledMul(uint256 a, uint256 b) internal pure returns (uint256) {
return (a * b) / DECIMAL_SCALE;
}
/**
* @notice Performs a division between two scaled numbers
*/
function scaledDiv(uint256 a, uint256 b) internal pure returns (uint256) {
return (a * DECIMAL_SCALE) / b;
}
/**
* @notice Performs a division between two numbers, rounding up the result
*/
function scaledDivRoundUp(uint256 a, uint256 b) internal pure returns (uint256) {
return (a * DECIMAL_SCALE + b - 1) / b;
}
/**
* @notice Performs a division between two numbers, ignoring any scaling and rounding up the result
*/
function divRoundUp(uint256 a, uint256 b) internal pure returns (uint256) {
return (a + b - 1) / b;
}
}
// File libraries/Errors.sol
pragma solidity 0.8.9;
// solhint-disable private-vars-leading-underscore
library Error {
string internal constant ADDRESS_WHITELISTED = "address already whitelisted";
string internal constant ADMIN_ALREADY_SET = "admin has already been set once";
string internal constant ADDRESS_NOT_WHITELISTED = "address not whitelisted";
string internal constant ADDRESS_NOT_FOUND = "address not found";
string internal constant CONTRACT_INITIALIZED = "contract can only be initialized once";
string internal constant CONTRACT_PAUSED = "contract is paused";
string internal constant INVALID_AMOUNT = "invalid amount";
string internal constant INVALID_INDEX = "invalid index";
string internal constant INVALID_VALUE = "invalid msg.value";
string internal constant INVALID_SENDER = "invalid msg.sender";
string internal constant INVALID_TOKEN = "token address does not match pool's LP token address";
string internal constant INVALID_DECIMALS = "incorrect number of decimals";
string internal constant INVALID_ARGUMENT = "invalid argument";
string internal constant INVALID_PARAMETER_VALUE = "invalid parameter value attempted";
string internal constant INVALID_IMPLEMENTATION = "invalid pool implementation for given coin";
string internal constant INVALID_POOL_IMPLEMENTATION =
"invalid pool implementation for given coin";
string internal constant INVALID_LP_TOKEN_IMPLEMENTATION =
"invalid LP Token implementation for given coin";
string internal constant INVALID_VAULT_IMPLEMENTATION =
"invalid vault implementation for given coin";
string internal constant INVALID_STAKER_VAULT_IMPLEMENTATION =
"invalid stakerVault implementation for given coin";
string internal constant INSUFFICIENT_BALANCE = "insufficient balance";
string internal constant ADDRESS_ALREADY_SET = "Address is already set";
string internal constant INSUFFICIENT_STRATEGY_BALANCE = "insufficient strategy balance";
string internal constant INSUFFICIENT_FUNDS_RECEIVED = "insufficient funds received";
string internal constant ADDRESS_DOES_NOT_EXIST = "address does not exist";
string internal constant ADDRESS_FROZEN = "address is frozen";
string internal constant ROLE_EXISTS = "role already exists";
string internal constant CANNOT_REVOKE_ROLE = "cannot revoke role";
string internal constant UNAUTHORIZED_ACCESS = "unauthorized access";
string internal constant SAME_ADDRESS_NOT_ALLOWED = "same address not allowed";
string internal constant SELF_TRANSFER_NOT_ALLOWED = "self-transfer not allowed";
string internal constant ZERO_ADDRESS_NOT_ALLOWED = "zero address not allowed";
string internal constant ZERO_TRANSFER_NOT_ALLOWED = "zero transfer not allowed";
string internal constant THRESHOLD_TOO_HIGH = "threshold is too high, must be under 10";
string internal constant INSUFFICIENT_THRESHOLD = "insufficient threshold";
string internal constant NO_POSITION_EXISTS = "no position exists";
string internal constant POSITION_ALREADY_EXISTS = "position already exists";
string internal constant PROTOCOL_NOT_FOUND = "protocol not found";
string internal constant TOP_UP_FAILED = "top up failed";
string internal constant SWAP_PATH_NOT_FOUND = "swap path not found";
string internal constant UNDERLYING_NOT_SUPPORTED = "underlying token not supported";
string internal constant NOT_ENOUGH_FUNDS_WITHDRAWN =
"not enough funds were withdrawn from the pool";
string internal constant FAILED_TRANSFER = "transfer failed";
string internal constant FAILED_MINT = "mint failed";
string internal constant FAILED_REPAY_BORROW = "repay borrow failed";
string internal constant FAILED_METHOD_CALL = "method call failed";
string internal constant NOTHING_TO_CLAIM = "there is no claimable balance";
string internal constant ERC20_BALANCE_EXCEEDED = "ERC20: transfer amount exceeds balance";
string internal constant INVALID_MINTER =
"the minter address of the LP token and the pool address do not match";
string internal constant STAKER_VAULT_EXISTS = "a staker vault already exists for the token";
string internal constant DEADLINE_NOT_ZERO = "deadline must be 0";
string internal constant DEADLINE_NOT_SET = "deadline is 0";
string internal constant DEADLINE_NOT_REACHED = "deadline has not been reached yet";
string internal constant DELAY_TOO_SHORT = "delay be at least 3 days";
string internal constant INSUFFICIENT_UPDATE_BALANCE =
"insufficient funds for updating the position";
string internal constant SAME_AS_CURRENT = "value must be different to existing value";
string internal constant NOT_CAPPED = "the pool is not currently capped";
string internal constant ALREADY_CAPPED = "the pool is already capped";
string internal constant EXCEEDS_DEPOSIT_CAP = "deposit exceeds deposit cap";
string internal constant VALUE_TOO_LOW_FOR_GAS = "value too low to cover gas";
string internal constant NOT_ENOUGH_FUNDS = "not enough funds to withdraw";
string internal constant ESTIMATED_GAS_TOO_HIGH = "too much ETH will be used for gas";
string internal constant DEPOSIT_FAILED = "deposit failed";
string internal constant GAS_TOO_HIGH = "too much ETH used for gas";
string internal constant GAS_BANK_BALANCE_TOO_LOW = "not enough ETH in gas bank to cover gas";
string internal constant INVALID_TOKEN_TO_ADD = "Invalid token to add";
string internal constant INVALID_TOKEN_TO_REMOVE = "token can not be removed";
string internal constant TIME_DELAY_NOT_EXPIRED = "time delay not expired yet";
string internal constant UNDERLYING_NOT_WITHDRAWABLE =
"pool does not support additional underlying coins to be withdrawn";
string internal constant STRATEGY_SHUT_DOWN = "Strategy is shut down";
string internal constant STRATEGY_DOES_NOT_EXIST = "Strategy does not exist";
string internal constant UNSUPPORTED_UNDERLYING = "Underlying not supported";
string internal constant NO_DEX_SET = "no dex has been set for token";
string internal constant INVALID_TOKEN_PAIR = "invalid token pair";
string internal constant TOKEN_NOT_USABLE = "token not usable for the specific action";
string internal constant ADDRESS_NOT_ACTION = "address is not registered action";
string internal constant INVALID_SLIPPAGE_TOLERANCE = "Invalid slippage tolerance";
string internal constant POOL_NOT_PAUSED = "Pool must be paused to withdraw from reserve";
string internal constant INTERACTION_LIMIT = "Max of one deposit and withdraw per block";
string internal constant GAUGE_EXISTS = "Gauge already exists";
string internal constant GAUGE_DOES_NOT_EXIST = "Gauge does not exist";
string internal constant EXCEEDS_MAX_BOOST = "Not allowed to exceed maximum boost on Convex";
string internal constant PREPARED_WITHDRAWAL =
"Cannot relock funds when withdrawal is being prepared";
string internal constant ASSET_NOT_SUPPORTED = "Asset not supported";
string internal constant STALE_PRICE = "Price is stale";
string internal constant NEGATIVE_PRICE = "Price is negative";
string internal constant NOT_ENOUGH_BKD_STAKED = "Not enough BKD tokens staked";
string internal constant RESERVE_ACCESS_EXCEEDED = "Reserve access exceeded";
}
// File @openzeppelin/contracts/utils/structs/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
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] = valueIndex; // Replace lastvalue's index to valueIndex
}
// 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) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// 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);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// 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))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// 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));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// File libraries/EnumerableMapping.sol
pragma solidity 0.8.9;
library EnumerableMapping {
using EnumerableSet for EnumerableSet.Bytes32Set;
// Code take from contracts/utils/structs/EnumerableMap.sol
// because the helper functions are private
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct Map {
// Storage of keys
EnumerableSet.Bytes32Set _keys;
mapping(bytes32 => bytes32) _values;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(
Map storage map,
bytes32 key,
bytes32 value
) private returns (bool) {
map._values[key] = value;
return map._keys.add(key);
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
delete map._values[key];
return map._keys.remove(key);
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._keys.contains(key);
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._keys.length();
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
bytes32 key = map._keys.at(index);
return (key, map._values[key]);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
bytes32 value = map._values[key];
if (value == bytes32(0)) {
return (_contains(map, key), bytes32(0));
} else {
return (true, value);
}
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
bytes32 value = map._values[key];
require(value != 0 || _contains(map, key), "EnumerableMap: nonexistent key");
return value;
}
// AddressToAddressMap
struct AddressToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(
AddressToAddressMap storage map,
address key,
address value
) internal returns (bool) {
return _set(map._inner, bytes32(uint256(uint160(key))), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(AddressToAddressMap storage map, address key) internal returns (bool) {
return _remove(map._inner, bytes32(uint256(uint160(key))));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(AddressToAddressMap storage map, address key) internal view returns (bool) {
return _contains(map._inner, bytes32(uint256(uint160(key))));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(AddressToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressToAddressMap storage map, uint256 index)
internal
view
returns (address, address)
{
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (address(uint160(uint256(key))), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(AddressToAddressMap storage map, address key)
internal
view
returns (bool, address)
{
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(uint256(uint160(key))));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(AddressToAddressMap storage map, address key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(uint256(uint160(key)))))));
}
// AddressToUintMap
struct AddressToUintMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(
AddressToUintMap storage map,
address key,
uint256 value
) internal returns (bool) {
return _set(map._inner, bytes32(uint256(uint160(key))), bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(AddressToUintMap storage map, address key) internal returns (bool) {
return _remove(map._inner, bytes32(uint256(uint160(key))));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(AddressToUintMap storage map, address key) internal view returns (bool) {
return _contains(map._inner, bytes32(uint256(uint160(key))));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(AddressToUintMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressToUintMap storage map, uint256 index)
internal
view
returns (address, uint256)
{
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (address(uint160(uint256(key))), uint256(value));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(AddressToUintMap storage map, address key)
internal
view
returns (bool, uint256)
{
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(uint256(uint160(key))));
return (success, uint256(value));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(AddressToUintMap storage map, address key) internal view returns (uint256) {
return uint256(_get(map._inner, bytes32(uint256(uint160(key)))));
}
// Bytes32ToUIntMap
struct Bytes32ToUIntMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(
Bytes32ToUIntMap storage map,
bytes32 key,
uint256 value
) internal returns (bool) {
return _set(map._inner, key, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(Bytes32ToUIntMap storage map, bytes32 key) internal returns (bool) {
return _remove(map._inner, key);
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(Bytes32ToUIntMap storage map, bytes32 key) internal view returns (bool) {
return _contains(map._inner, key);
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(Bytes32ToUIntMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32ToUIntMap storage map, uint256 index)
internal
view
returns (bytes32, uint256)
{
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (key, uint256(value));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(Bytes32ToUIntMap storage map, bytes32 key)
internal
view
returns (bool, uint256)
{
(bool success, bytes32 value) = _tryGet(map._inner, key);
return (success, uint256(value));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(Bytes32ToUIntMap storage map, bytes32 key) internal view returns (uint256) {
return uint256(_get(map._inner, key));
}
}
// File libraries/EnumerableExtensions.sol
pragma solidity 0.8.9;
library EnumerableExtensions {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.Bytes32Set;
using EnumerableMapping for EnumerableMapping.AddressToAddressMap;
using EnumerableMapping for EnumerableMapping.AddressToUintMap;
using EnumerableMapping for EnumerableMapping.Bytes32ToUIntMap;
function toArray(EnumerableSet.AddressSet storage addresses)
internal
view
returns (address[] memory)
{
uint256 len = addresses.length();
address[] memory result = new address[](len);
for (uint256 i = 0; i < len; i++) {
result[i] = addresses.at(i);
}
return result;
}
function toArray(EnumerableSet.Bytes32Set storage values)
internal
view
returns (bytes32[] memory)
{
uint256 len = values.length();
bytes32[] memory result = new bytes32[](len);
for (uint256 i = 0; i < len; i++) {
result[i] = values.at(i);
}
return result;
}
function keyAt(EnumerableMapping.AddressToAddressMap storage map, uint256 index)
internal
view
returns (address)
{
(address key, ) = map.at(index);
return key;
}
function valueAt(EnumerableMapping.AddressToAddressMap storage map, uint256 index)
internal
view
returns (address)
{
(, address value) = map.at(index);
return value;
}
function keyAt(EnumerableMapping.AddressToUintMap storage map, uint256 index)
internal
view
returns (address)
{
(address key, ) = map.at(index);
return key;
}
function keyAt(EnumerableMapping.Bytes32ToUIntMap storage map, uint256 index)
internal
view
returns (bytes32)
{
(bytes32 key, ) = map.at(index);
return key;
}
function valueAt(EnumerableMapping.AddressToUintMap storage map, uint256 index)
internal
view
returns (uint256)
{
(, uint256 value) = map.at(index);
return value;
}
function keysArray(EnumerableMapping.AddressToAddressMap storage map)
internal
view
returns (address[] memory)
{
uint256 len = map.length();
address[] memory result = new address[](len);
for (uint256 i = 0; i < len; i++) {
result[i] = keyAt(map, i);
}
return result;
}
function valuesArray(EnumerableMapping.AddressToAddressMap storage map)
internal
view
returns (address[] memory)
{
uint256 len = map.length();
address[] memory result = new address[](len);
for (uint256 i = 0; i < len; i++) {
result[i] = valueAt(map, i);
}
return result;
}
function keysArray(EnumerableMapping.AddressToUintMap storage map)
internal
view
returns (address[] memory)
{
uint256 len = map.length();
address[] memory result = new address[](len);
for (uint256 i = 0; i < len; i++) {
result[i] = keyAt(map, i);
}
return result;
}
function keysArray(EnumerableMapping.Bytes32ToUIntMap storage map)
internal
view
returns (bytes32[] memory)
{
uint256 len = map.length();
bytes32[] memory result = new bytes32[](len);
for (uint256 i = 0; i < len; i++) {
result[i] = keyAt(map, i);
}
return result;
}
}
// File interfaces/IRoleManager.sol
pragma solidity 0.8.9;
interface IRoleManager {
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function hasRole(bytes32 role, address account) external view returns (bool);
function hasAnyRole(bytes32[] memory roles, address account) external view returns (bool);
function hasAnyRole(
bytes32 role1,
bytes32 role2,
address account
) external view returns (bool);
function hasAnyRole(
bytes32 role1,
bytes32 role2,
bytes32 role3,
address account
) external view returns (bool);
function getRoleMemberCount(bytes32 role) external view returns (uint256);
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
}
// File interfaces/tokenomics/IBkdToken.sol
pragma solidity 0.8.9;
interface IBkdToken is IERC20 {
function mint(address account, uint256 amount) external;
}
// File libraries/AddressProviderKeys.sol
pragma solidity 0.8.9;
library AddressProviderKeys {
bytes32 internal constant _TREASURY_KEY = "treasury";
bytes32 internal constant _GAS_BANK_KEY = "gasBank";
bytes32 internal constant _VAULT_RESERVE_KEY = "vaultReserve";
bytes32 internal constant _SWAPPER_REGISTRY_KEY = "swapperRegistry";
bytes32 internal constant _ORACLE_PROVIDER_KEY = "oracleProvider";
bytes32 internal constant _POOL_FACTORY_KEY = "poolFactory";
bytes32 internal constant _CONTROLLER_KEY = "controller";
bytes32 internal constant _BKD_LOCKER_KEY = "bkdLocker";
bytes32 internal constant _ROLE_MANAGER_KEY = "roleManager";
}
// File libraries/AddressProviderHelpers.sol
pragma solidity 0.8.9;
library AddressProviderHelpers {
/**
* @return The address of the treasury.
*/
function getTreasury(IAddressProvider provider) internal view returns (address) {
return provider.getAddress(AddressProviderKeys._TREASURY_KEY);
}
/**
* @return The gas bank.
*/
function getGasBank(IAddressProvider provider) internal view returns (IGasBank) {
return IGasBank(provider.getAddress(AddressProviderKeys._GAS_BANK_KEY));
}
/**
* @return The address of the vault reserve.
*/
function getVaultReserve(IAddressProvider provider) internal view returns (IVaultReserve) {
return IVaultReserve(provider.getAddress(AddressProviderKeys._VAULT_RESERVE_KEY));
}
/**
* @return The address of the swapperRegistry.
*/
function getSwapperRegistry(IAddressProvider provider) internal view returns (address) {
return provider.getAddress(AddressProviderKeys._SWAPPER_REGISTRY_KEY);
}
/**
* @return The oracleProvider.
*/
function getOracleProvider(IAddressProvider provider) internal view returns (IOracleProvider) {
return IOracleProvider(provider.getAddress(AddressProviderKeys._ORACLE_PROVIDER_KEY));
}
/**
* @return the address of the BKD locker
*/
function getBKDLocker(IAddressProvider provider) internal view returns (address) {
return provider.getAddress(AddressProviderKeys._BKD_LOCKER_KEY);
}
/**
* @return the address of the BKD locker
*/
function getRoleManager(IAddressProvider provider) internal view returns (IRoleManager) {
return IRoleManager(provider.getAddress(AddressProviderKeys._ROLE_MANAGER_KEY));
}
/**
* @return the controller
*/
function getController(IAddressProvider provider) internal view returns (IController) {
return IController(provider.getAddress(AddressProviderKeys._CONTROLLER_KEY));
}
}
// File contracts/vault/VaultStorage.sol
pragma solidity 0.8.9;
contract VaultStorage {
uint256 public currentAllocated;
uint256 public waitingForRemovalAllocated;
address public pool;
uint256 public totalDebt;
bool public strategyActive;
EnumerableMapping.AddressToUintMap internal _strategiesWaitingForRemoval;
}
contract VaultStorageV1 is VaultStorage {
/**
* @dev This is to avoid breaking contracts inheriting from `VaultStorage`
* such as `Erc20Vault`, especially if they have storage variables
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
* for more details
*
* A new field can be added using a new contract such as
*
* ```solidity
* contract VaultStorageV2 is VaultStorage {
* uint256 someNewField;
* uint256[49] private __gap;
* }
*/
uint256[50] private __gap;
}
// File contracts/utils/Preparable.sol
pragma solidity 0.8.9;
/**
* @notice Implements the base logic for a two-phase commit
* @dev This does not implements any access-control so publicly exposed
* callers should make sure to have the proper checks in palce
*/
contract Preparable is IPreparable {
uint256 private constant _MIN_DELAY = 3 days;
mapping(bytes32 => address) public pendingAddresses;
mapping(bytes32 => uint256) public pendingUInts256;
mapping(bytes32 => address) public currentAddresses;
mapping(bytes32 => uint256) public currentUInts256;
/**
* @dev Deadlines shares the same namespace regardless of the type
* of the pending variable so this needs to be enforced in the caller
*/
mapping(bytes32 => uint256) public deadlines;
function _prepareDeadline(bytes32 key, uint256 delay) internal {
require(deadlines[key] == 0, Error.DEADLINE_NOT_ZERO);
require(delay >= _MIN_DELAY, Error.DELAY_TOO_SHORT);
deadlines[key] = block.timestamp + delay;
}
/**
* @notice Prepares an uint256 that should be commited to the contract
* after `_MIN_DELAY` elapsed
* @param value The value to prepare
* @return `true` if success.
*/
function _prepare(
bytes32 key,
uint256 value,
uint256 delay
) internal returns (bool) {
_prepareDeadline(key, delay);
pendingUInts256[key] = value;
emit ConfigPreparedNumber(key, value, delay);
return true;
}
/**
* @notice Same as `_prepare(bytes32,uint256,uint256)` but uses a default delay
*/
function _prepare(bytes32 key, uint256 value) internal returns (bool) {
return _prepare(key, value, _MIN_DELAY);
}
/**
* @notice Prepares an address that should be commited to the contract
* after `_MIN_DELAY` elapsed
* @param value The value to prepare
* @return `true` if success.
*/
function _prepare(
bytes32 key,
address value,
uint256 delay
) internal returns (bool) {
_prepareDeadline(key, delay);
pendingAddresses[key] = value;
emit ConfigPreparedAddress(key, value, delay);
return true;
}
/**
* @notice Same as `_prepare(bytes32,address,uint256)` but uses a default delay
*/
function _prepare(bytes32 key, address value) internal returns (bool) {
return _prepare(key, value, _MIN_DELAY);
}
/**
* @notice Reset a uint256 key
* @return `true` if success.
*/
function _resetUInt256Config(bytes32 key) internal returns (bool) {
require(deadlines[key] != 0, Error.DEADLINE_NOT_ZERO);
deadlines[key] = 0;
pendingUInts256[key] = 0;
emit ConfigReset(key);
return true;
}
/**
* @notice Reset an address key
* @return `true` if success.
*/
function _resetAddressConfig(bytes32 key) internal returns (bool) {
require(deadlines[key] != 0, Error.DEADLINE_NOT_ZERO);
deadlines[key] = 0;
pendingAddresses[key] = address(0);
emit ConfigReset(key);
return true;
}
/**
* @dev Checks the deadline of the key and reset it
*/
function _executeDeadline(bytes32 key) internal {
uint256 deadline = deadlines[key];
require(block.timestamp >= deadline, Error.DEADLINE_NOT_REACHED);
require(deadline != 0, Error.DEADLINE_NOT_SET);
deadlines[key] = 0;
}
/**
* @notice Execute uint256 config update (with time delay enforced).
* @dev Needs to be called after the update was prepared. Fails if called before time delay is met.
* @return New value.
*/
function _executeUInt256(bytes32 key) internal returns (uint256) {
_executeDeadline(key);
uint256 newValue = pendingUInts256[key];
_setConfig(key, newValue);
return newValue;
}
/**
* @notice Execute address config update (with time delay enforced).
* @dev Needs to be called after the update was prepared. Fails if called before time delay is met.
* @return New value.
*/
function _executeAddress(bytes32 key) internal returns (address) {
_executeDeadline(key);
address newValue = pendingAddresses[key];
_setConfig(key, newValue);
return newValue;
}
function _setConfig(bytes32 key, address value) internal returns (address) {
address oldValue = currentAddresses[key];
currentAddresses[key] = value;
pendingAddresses[key] = address(0);
deadlines[key] = 0;
emit ConfigUpdatedAddress(key, oldValue, value);
return value;
}
function _setConfig(bytes32 key, uint256 value) internal returns (uint256) {
uint256 oldValue = currentUInts256[key];
currentUInts256[key] = value;
pendingUInts256[key] = 0;
deadlines[key] = 0;
emit ConfigUpdatedNumber(key, oldValue, value);
return value;
}
}
// File contracts/utils/IPausable.sol
pragma solidity 0.8.9;
interface IPausable {
function pause() external returns (bool);
function unpause() external returns (bool);
function isPaused() external view returns (bool);
function isAuthorizedToPause(address account) external view returns (bool);
}
// File libraries/Roles.sol
pragma solidity 0.8.9;
// solhint-disable private-vars-leading-underscore
library Roles {
bytes32 internal constant GOVERNANCE = "governance";
bytes32 internal constant ADDRESS_PROVIDER = "address_provider";
bytes32 internal constant POOL_FACTORY = "pool_factory";
bytes32 internal constant CONTROLLER = "controller";
bytes32 internal constant GAUGE_ZAP = "gauge_zap";
bytes32 internal constant MAINTENANCE = "maintenance";
bytes32 internal constant INFLATION_MANAGER = "inflation_manager";
bytes32 internal constant POOL = "pool";
bytes32 internal constant VAULT = "vault";
}
// File contracts/access/AuthorizationBase.sol
pragma solidity 0.8.9;
/**
* @notice Provides modifiers for authorization
*/
abstract contract AuthorizationBase {
/**
* @notice Only allows a sender with `role` to perform the given action
*/
modifier onlyRole(bytes32 role) {
require(_roleManager().hasRole(role, msg.sender), Error.UNAUTHORIZED_ACCESS);
_;
}
/**
* @notice Only allows a sender with GOVERNANCE role to perform the given action
*/
modifier onlyGovernance() {
require(_roleManager().hasRole(Roles.GOVERNANCE, msg.sender), Error.UNAUTHORIZED_ACCESS);
_;
}
/**
* @notice Only allows a sender with any of `roles` to perform the given action
*/
modifier onlyRoles2(bytes32 role1, bytes32 role2) {
require(_roleManager().hasAnyRole(role1, role2, msg.sender), Error.UNAUTHORIZED_ACCESS);
_;
}
/**
* @notice Only allows a sender with any of `roles` to perform the given action
*/
modifier onlyRoles3(
bytes32 role1,
bytes32 role2,
bytes32 role3
) {
require(
_roleManager().hasAnyRole(role1, role2, role3, msg.sender),
Error.UNAUTHORIZED_ACCESS
);
_;
}
function roleManager() external view virtual returns (IRoleManager) {
return _roleManager();
}
function _roleManager() internal view virtual returns (IRoleManager);
}
// File contracts/access/Authorization.sol
pragma solidity 0.8.9;
contract Authorization is AuthorizationBase {
IRoleManager internal immutable __roleManager;
constructor(IRoleManager roleManager) {
__roleManager = roleManager;
}
function _roleManager() internal view override returns (IRoleManager) {
return __roleManager;
}
}
// File contracts/vault/Vault.sol
pragma solidity 0.8.9;
abstract contract Vault is IVault, Authorization, VaultStorageV1, Preparable, Initializable {
using ScaledMath for uint256;
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableExtensions for EnumerableSet.AddressSet;
using EnumerableMapping for EnumerableMapping.AddressToUintMap;
using EnumerableExtensions for EnumerableMapping.AddressToUintMap;
using AddressProviderHelpers for IAddressProvider;
bytes32 internal constant _STRATEGY_KEY = "Strategy";
bytes32 internal constant _PERFORMANCE_FEE_KEY = "PerformanceFee";
bytes32 internal constant _STRATEGIST_FEE_KEY = "StrategistFee";
bytes32 internal constant _DEBT_LIMIT_KEY = "DebtLimit";
bytes32 internal constant _TARGET_ALLOCATION_KEY = "TargetAllocation";
bytes32 internal constant _RESERVE_FEE_KEY = "ReserveFee";
bytes32 internal constant _BOUND_KEY = "Bound";
uint256 internal constant _INITIAL_RESERVE_FEE = 0.01e18;
uint256 internal constant _INITIAL_STRATEGIST_FEE = 0.1e18;
uint256 internal constant _INITIAL_PERFORMANCE_FEE = 0;
uint256 public constant MAX_PERFORMANCE_FEE = 0.5e18;
uint256 public constant MAX_DEVIATION_BOUND = 0.5e18;
uint256 public constant STRATEGY_DELAY = 5 days;
IController public immutable controller;
IAddressProvider public immutable addressProvider;
IVaultReserve public immutable reserve;
modifier onlyPool() {
require(msg.sender == pool, Error.UNAUTHORIZED_ACCESS);
_;
}
modifier onlyPoolOrGovernance() {
require(
msg.sender == pool || _roleManager().hasRole(Roles.GOVERNANCE, msg.sender),
Error.UNAUTHORIZED_ACCESS
);
_;
}
modifier onlyPoolOrMaintenance() {
require(
msg.sender == pool || _roleManager().hasRole(Roles.MAINTENANCE, msg.sender),
Error.UNAUTHORIZED_ACCESS
);
_;
}
constructor(IController _controller)
Authorization(_controller.addressProvider().getRoleManager())
{
controller = _controller;
IAddressProvider addressProvider_ = _controller.addressProvider();
addressProvider = addressProvider_;
reserve = IVaultReserve(addressProvider_.getVaultReserve());
}
function _initialize(
address _pool,
uint256 _debtLimit,
uint256 _targetAllocation,
uint256 _bound
) internal {
require(_debtLimit <= ScaledMath.ONE, Error.INVALID_AMOUNT);
require(_targetAllocation <= ScaledMath.ONE, Error.INVALID_AMOUNT);
require(_bound <= MAX_DEVIATION_BOUND, Error.INVALID_AMOUNT);
pool = _pool;
_setConfig(_DEBT_LIMIT_KEY, _debtLimit);
_setConfig(_TARGET_ALLOCATION_KEY, _targetAllocation);
_setConfig(_BOUND_KEY, _bound);
_setConfig(_RESERVE_FEE_KEY, _INITIAL_RESERVE_FEE);
_setConfig(_STRATEGIST_FEE_KEY, _INITIAL_STRATEGIST_FEE);
_setConfig(_PERFORMANCE_FEE_KEY, _INITIAL_PERFORMANCE_FEE);
}
/**
* @notice Handles deposits from the liquidity pool
*/
function deposit() external payable override onlyPoolOrMaintenance {
// solhint-disable-previous-line ordering
_deposit();
}
/**
* @notice Withdraws specified amount of underlying from vault.
* @dev If the specified amount exceeds idle funds, an amount of funds is withdrawn
* from the strategy such that it will achieve a target allocation for after the
* amount has been withdrawn.
* @param amount Amount to withdraw.
* @return `true` if successful.
*/
function withdraw(uint256 amount) external override onlyPoolOrGovernance returns (bool) {
IStrategy strategy = getStrategy();
uint256 availableUnderlying_ = _availableUnderlying();
if (availableUnderlying_ < amount) {
if (address(strategy) == address(0)) return false;
uint256 allocated = strategy.balance();
uint256 requiredWithdrawal = amount - availableUnderlying_;
if (requiredWithdrawal > allocated) return false;
// compute withdrawal amount to sustain target allocation
uint256 newTarget = (allocated - requiredWithdrawal).scaledMul(getTargetAllocation());
uint256 excessAmount = allocated - newTarget;
strategy.withdraw(excessAmount);
currentAllocated = _computeNewAllocated(currentAllocated, excessAmount);
} else {
uint256 allocatedUnderlying = 0;
if (address(strategy) != address(0))
allocatedUnderlying = IStrategy(strategy).balance();
uint256 totalUnderlying = availableUnderlying_ +
allocatedUnderlying +
waitingForRemovalAllocated;
uint256 totalUnderlyingAfterWithdraw = totalUnderlying - amount;
_rebalance(totalUnderlyingAfterWithdraw, allocatedUnderlying);
}
_transfer(pool, amount);
return true;
}
/**
* @notice Withdraws all funds from vault and strategy and transfer them to the pool.
*/
function withdrawAll() external override onlyPoolOrGovernance {
_withdrawAllFromStrategy();
_transfer(pool, _availableUnderlying());
}
/**
* @notice Withdraws specified amount of underlying from reserve to vault.
* @dev Withdraws from reserve will cause a spike in pool exchange rate.
* Pool deposits should be paused during this to prevent front running
* @param amount Amount to withdraw.
*/
function withdrawFromReserve(uint256 amount) external override onlyGovernance {
require(amount > 0, Error.INVALID_AMOUNT);
require(IPausable(pool).isPaused(), Error.POOL_NOT_PAUSED);
uint256 reserveBalance_ = reserve.getBalance(address(this), getUnderlying());
require(amount <= reserveBalance_, Error.INSUFFICIENT_BALANCE);
reserve.withdraw(getUnderlying(), amount);
}
/**
* @notice Activate the current strategy set for the vault.
* @return `true` if strategy has been activated
*/
function activateStrategy() external onlyGovernance returns (bool) {
return _activateStrategy();
}
/**
* @notice Deactivates a strategy.
* @return `true` if strategy has been deactivated
*/
function deactivateStrategy() external onlyGovernance returns (bool) {
return _deactivateStrategy();
}
/**
* @notice Initializes the vault's strategy.
* @dev Bypasses the time delay, but can only be called if strategy is not set already.
* @param strategy_ Address of the strategy.
* @return `true` if successful.
*/
function initializeStrategy(address strategy_) external override onlyGovernance returns (bool) {
require(currentAddresses[_STRATEGY_KEY] == address(0), Error.ADDRESS_ALREADY_SET);
require(strategy_ != address(0), Error.ZERO_ADDRESS_NOT_ALLOWED);
_setConfig(_STRATEGY_KEY, strategy_);
_activateStrategy();
require(IStrategy(strategy_).strategist() != address(0), Error.ZERO_ADDRESS_NOT_ALLOWED);
return true;
}
/**
* @notice Prepare update of the vault's strategy (with time delay enforced).
* @param newStrategy Address of the new strategy.
* @return `true` if successful.
*/
function prepareNewStrategy(address newStrategy) external onlyGovernance returns (bool) {
return _prepare(_STRATEGY_KEY, newStrategy, STRATEGY_DELAY);
}
/**
* @notice Execute strategy update (with time delay enforced).
* @dev Needs to be called after the update was prepraed. Fails if called before time delay is met.
* @return New strategy address.
*/
function executeNewStrategy() external returns (address) {
_executeDeadline(_STRATEGY_KEY);
IStrategy strategy = getStrategy();
if (address(strategy) != address(0)) {
_harvest();
strategy.shutdown();
strategy.withdrawAll();
// there might still be some balance left if the strategy did not
// manage to withdraw all funds (e.g. due to locking)
uint256 remainingStrategyBalance = strategy.balance();
if (remainingStrategyBalance > 0) {
_strategiesWaitingForRemoval.set(address(strategy), remainingStrategyBalance);
waitingForRemovalAllocated += remainingStrategyBalance;
}
}
_deactivateStrategy();
currentAllocated = 0;
totalDebt = 0;
address newStrategy = pendingAddresses[_STRATEGY_KEY];
_setConfig(_STRATEGY_KEY, newStrategy);
if (newStrategy != address(0)) {
_activateStrategy();
}
return newStrategy;
}
function resetNewStrategy() external onlyGovernance returns (bool) {
return _resetAddressConfig(_STRATEGY_KEY);
}
/**
* @notice Prepare update of performance fee (with time delay enforced).
* @param newPerformanceFee New performance fee value.
* @return `true` if successful.
*/
function preparePerformanceFee(uint256 newPerformanceFee)
external
onlyGovernance
returns (bool)
{
require(newPerformanceFee <= MAX_PERFORMANCE_FEE, Error.INVALID_AMOUNT);
return _prepare(_PERFORMANCE_FEE_KEY, newPerformanceFee);
}
/**
* @notice Execute update of performance fee (with time delay enforced).
* @dev Needs to be called after the update was prepraed. Fails if called before time delay is met.
* @return New performance fee.
*/
function executePerformanceFee() external returns (uint256) {
return _executeUInt256(_PERFORMANCE_FEE_KEY);
}
function resetPerformanceFee() external onlyGovernance returns (bool) {
return _resetUInt256Config(_PERFORMANCE_FEE_KEY);
}
/**
* @notice Prepare update of strategist fee (with time delay enforced).
* @param newStrategistFee New strategist fee value.
* @return `true` if successful.
*/
function prepareStrategistFee(uint256 newStrategistFee) external onlyGovernance returns (bool) {
_checkFeesInvariant(getReserveFee(), newStrategistFee);
return _prepare(_STRATEGIST_FEE_KEY, newStrategistFee);
}
/**
* @notice Execute update of strategist fee (with time delay enforced).
* @dev Needs to be called after the update was prepraed. Fails if called before time delay is met.
* @return New strategist fee.
*/
function executeStrategistFee() external returns (uint256) {
uint256 newStrategistFee = _executeUInt256(_STRATEGIST_FEE_KEY);
_checkFeesInvariant(getReserveFee(), newStrategistFee);
return newStrategistFee;
}
function resetStrategistFee() external onlyGovernance returns (bool) {
return _resetUInt256Config(_STRATEGIST_FEE_KEY);
}
/**
* @notice Prepare update of debt limit (with time delay enforced).
* @param newDebtLimit New debt limit.
* @return `true` if successful.
*/
function prepareDebtLimit(uint256 newDebtLimit) external onlyGovernance returns (bool) {
return _prepare(_DEBT_LIMIT_KEY, newDebtLimit);
}
/**
* @notice Execute update of debt limit (with time delay enforced).
* @dev Needs to be called after the update was prepraed. Fails if called before time delay is met.
* @return New debt limit.
*/
function executeDebtLimit() external returns (uint256) {
uint256 debtLimit = _executeUInt256(_DEBT_LIMIT_KEY);
uint256 debtLimitAllocated = currentAllocated.scaledMul(debtLimit);
if (totalDebt >= debtLimitAllocated) {
_handleExcessDebt();
}
return debtLimit;
}
function resetDebtLimit() external onlyGovernance returns (bool) {
return _resetUInt256Config(_DEBT_LIMIT_KEY);
}
/**
* @notice Prepare update of target allocation (with time delay enforced).
* @param newTargetAllocation New target allocation.
* @return `true` if successful.
*/
function prepareTargetAllocation(uint256 newTargetAllocation)
external
onlyGovernance
returns (bool)
{
return _prepare(_TARGET_ALLOCATION_KEY, newTargetAllocation);
}
/**
* @notice Execute update of target allocation (with time delay enforced).
* @dev Needs to be called after the update was prepraed. Fails if called before time delay is met.
* @return New target allocation.
*/
function executeTargetAllocation() external returns (uint256) {
uint256 targetAllocation = _executeUInt256(_TARGET_ALLOCATION_KEY);
_deposit();
return targetAllocation;
}
function resetTargetAllocation() external onlyGovernance returns (bool) {
return _resetUInt256Config(_TARGET_ALLOCATION_KEY);
}
/**
* @notice Prepare update of reserve fee (with time delay enforced).
* @param newReserveFee New reserve fee.
* @return `true` if successful.
*/
function prepareReserveFee(uint256 newReserveFee) external onlyGovernance returns (bool) {
_checkFeesInvariant(newReserveFee, getStrategistFee());
return _prepare(_RESERVE_FEE_KEY, newReserveFee);
}
/**
* @notice Execute update of reserve fee (with time delay enforced).
* @dev Needs to be called after the update was prepraed. Fails if called before time delay is met.
* @return New reserve fee.
*/
function executeReserveFee() external returns (uint256) {
uint256 newReserveFee = _executeUInt256(_RESERVE_FEE_KEY);
_checkFeesInvariant(newReserveFee, getStrategistFee());
return newReserveFee;
}
function resetReserveFee() external onlyGovernance returns (bool) {
return _resetUInt256Config(_RESERVE_FEE_KEY);
}
/**
* @notice Prepare update of deviation bound for strategy allocation (with time delay enforced).
* @param newBound New deviation bound for target allocation.
* @return `true` if successful.
*/
function prepareBound(uint256 newBound) external onlyGovernance returns (bool) {
require(newBound <= MAX_DEVIATION_BOUND, Error.INVALID_AMOUNT);
return _prepare(_BOUND_KEY, newBound);
}
/**
* @notice Execute update of deviation bound for strategy allocation (with time delay enforced).
* @dev Needs to be called after the update was prepraed. Fails if called before time delay is met.
* @return New deviation bound.
*/
function executeBound() external returns (uint256) {
uint256 bound = _executeUInt256(_BOUND_KEY);
_deposit();
return bound;
}
function resetBound() external onlyGovernance returns (bool) {
return _resetUInt256Config(_BOUND_KEY);
}
/**
* @notice Withdraws an amount of underlying from the strategy to the vault.
* @param amount Amount of underlying to withdraw.
* @return True if successful withdrawal.
*/
function withdrawFromStrategy(uint256 amount) external onlyGovernance returns (bool) {
IStrategy strategy = getStrategy();
if (address(strategy) == address(0)) return false;
if (strategy.balance() < amount) return false;
uint256 oldBalance = _availableUnderlying();
strategy.withdraw(amount);
uint256 newBalance = _availableUnderlying();
currentAllocated -= newBalance - oldBalance;
return true;
}
function withdrawFromStrategyWaitingForRemoval(address strategy) external returns (uint256) {
(bool exists, uint256 allocated) = _strategiesWaitingForRemoval.tryGet(strategy);
require(exists, Error.STRATEGY_DOES_NOT_EXIST);
IStrategy strategy_ = IStrategy(strategy);
strategy_.harvest();
uint256 withdrawn = strategy_.withdrawAll();
uint256 _waitingForRemovalAllocated = waitingForRemovalAllocated;
if (withdrawn >= _waitingForRemovalAllocated) {
waitingForRemovalAllocated = 0;
} else {
waitingForRemovalAllocated = _waitingForRemovalAllocated - withdrawn;
}
if (withdrawn > allocated) {
uint256 profit = withdrawn - allocated;
uint256 strategistShare = _shareFees(profit.scaledMul(getPerformanceFee()));
if (strategistShare > 0) {
_payStrategist(strategistShare, strategy_.strategist());
}
allocated = 0;
emit Harvest(profit, 0);
} else {
allocated -= withdrawn;
}
if (strategy_.balance() == 0) {
_strategiesWaitingForRemoval.remove(address(strategy_));
} else {
_strategiesWaitingForRemoval.set(address(strategy_), allocated);
}
return withdrawn;
}
function getStrategiesWaitingForRemoval() external view returns (address[] memory) {
return _strategiesWaitingForRemoval.keysArray();
}
/**
* @notice Computes the total underlying of the vault: idle funds + allocated funds - debt
* @return Total amount of underlying.
*/
function getTotalUnderlying() external view override returns (uint256) {
uint256 availableUnderlying_ = _availableUnderlying();
if (address(getStrategy()) == address(0)) {
return availableUnderlying_;
}
uint256 netUnderlying = availableUnderlying_ +
currentAllocated +
waitingForRemovalAllocated;
if (totalDebt <= netUnderlying) return netUnderlying - totalDebt;
return 0;
}
function getAllocatedToStrategyWaitingForRemoval(address strategy)
external
view
returns (uint256)
{
return _strategiesWaitingForRemoval.get(strategy);
}
/**
* @notice Withdraws all funds from strategy to vault.
* @dev Harvests profits before withdrawing. Deactivates strategy after withdrawing.
* @return `true` if successful.
*/
function withdrawAllFromStrategy() public onlyPoolOrGovernance returns (bool) {
return _withdrawAllFromStrategy();
}
/**
* @notice Harvest profits from the vault's strategy.
* @dev Harvesting adds profits to the vault's balance and deducts fees.
* No performance fees are charged on profit used to repay debt.
* @return `true` if successful.
*/
function harvest() public onlyPoolOrMaintenance returns (bool) {
return _harvest();
}
/**
* @notice Returns the percentage of the performance fee that goes to the strategist.
*/
function getStrategistFee() public view returns (uint256) {
return currentUInts256[_STRATEGIST_FEE_KEY];
}
function getStrategy() public view override returns (IStrategy) {
return IStrategy(currentAddresses[_STRATEGY_KEY]);
}
/**
* @notice Returns the percentage of the performance fee which is allocated to the vault reserve
*/
function getReserveFee() public view returns (uint256) {
return currentUInts256[_RESERVE_FEE_KEY];
}
/**
* @notice Returns the fee charged on a strategy's generated profits.
* @dev The strategist is paid in LP tokens, while the remainder of the profit stays in the vault.
* Default performance fee is set to 5% of harvested profits.
*/
function getPerformanceFee() public view returns (uint256) {
return currentUInts256[_PERFORMANCE_FEE_KEY];
}
/**
* @notice Returns the allowed symmetric bound for target allocation (e.g. +- 5%)
*/
function getBound() public view returns (uint256) {
return currentUInts256[_BOUND_KEY];
}
/**
* @notice The target percentage of total underlying funds to be allocated towards a strategy.
* @dev this is to reduce gas costs. Withdrawals first come from idle funds and can therefore
* avoid unnecessary gas costs.
*/
function getTargetAllocation() public view returns (uint256) {
return currentUInts256[_TARGET_ALLOCATION_KEY];
}
/**
* @notice The debt limit that the total debt of a strategy may not exceed.
*/
function getDebtLimit() public view returns (uint256) {
return currentUInts256[_DEBT_LIMIT_KEY];
}
function getUnderlying() public view virtual override returns (address);
function _activateStrategy() internal returns (bool) {
IStrategy strategy = getStrategy();
if (address(strategy) == address(0)) return false;
strategyActive = true;
emit StrategyActivated(address(strategy));
_deposit();
return true;
}
function _harvest() internal returns (bool) {
IStrategy strategy = getStrategy();
if (address(strategy) == address(0)) {
return false;
}
strategy.harvest();
uint256 strategistShare = 0;
uint256 allocatedUnderlying = strategy.balance();
uint256 amountAllocated = currentAllocated;
uint256 currentDebt = totalDebt;
if (allocatedUnderlying > amountAllocated) {
// we made profits
uint256 profit = allocatedUnderlying - amountAllocated;
if (profit > currentDebt) {
if (currentDebt > 0) {
profit -= currentDebt;
currentDebt = 0;
}
(profit, strategistShare) = _shareProfit(profit);
} else {
currentDebt -= profit;
}
emit Harvest(profit, 0);
} else if (allocatedUnderlying < amountAllocated) {
// we made a loss
uint256 loss = amountAllocated - allocatedUnderlying;
currentDebt += loss;
// check debt limit and withdraw funds if exceeded
uint256 debtLimit = getDebtLimit();
uint256 debtLimitAllocated = amountAllocated.scaledMul(debtLimit);
if (currentDebt > debtLimitAllocated) {
currentDebt = _handleExcessDebt(currentDebt);
}
emit Harvest(0, loss);
} else {
// nothing to declare
return true;
}
totalDebt = currentDebt;
currentAllocated = strategy.balance();
if (strategistShare > 0) {
_payStrategist(strategistShare);
}
return true;
}
function _withdrawAllFromStrategy() internal returns (bool) {
IStrategy strategy = getStrategy();
if (address(strategy) == address(0)) return false;
_harvest();
uint256 oldBalance = _availableUnderlying();
strategy.withdrawAll();
uint256 newBalance = _availableUnderlying();
uint256 withdrawnAmount = newBalance - oldBalance;
currentAllocated = _computeNewAllocated(currentAllocated, withdrawnAmount);
_deactivateStrategy();
return true;
}
function _handleExcessDebt(uint256 currentDebt) internal returns (uint256) {
uint256 underlyingReserves = reserve.getBalance(address(this), getUnderlying());
if (currentDebt > underlyingReserves) {
_emergencyStop(underlyingReserves);
} else if (reserve.canWithdraw(address(this))) {
reserve.withdraw(getUnderlying(), currentDebt);
currentDebt = 0;
_deposit();
}
return currentDebt;
}
function _handleExcessDebt() internal {
uint256 currentDebt = totalDebt;
uint256 newDebt = _handleExcessDebt(totalDebt);
if (currentDebt != newDebt) {
totalDebt = newDebt;
}
}
/**
* @notice Invest the underlying money in the vault after a deposit from the pool is made.
* @dev After each deposit, the vault checks whether it needs to rebalance underlying funds allocated to strategy.
* If no strategy is set then all deposited funds will be idle.
*/
function _deposit() internal {
if (!strategyActive) return;
uint256 allocatedUnderlying = getStrategy().balance();
uint256 totalUnderlying = _availableUnderlying() +
allocatedUnderlying +
waitingForRemovalAllocated;
if (totalUnderlying == 0) return;
_rebalance(totalUnderlying, allocatedUnderlying);
}
function _shareProfit(uint256 profit) internal returns (uint256, uint256) {
uint256 totalFeeAmount = profit.scaledMul(getPerformanceFee());
if (_availableUnderlying() < totalFeeAmount) {
getStrategy().withdraw(totalFeeAmount);
}
uint256 strategistShare = _shareFees(totalFeeAmount);
return ((profit - totalFeeAmount), strategistShare);
}
function _shareFees(uint256 totalFeeAmount) internal returns (uint256) {
uint256 strategistShare = totalFeeAmount.scaledMul(getStrategistFee());
uint256 reserveShare = totalFeeAmount.scaledMul(getReserveFee());
uint256 treasuryShare = totalFeeAmount - strategistShare - reserveShare;
_depositToReserve(reserveShare);
if (treasuryShare > 0) {
_depositToTreasury(treasuryShare);
}
return strategistShare;
}
function _emergencyStop(uint256 underlyingReserves) internal {
// debt limit exceeded: withdraw funds from strategy
uint256 withdrawn = getStrategy().withdrawAll();
uint256 actualDebt = _computeNewAllocated(currentAllocated, withdrawn);
if (reserve.canWithdraw(address(this))) {
// check if debt can be covered with reserve funds
if (underlyingReserves >= actualDebt) {
reserve.withdraw(getUnderlying(), actualDebt);
} else if (underlyingReserves > 0) {
// debt can not be covered with reserves
reserve.withdraw(getUnderlying(), underlyingReserves);
}
}
// too much money lost, stop the strategy
_deactivateStrategy();
}
/**
* @notice Deactivates a strategy. All positions of the strategy are exited.
* @return `true` if strategy has been deactivated
*/
function _deactivateStrategy() internal returns (bool) {
if (!strategyActive) return false;
strategyActive = false;
emit StrategyDeactivated(address(getStrategy()));
return true;
}
function _payStrategist(uint256 amount) internal {
_payStrategist(amount, getStrategy().strategist());
}
function _payStrategist(uint256 amount, address strategist) internal virtual;
function _transfer(address to, uint256 amount) internal virtual;
function _depositToReserve(uint256 amount) internal virtual;
function _depositToTreasury(uint256 amount) internal virtual;
function _availableUnderlying() internal view virtual returns (uint256);
function _computeNewAllocated(uint256 allocated, uint256 withdrawn)
internal
pure
returns (uint256)
{
if (allocated > withdrawn) {
return allocated - withdrawn;
}
return 0;
}
function _checkFeesInvariant(uint256 reserveFee, uint256 strategistFee) internal pure {
require(
reserveFee + strategistFee <= ScaledMath.ONE,
"sum of strategist fee and reserve fee should be below 1"
);
}
function _rebalance(uint256 totalUnderlying, uint256 allocatedUnderlying)
private
returns (bool)
{
if (!strategyActive) return false;
uint256 targetAllocation = getTargetAllocation();
IStrategy strategy = getStrategy();
uint256 bound = getBound();
uint256 target = totalUnderlying.scaledMul(targetAllocation);
uint256 upperBound = targetAllocation == 0 ? 0 : targetAllocation + bound;
upperBound = upperBound > ScaledMath.ONE ? ScaledMath.ONE : upperBound;
uint256 lowerBound = bound > targetAllocation ? 0 : targetAllocation - bound;
if (allocatedUnderlying > totalUnderlying.scaledMul(upperBound)) {
// withdraw funds from strategy
uint256 withdrawAmount = allocatedUnderlying - target;
strategy.withdraw(withdrawAmount);
currentAllocated = _computeNewAllocated(currentAllocated, withdrawAmount);
} else if (allocatedUnderlying < totalUnderlying.scaledMul(lowerBound)) {
// allocate more funds to strategy
uint256 depositAmount = target - allocatedUnderlying;
_transfer(address(strategy), depositAmount);
currentAllocated += depositAmount;
strategy.deposit();
}
return true;
}
}
// File contracts/vault/EthVault.sol
pragma solidity 0.8.9;
contract EthVault is Vault {
using AddressProviderHelpers for IAddressProvider;
address private constant _UNDERLYING = address(0);
constructor(IController controller) Vault(controller) {}
receive() external payable {}
function initialize(
address _pool,
uint256 _debtLimit,
uint256 _targetAllocation,
uint256 _bound
) external virtual override initializer {
_initialize(_pool, _debtLimit, _targetAllocation, _bound);
}
function getUnderlying() public pure override returns (address) {
return _UNDERLYING;
}
function _transfer(address to, uint256 amount) internal override {
payable(to).transfer(amount);
}
function _depositToReserve(uint256 amount) internal override {
reserve.deposit{value: amount}(_UNDERLYING, amount);
}
function _depositToTreasury(uint256 amount) internal override {
payable(addressProvider.getTreasury()).transfer(amount);
}
function _payStrategist(uint256 amount, address strategist) internal override {
if (strategist == address(0)) return;
ILiquidityPool(pool).depositFor{value: amount}(strategist, amount);
}
function _availableUnderlying() internal view override returns (uint256) {
return address(this).balance;
}
}
|
Tries to returns the value associated with `key`. O(1). Does not revert if `key` is not in the map. _Available since v3.4._/
|
function tryGet(Bytes32ToUIntMap storage map, bytes32 key)
internal
view
returns (bool, uint256)
{
(bool success, bytes32 value) = _tryGet(map._inner, key);
return (success, uint256(value));
}
| 6,638,978
|
// SPDX-License-Identifier: MIT
// Created by Flux Team
pragma solidity 0.6.8;
import "./FluxStorage.sol";
import "./market/Interface.sol";
import "./lib/Ownable.sol";
import "./lib/Exponential.sol";
import "./lib/SafeMath.sol";
import "./lib/EnumerableSet.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/upgrades/contracts/Initializable.sol";
/**
@title Flux-去中心借贷平台
@dev Flux协议实现的核心,所有业务围绕 FluxApp 实现。
*/
contract FluxApp is Ownable, Initializable, AppStroageV3 {
using Exponential for Exp;
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
uint256 private constant DECIMAL_UNIT = 1e18;
string private constant CONFIG_TEAM_INCOME_ADDRESS = "FLUX_TEAM_INCOME_ADDRESS";
string private constant CONFIG_TAX_RATE = "MKT_BORROW_INTEREST_TAX_RATE";
string private constant CONFIG_LIQUIDITY_RATE = "MKT_LIQUIDATION_FEE_RATE";
/**
@notice 市场状态被改变
@param market 被改变的借贷市场
@param oldStatus 改变前的市场状态
@param newStatus 改变后的市场状态
*/
event MarketStatusChagned(IMarket market, MarketStatus oldStatus, MarketStatus newStatus);
/**
@notice 参数变更事件
@dev 表示 APP 所存储的可扩展参数 `mapping<string=>uint256> configs` 内容发生变化。
@param item 变更项
@param oldValue 变更前的值
@param newValue 变更后的值
*/
event ConfigChanged(string item, uint256 oldValue, uint256 newValue);
/**
@notice 新的借贷市场被批准
@dev 当一个新的市场在 Flux 被授权加入,FluxApp 合约将产生 MarketApproved 事件。
@param market 被授权加入的新借贷市场合约地址;
@param collRatioMan 该借贷市场借款抵押率(尾数)。
*/
event MarketApproved(IMarket market, uint256 collRatioMan);
/**
@notice 借贷市场被移除事件
@param market 被移除的借贷市场合约地址
*/
event MarketRemoved(IMarket market);
/**
@notice 借贷市场的抵押率修改事件
@param market 被修改的借贷市场
@param oldValue 修改前的抵押率(尾数)
@param newValue 修改后的抵押率(尾数)
*/
event MarketCollRationChanged(IMarket market, uint256 oldValue, uint256 newValue);
event FluxMintChanged(FluxMint oldValue, FluxMint newValue);
event StakePoolApproved(IStake pool, uint256 weights);
event StakePoolStatusChanged(IStake indexed pool, MarketStatus oldValue, MarketStatus newValue);
event StakePoolBorrowLimitChanged(IStake indexed pool, uint256 oldValue, uint256 newValue);
event StakePoolRemoved(IStake indexed pool);
/**
@notice 初始化合约
@dev 部署合约后需要在第一时间调用初始化合约,以便将信息在业务实施前设置。
@param admin 管理员
*/
function initialize(address admin) external initializer {
initOwner(admin);
address incomeAddr = 0xd34008Af58BA1DC1e1E8d8804f2BF745A18f38Bd;
configs[CONFIG_TEAM_INCOME_ADDRESS] = uint256(incomeAddr);
configs[CONFIG_TAX_RATE] = 0.1 * 1e18; //10%
configs[CONFIG_LIQUIDITY_RATE] = 0.06 * 1e18; //6%
}
/**
@notice 管理员修改配置项
@dev 当前保留的存储信息,以便后续向 Flux 追加若干个配置项。
@param item 配置项
@param newValue 新值
*/
function setConfig(string calldata item, uint256 newValue) external onlyOwner {
uint256 old = configs[item];
require(old != newValue, "NOTHING_MODIFIED");
configs[item] = newValue;
emit ConfigChanged(item, old, newValue);
}
/**
* @notice 管理员批准指定的借贷市场进入Flux
* @dev 这仅仅是在平台中批准借贷市场进入,但默认禁止操作的。需要在风控`Risk`中开启市场交易。
* @param market 需要批准的借贷市场合约地址。
* @param collRatioMan 该借贷市场的抵押率(尾数),必须大于 100%。
*/
function approveMarket(IMarket market, uint256 collRatioMan) external onlyOwner {
require(market.isFluxMarket(), "NO_FLUX_MARKET");
// 不允许重复
require(markets[market].status == MarketStatus.Unknown, "MARKET_REPEAT");
// 抵押率必须大于 100%
require(1 * 1e18 < collRatioMan, "INVLIAD_COLLATERAL_RATE");
// 检查风控是否已经允许该市场进入
//check repeat
address underlying = address(market.underlying());
require(supportTokens[underlying] == address(0), "UNDERLYING_REPEAT");
markets[market] = Market(MarketStatus.Opened, collRatioMan);
marketList.push(market);
supportTokens[underlying] = address(market);
emit MarketApproved(market, collRatioMan);
}
/**
* @notice 重置借贷市场的抵押率
* @param market 需要修改的借贷市场合约地址。
* @param collRatioMan 该借贷市场的抵押率,必须大于 100%。
*/
function resetCollRatio(IMarket market, uint256 collRatioMan) external onlyOwner {
Market storage info = markets[market];
//不允许重复
require(info.status != MarketStatus.Unknown, "MARKET_NOT_OPENED");
require(info.collRatioMan != collRatioMan, "NOTHING_MODIFIED");
// 抵押率必须大于 100%
require(1e18 < collRatioMan, "INVLIAD_COLLATERAL_RATE");
uint256 old = info.collRatioMan;
markets[market].collRatioMan = collRatioMan;
emit MarketCollRationChanged(market, old, collRatioMan);
}
/**
* @notice 移除指定的借贷市场
* @dev 移除前请确保市场状态已经是 Killed,不得随意移除市场。
* @param market 待移除的借贷市场
*/
function removeMarket(IMarket market) external onlyOwner {
Market storage mkt = markets[market];
require(mkt.status == MarketStatus.Stopped, "MARKET_NOT_STOPPED");
IERC20 underlying = market.underlying();
require(underlying.balanceOf(address(market)) == 0, "MARKET_NOT_EMPTYE");
//在移除前必须确保市场已经 Kill
mkt.status = MarketStatus.Unknown;
mkt.collRatioMan = 0;
delete markets[market];
delete supportTokens[address(market.underlying())];
emit MarketRemoved(market);
fluxMiner.removePool(address(market));
// remove market from marketList
uint256 len = marketList.length;
for (uint256 i = 0; i < len; i++) {
if (marketList[i] == market) {
//find
if (i != len - 1) {
marketList[i] = marketList[len - 1];
}
marketList.pop();
break;
}
}
}
/**
* @notice 查询指定的借贷市场信息
* @param market 待查询的借贷市场
* @return ratio 该借贷市场抵押率
* @return status 该借贷市场状态(MarketStatus:Unknown、Opened、Stopped、Killed)
*/
function marketStatus(IMarket market) public view returns (uint256 ratio, MarketStatus status) {
Market storage mkt = markets[market];
return (mkt.collRatioMan, mkt.status);
}
struct ValuesVars {
address user;
uint256 supplyValueMan;
uint256 borrowValueMan;
uint256 borrowLimitMan;
}
/**
@dev 计算指定账户的资产信息,在计算时可以添加借款或存款来动态计算最终的借贷和抵押数据
⚠️ 因为计算结果是放大18倍,如果是存在一个天文的借贷信息,则会导致因为数据越界而无法累加。
@return supplyValueMan 存款额(尾数)
@return borrowValueMan 借款额(尾数)
@return borrowLimitMan 借款限额(尾数)
*/
function _calcAcct(
address acct,
address targetMarket,
uint256 addBorrows,
uint256 subSupplies
)
internal
view
returns (
uint256 supplyValueMan,
uint256 borrowValueMan,
uint256 borrowLimitMan
)
{
require(acct != address(0), "ADDRESS_IS_EMPTY");
uint256 len = marketList.length;
ValuesVars memory varsSum;
ValuesVars memory vars;
vars.user = acct;
uint256 b;
uint256 s;
// 这里不限制数量,而是在进入市场时限制
for (uint256 i = 0; i < len; i++) {
IMarket m = marketList[i];
if (address(m) == targetMarket) {
b = addBorrows;
s = subSupplies;
} else {
(b, s) = (0, 0);
}
(vars.supplyValueMan, vars.borrowValueMan, vars.borrowLimitMan) = m.accountValues(vars.user, markets[m].collRatioMan, b, s);
varsSum.supplyValueMan = varsSum.supplyValueMan.add(vars.supplyValueMan);
varsSum.borrowValueMan = varsSum.borrowValueMan.add(vars.borrowValueMan);
varsSum.borrowLimitMan = varsSum.borrowLimitMan.add(vars.borrowLimitMan);
}
return (varsSum.supplyValueMan, varsSum.borrowValueMan, varsSum.borrowLimitMan);
}
/**
* @notice 查询账户借贷信息
* @dev 一次性查询指定账户的借贷信息
* @param acct 待查询账户
* @return supplyValueMan uint256 存款额(尾数)
* @return borrowValueMan uint256 借款额(尾数)
* @return borrowLimitMan uint256 所需要的抵押额(尾数)
*/
function getAcctSnapshot(address acct)
public
view
returns (
uint256 supplyValueMan,
uint256 borrowValueMan,
uint256 borrowLimitMan
)
{
return _calcAcct(acct, address(0), 0, 0);
}
/**
@notice 计算借款发生后账户的借贷信息
@param borrower 借款人
@param borrowMkt 借款市场
@param amount 借款数量
*/
function calcBorrow(
address borrower,
address borrowMkt,
uint256 amount
)
public
view
returns (
uint256 supplyValueMan,
uint256 borrowValueMan,
uint256 borrowLimitMan
)
{
return _calcAcct(borrower, borrowMkt, amount, 0);
}
/**
@notice 返回是否允许清算人清算借款人资产
@param borrower 借款人
*/
function liquidateAllowed(address borrower) public view returns (bool yes) {
require(!liquidateDisabled, "RISK_LIQUIDATE_DISABLED");
require(!creditBorrowers[borrower], "BORROWER_IS_CERDITLOAN");
ValuesVars memory vars;
(vars.supplyValueMan, vars.borrowValueMan, vars.borrowLimitMan) = getAcctSnapshot(borrower);
if (vars.borrowValueMan == 0) {
return false;
}
//当实时抵押率跌至清算抵押率时可以被清算
// 存款额/借款 < 清算抵押率
return Exp(vars.supplyValueMan).div(Exp(vars.borrowValueMan)).mantissa < CLOSE_FACTOR_MANTISSA;
}
/**
@notice 登记账户进入/离开的市场集合
@dev 记录的目的是,在统计账户借贷资产时,无需遍历所有市场进行查找。仅需要遍历已登记的市场即可。
同时,对于每个借贷市场会记录所有曾经进入过的账户清单(增量)。
该记录将会自动在借贷活动中由风控事件来执行。该方法只能被借贷市场调研
@param acct address,待登记的账户地址
@dev 只能被已加入的市场调研
*/
function setAcctMarket(address acct, bool join) external {
IMarket market = IMarket(msg.sender); //call from Market
require(markets[market].status == MarketStatus.Opened, "MARKET_NOT_OPENED");
EnumerableSet.AddressSet storage set = acctJoinedMkts[acct];
if (!join) {
//实时清理数据
set.remove(address(market));
delete markets[market].accountMembership[acct];
} else {
//重复添加时返回FALSE,如果成功添加,则判断是否超出数量限制,如果是则返回错误
if (set.add(address(market))) {
require(set.length() <= JOINED_MKT_LIMIT, "JOIN_TOO_MATCH");
//进入市场
markets[market].accountMembership[acct] = true;
}
}
}
/**
@notice 借贷市场数量
@return uint256 返回当前平台中借贷市场的个数。
*/
function mktCount() external view returns (uint256) {
return marketList.length;
}
/**
* @notice 查询借贷市场是否已开启
*/
function mktExist(IMarket mkt) external view returns (bool) {
return markets[mkt].status == MarketStatus.Opened;
}
function getJoinedMktInfoAt(address acct, uint256 index) external view returns (IMarket mkt, uint256 collRatioMan) {
mkt = IMarket(acctJoinedMkts[acct].at(index));
collRatioMan = markets[mkt].collRatioMan;
}
function getAcctJoinedMktCount(address acct) external view returns (uint256) {
return acctJoinedMkts[acct].length();
}
/**
@notice 修改铸币(存款)可操作状态
@param disable 为 TRUE 则禁用 Supply,否则解禁 Supply。
*/
function changeSupplyStatus(bool disable) external onlyOwner {
require(disableSupply != disable, "NOTHING_MODIFIED");
disableSupply = disable;
emit ConfigChanged("DISABLE_SUPPLY", disable ? 1 : 0, disable ? 0 : 1);
}
/**
@notice 修改借币可操作状态
@param disable 为 TRUE 则禁用 Borrow,否则解禁 Borrow。
*/
function changeBorrowStatus(bool disable) external onlyOwner {
require(disableBorrow != disable, "NOTHING_MODIFIED");
disableBorrow = disable;
emit ConfigChanged("DISABLE_BORROW", disable ? 1 : 0, disable ? 0 : 1);
}
/**
@notice 修改清算可操作状态
*/
function changeLiquidateStatus(bool disable) external onlyOwner {
require(liquidateDisabled != disable, "NOTHING_MODIFIED");
liquidateDisabled = disable;
emit ConfigChanged("DISABLE_LIQUIDATE", disable ? 1 : 0, disable ? 0 : 1);
}
/**
@notice 修改借币可操作状态
@param disable 为 TRUE 则禁用 Supply,否则解禁 Supply。
*/
function changeAllActionStatus(bool disable) external onlyOwner {
require(lockAllAction != disable, "NOTHING_MODIFIED");
lockAllAction = disable;
emit ConfigChanged("DISABLE_ALL_ACTION", disable ? 1 : 0, disable ? 0 : 1);
}
/**
@notice 设置市场状态
@dev 市场状态有四种(Unkown,Opend,Stopped,Killed),其修改状态顺序有一定规则。
@param market 待修改状态的市场地址
@param status 市场新状态
*/
function setMarketStatus(IMarket market, MarketStatus status) external onlyOwner {
Market storage mkt = markets[market];
MarketStatus old = mkt.status;
require(status != MarketStatus.Unknown, "INVLIAD_MARKET_STATUS");
require(old != status, "INVLIAD_MARKET_STATUS");
require(status <= MarketStatus.Stopped, "INVLIAD_MARKET_STATUS");
mkt.status = status;
emit MarketStatusChagned(market, old, status);
}
/**
* @notice 修改借款限额
*/
function setBorrowLimit(address[] calldata pools, uint256[] calldata limit) external onlyOwner {
require(pools.length == limit.length, "INVLIAD_PARAMS");
for (uint256 i = 0; i < pools.length; i++) {
address pool = pools[i];
uint256 oldValue = poolBorrowLimit[pool];
uint256 newValue = limit[i];
poolBorrowLimit[pool] = newValue;
emit StakePoolBorrowLimitChanged(IStake(pool), oldValue, newValue);
}
}
/**
@notice 检查用户是否能够取款
@dev 当用户取款时将需要检查用户所有用的资产能否足够取款,且在取款时借款抵押的资产不允许取走。
将根据实时的资产价格计算用户资产,以检查用户的借款抵押率是否低于 `TOKEN_INSUFFICIENT_ALLOWANCE`
@param acct 待检查的用户地址
*/
function redeemAllowed(
address acct,
address mkt,
uint256 ftokens
) public view {
ValuesVars memory vars;
(vars.supplyValueMan, vars.borrowValueMan, vars.borrowLimitMan) = _calcAcct(acct, mkt, 0, ftokens);
if (vars.borrowValueMan == 0) {
return;
}
// 借款限额被使用完则表示抵押不足,不得取款
require(vars.borrowLimitMan >= vars.borrowValueMan, "REDEEM_INSUFFICIENT_COLLATERAL");
//抵押率不得低于 115%
require(Exp(vars.supplyValueMan).div(Exp(vars.borrowValueMan)).mantissa >= REDEEM_FACTOR_MANTISSA, "REDEEM_INSUFFICIENT_TOO_LOW");
}
function borrowAllowed(
address borrower,
address market,
uint256 ctokens
) public view {
require(ctokens > 0, "BORROW_IS_ZERO");
require(!disableBorrow, "RISK_BORROW_DISABLED");
_workingCheck(market);
//借款不能超过限额
uint256 limit = poolBorrowLimit[market];
require(limit == 0 || IMarket(market).totalBorrows().add(ctokens) <= limit, "POOL_BORROW_EXCEEDED");
ValuesVars memory vars;
(vars.supplyValueMan, vars.borrowValueMan, vars.borrowLimitMan) = _calcAcct(borrower, market, ctokens, 0);
//信用贷用户可以直接借款
uint256 creditBorrowLimit = creditLimit[borrower][market];
if (creditBorrowLimit > 0) {
// 无需超过限制
require(vars.borrowValueMan <= creditBorrowLimit, "BORROW_LIMIT_OUT");
require(creditBorrowers[borrower], "NOT_FOUND_CERDITLOAN");
} else {
require(vars.borrowValueMan <= vars.borrowLimitMan, "BORROW_LIMIT_OUT");
//抵押率不得低于110%
require(Exp(vars.supplyValueMan).div(Exp(vars.borrowValueMan)).mantissa >= CLOSE_FACTOR_MANTISSA, "REDEEM_INSUFFICIENT_TOO_LOW");
}
}
/**
* @notice 存款(放贷)前风控检查
* param minter 存款人
* @param market 借贷市场地址
* param ctokens 存入的标的资产数量
*/
function beforeSupply(
address, //minter,
address market,
uint256 //ctokens
) external view {
require(!disableSupply, "RISK_DISABLE_MINT");
_workingCheck(market);
}
function beforeTransferLP(
address market,
address from,
address to,
uint256 amount
) external {
if (from != address(0)) {
_workingCheck(market);
redeemAllowed(from, market, amount);
_settleOnce(market, TradeType.Supply, from);
}
if (to != address(0)) {
_settleOnce(market, TradeType.Supply, to);
}
}
/**
@dev 检查市场是否可借贷,只有市场处于Open状态才允许借贷
*/
function _workingCheck(address market) private view {
require(!lockAllAction, "RISK_DISABLE_ALL");
// 只有 open 状态的市场才允许交易
require(markets[IMarket(market)].status == MarketStatus.Opened, "MARKET_NOT_OPENED");
}
/**
@notice 借款前风控检查
@param borrower 借款人
@param market 借贷市场地址
@param ctokens 待借入标的资产数量
*/
function beforeBorrow(
address borrower,
address market,
uint256 ctokens
) external {
borrowAllowed(borrower, market, ctokens);
_settleOnce(market, TradeType.Borrow, borrower);
}
/**
@notice 取款(兑换)标的资产前风控检查
@param redeemer 借款人
@param market 借贷市场地址
@param ftokens 待兑换的 ftoken 数量
@dev 不管平台是否出现严重的安全问题,都允许用户取款
*/
function beforeRedeem(
address redeemer,
address market,
uint256 ftokens
) external view {
_workingCheck(market);
redeemAllowed(redeemer, market, ftokens);
}
function beforeRepay(
address borrower,
address market,
uint256 //amount
) external {
_workingCheck(market);
_settleOnce(market, TradeType.Borrow, borrower);
}
function beforeLiquidate(
address, //liquidator,
address borrower,
uint256 //amount
) external {
address market = msg.sender;
_workingCheck(market);
_settleOnce(market, TradeType.Supply, borrower);
_settleOnce(market, TradeType.Borrow, borrower);
}
/**
* @notice 查询指定账户在给定市场的借款上线
* @param acct 借款人地址
* @param mkt 借款市场
* @return limit 账户在该市场可借贷的资产数量
* @return cash 该市场总现金数量
* @dev 借款上限不能高于抵押品并且需要确保不会超出市场总量
*/
function getBorrowLimit(IMarket mkt, address acct) external view returns (uint256 limit, uint256 cash) {
cash = mkt.underlying().balanceOf(address(mkt));
ValuesVars memory vars;
(vars.supplyValueMan, vars.borrowValueMan, vars.borrowLimitMan) = _calcAcct(acct, address(mkt), 0, 0);
//信用贷用户借款额度等于额度外的量
uint256 creditBorrowLimit = creditLimit[acct][address(mkt)];
if (creditBorrowLimit > 0) {
vars.borrowLimitMan = creditBorrowLimit;
}
// 当已借款高出借款上限时,无法继续借款
if (vars.borrowLimitMan <= vars.borrowValueMan) {
return (0, cash);
}
uint256 unusedMan = vars.borrowLimitMan - vars.borrowValueMan;
uint256 priceMan = mkt.underlyingPrice();
uint256 tokenUnit = 10**(uint256(mkt.decimals()));
limit = tokenUnit.mul(unusedMan).div(priceMan);
}
/**
* @notice 查询指定账号的取款上限
* @param acct 借款人地址
* @param mkt 借款市场
* @return limit 账户在该市场可借贷的资产数量
* @return cash 该市场总现金数量
@dev 取款上限不能超时取款警戒线
*/
function getWithdrawLimit(IMarket mkt, address acct) external view returns (uint256 limit, uint256 cash) {
cash = mkt.underlying().balanceOf(address(mkt));
ValuesVars memory vars;
vars.user = acct;
(vars.supplyValueMan, vars.borrowValueMan, vars.borrowLimitMan) = _calcAcct(vars.user, address(mkt), 0, 0);
//无存款,则为0
if (vars.supplyValueMan == 0) {
return (0, cash);
}
uint256 balance = mkt.balanceOf(acct);
uint256 xrate = mkt.exchangeRate();
uint256 supply = Exp(xrate).mulScalarTruncate(balance);
// 无借款
if (vars.borrowValueMan == 0) {
//可以取走全部存款
return (supply, cash);
}
// 不能超额度
if (vars.borrowLimitMan <= vars.borrowValueMan) {
return (0, cash);
}
// 不低于抵押率
if (Exp(vars.supplyValueMan).div(Exp(vars.borrowValueMan)).mantissa <= REDEEM_FACTOR_MANTISSA) {
return (0, cash);
}
ValuesVars memory mktVars;
uint256 collRatio = markets[mkt].collRatioMan;
(mktVars.supplyValueMan, mktVars.borrowValueMan, mktVars.borrowLimitMan) = mkt.accountValues(vars.user, collRatio, 0, 0);
uint256 otherBorrowLimit = vars.borrowLimitMan.sub(mktVars.borrowLimitMan);
//( mktSupply - withdraw)/ collRation + otherBorrowLimit >= borrows
// withdraw= mktSupply - (borrows-otherBorrowLimit)*collRation
// 如果其他资产的抵押品足够抵押借款,则该市场可以全部取走
if (otherBorrowLimit >= vars.borrowValueMan) {
return (supply, cash);
}
uint256 priceMan = mkt.underlyingPrice();
uint256 used = vars.borrowValueMan - otherBorrowLimit;
uint256 tokenUnit = 10**(uint256(mkt.decimals()));
uint256 coll = tokenUnit.mul(used).mul(collRatio).div(priceMan).div(DECIMAL_UNIT);
if (coll > supply) {
limit = 0;
} else {
limit = supply - coll;
}
}
/**################################################
# Flux Reward #
###################################################*/
function setFluxMint(FluxMint fluxMiner_) external onlyOwner {
FluxMint old = fluxMiner;
require(address(old) == address(0), "REPEAT_INIT");
emit FluxMintChanged(old, fluxMiner_);
fluxMiner = fluxMiner_;
}
/**
* @notice 刷新Flux分配比例
*/
function refreshMarkeFluxSeed() external {
require(msg.sender == tx.origin, "#FutureCore: SENDER_NOT_HUMAN");
//执行复利
uint256 len = marketList.length;
for (uint256 i = 0; i < len; i++) {
marketList[i].calcCompoundInterest();
}
}
function _settleOnce(
address pool,
TradeType kind,
address user
) private {
FluxMint miner = fluxMiner;
if (address(miner) != address(0)) {
miner.settleOnce(pool, kind, user);
}
}
/**################################################
# Stack Pool Manager #
###################################################*/
/**
@notice 新增抵押池
@dev 当前保留的存储信息,以便后续向 Flux 追加若干个配置项。
@param pool 抵押池
*/
function stakePoolApprove(IStake pool, uint256 seed) external onlyOwner {
require(stakePoolStatus[pool] == MarketStatus.Unknown, "STAKEPOOL_EXIST");
stakePools.push(pool);
stakePoolStatus[pool] = MarketStatus.Opened;
fluxMiner.setPoolSeed(address(pool), seed);
emit StakePoolApproved(pool, seed);
emit StakePoolStatusChanged(pool, MarketStatus.Unknown, MarketStatus.Opened);
}
function setStakePoolStatus(IStake pool, bool opened) external onlyOwner {
require(stakePoolStatus[pool] != MarketStatus.Unknown, "STAKEPOOL_MISSING");
MarketStatus oldValue = stakePoolStatus[pool];
MarketStatus newValue = opened ? MarketStatus.Opened : MarketStatus.Stopped;
stakePoolStatus[pool] = newValue;
emit StakePoolStatusChanged(pool, oldValue, newValue);
}
function beforeStake(address user) external {
require(stakePoolStatus[IStake(msg.sender)] == MarketStatus.Opened, "STAKEPOOL_NOT_OPEN");
_settleOnce(msg.sender, TradeType.Stake, user);
}
function beforeUnStake(address user) external {
require(stakePoolStatus[IStake(msg.sender)] != MarketStatus.Unknown, "STAKEPOOL_NOT_FOUND");
_settleOnce(msg.sender, TradeType.Stake, user);
}
function removeStakePool(IStake pool) external onlyOwner {
require(stakePoolStatus[pool] == MarketStatus.Stopped, "STAKEPOOL_IS_NOT_STOPPED");
// require(pool.totalStakeAt(type(uint256).max) == 0, "ASSET_IS_NOT_ZERO");
uint256 len = stakePools.length;
for (uint256 i = 0; i < len; i++) {
if (stakePools[i] == pool) {
stakePools[i] = stakePools[len - 1];
stakePools.pop();
emit StakePoolRemoved(pool);
break;
}
}
}
/**
@notice 获取市场地址清单
*/
function getMarketList() external view returns (address[] memory list) {
uint256 len = marketList.length;
list = new address[](len);
for (uint256 i = 0; i < len; i++) {
list[i] = address(marketList[i]);
}
}
function getStakePoolList() external view returns (address[] memory list) {
uint256 len = stakePools.length;
list = new address[](len);
for (uint256 i = 0; i < len; i++) {
list[i] = address(stakePools[i]);
}
}
function getFluxTeamIncomeAddress() external view returns (address) {
return address(configs[CONFIG_TEAM_INCOME_ADDRESS]);
}
//------------------
// Flux V3
//-------------------
/**
@notice 重置信用贷用户
@dev 添加或者移除信用贷地址,添加进入信用贷的用户将被授权信用借款
*/
function resetCreditLoan(address borrower, bool add) external onlyOwner {
if (add) {
creditBorrowers[borrower] = true;
} else {
require(creditBorrowers[borrower], "NOT_FOUND_CERDITLOAN");
// 检查借款额
(, uint256 borrowValueMan, ) = getAcctSnapshot(borrower);
require(borrowValueMan == 0, "EXIST_CERDITLOAN");
//移除时限额重置为0
uint256 len = marketList.length;
for (uint256 i = 0; i < len; i++) {
resetCreditLoanLimit(address(marketList[i]), borrower, 0);
}
creditBorrowers[borrower] = false;
}
emit CreditLoanChange(borrower, add);
}
/**
@notice 重置信用贷用户借款限额
@dev 添加或者移除信用贷地址,添加进入信用贷的用户将被授权信用借款
*/
function resetCreditLoanLimit(
address market,
address borrower,
uint256 limit
) public onlyOwner {
require(creditBorrowers[borrower], "NOT_FOUND_CERDITLOAN");
uint256 oldLimit = creditLimit[borrower][market];
creditLimit[borrower][market] = limit;
emit CreditLoanLimitChange(borrower, market, limit, oldLimit);
}
/**
@notice 返回是否允许清算人清算借款人资产
@param borrower 借款人
*/
function killAllowed(address borrower) external view returns (bool yes) {
require(!liquidateDisabled, "RISK_LIQUIDATE_DISABLED");
require(!creditBorrowers[borrower], "BORROWER_IS_CERDITLOAN");
ValuesVars memory vars;
(vars.supplyValueMan, vars.borrowValueMan, vars.borrowLimitMan) = getAcctSnapshot(borrower);
if (vars.borrowValueMan == 0) {
return false;
}
//当实时抵押率跌至清算抵押率时可以被清算
// 存款额/借款 < 清算抵押率
return Exp(vars.supplyValueMan).div(Exp(vars.borrowValueMan)).mantissa < KILL_FACTOR_MANTISSA;
}
}
|
require(pool.totalStakeAt(type(uint256).max) == 0, "ASSET_IS_NOT_ZERO");
|
function removeStakePool(IStake pool) external onlyOwner {
require(stakePoolStatus[pool] == MarketStatus.Stopped, "STAKEPOOL_IS_NOT_STOPPED");
uint256 len = stakePools.length;
for (uint256 i = 0; i < len; i++) {
if (stakePools[i] == pool) {
stakePools[i] = stakePools[len - 1];
stakePools.pop();
emit StakePoolRemoved(pool);
break;
}
}
}
| 15,841,164
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract CreditToken {
//transfer function
function transferFrom(address, address, uint ) public returns (bool ) {}
function balanceOf(address) public view returns (uint ) {}
function allowance(address, address ) public view returns (uint ) {}
function transfer(address , uint ) external returns (bool ){}
function whitelistAddress (address ) external {}
function approve(address, address, uint) external returns (bool){}
function mint(address, uint) external {}
function burn(address, uint) external {}
}
contract _LendingPool{
function receiveFromLoan(uint, uint) external payable{}
}
contract Loan{
CreditToken constant public creditToken = CreditToken(0x80cDF946c1c86B7eee50743E2bc9a6d7d9ed597A);
_LendingPool immutable public lendingPool;
uint immutable public collateralRequired;
uint immutable public creditTokensRequired;
uint immutable public creationTime;
address payable immutable public borrower;
uint immutable public loanAmount;
uint immutable public loanTerm;
uint public lastPayment;
int public principal;
uint public paidBack;
uint immutable public interestRate;
uint public interestPaid;
uint public spamFee = 150;
uint public paidFees;
uint public creditChange;
enum States {
WaitingOnCollateral,
TakingStake,
DisbursingLoan,
Active,
Late,
PaidInFull,
Defaulted
}
States public state;
//https://ethereum.stackexchange.com/questions/59132/deploy-contract-with-ether
constructor (
//CreditToken tokenAddr, //the address of the credittoken's contract. (only development phase. Should be hardcoded in production time)
uint _collateralRequired, //the Ether amount of the collateral in weis
address payable _borrower, //address of the borroweaddress
uint _creditTokensRequired, // the Credit Tokens neccessary to put up as stake
uint _loanAmount, //The amount of Ether that is going to be lended to the borrower (weis)
uint _loanTerm, // in days
uint _interestRate // in percentual points muliplied by 100 (i.e. 1.5% = 150)
)
payable{ // The constructor is payable because it will receive the Ether to be lended at creation time
require(msg.value == _loanAmount);
creationTime = block.timestamp;
lendingPool = _LendingPool(msg.sender);
lastPayment = block.timestamp;
collateralRequired = _collateralRequired;
loanTerm = _loanTerm;
borrower = _borrower;
loanAmount = _loanAmount;
creditTokensRequired = _creditTokensRequired;
interestRate = _interestRate;
state = States.WaitingOnCollateral;
}
modifier onlyOnState(States _state) {
require(state == _state,"Function cannot be called at this time.");
_;
}
function nextState() internal {
state = States(uint(state) + 1);
}
//After this contract has been created, the borrower must put up the collateral by sending ETH
//to the address of the Loan Contract which will be handled by this method and initiate the
//disbursement of the loan.
receive() external payable{
if (state == States.WaitingOnCollateral){
takeCollateralDisburseLoan();
}
else if(state == States.Active){
receivePayment();
}
}
function takeCollateralDisburseLoan() internal{
uint thisSpamFee = (loanAmount * spamFee)/10000;
require(msg.value >= (collateralRequired + thisSpamFee) * 1 wei, "Your collateral is not enough for this loan.");
require(msg.value < (collateralRequired + thisSpamFee + loanAmount) * 1 wei, "You can't pay off loan right away.");
paidFees += thisSpamFee;
uint collateralSent = msg.value - thisSpamFee;
//..Now that the borrower has put the ETH as collateral, we take the CreditTokens for the loan.
nextState();
getStake();
//and disburse the loan
nextState();
disburseLoan();
principal = int(loanAmount);
//Taking care of excesive Ether sent: //ALSO, TAKE CARE OF ATTACK WHERE THE EXCESIVE ETHER WOULD BE ENOUH TO PAYOFF THE DEBT
if(collateralSent > collateralRequired){
principal -= int(collateralSent - collateralRequired);
paidBack += (collateralSent - collateralRequired);
}
nextState();
}
function receivePayment() internal{
// the payment has to be able to cover at least the interest borrowed
uint interest = calculateInteresestsofPayment();
require( msg.value >= interest, "Your payment has to cover at least the interest owed today." );
interestPaid += interest;
uint toPrincipal = msg.value - interest;
principal -= int(toPrincipal);
paidBack += toPrincipal;
if(principal <= 0 ){
state = States.PaidInFull;
if (principal<0){
paidBack -= uint(-principal);
}
closeLoan();
}
lastPayment = block.timestamp;
}
function closeLoan()internal onlyOnState(States.PaidInFull){
require(payPool(),"Could not pay pool");
require(returnAllCreditTokens(),"Could not return credit tokens");
require(returnCollateral(),"Could return collateral");
require(changeCreditScore(),"Could not change credit score");
}
function getStake() public payable onlyOnState( States.TakingStake) returns (bool success){
uint256 allowance = creditToken.allowance(borrower, address(this));
require(allowance >= creditTokensRequired, "Check the token allowance");
creditToken.transferFrom(borrower, address(this), creditTokensRequired);
return true;
}
function getCreditTokenBalance() public view returns (uint balance) {
return creditToken.balanceOf(address(this));
}
function getEtherBalance() public view returns (uint){
return address(this).balance;
}
function disburseLoan() private onlyOnState( States.DisbursingLoan ) returns(bool success){
borrower.transfer(loanAmount);
principal = int(loanAmount);
return true;
}
function returnCollateral() public returns(bool success){ //SET TO PRIVATE!!!
//borrower.transfer(collateralRequired);
//We return to the borrower all the money left in the loan since we have already
//paid the pool (interest, fees and loanAmount)
borrower.transfer(address(this).balance);
return true;
}
function changeCreditScore() internal returns (bool success) {
calculateCreditChange();
if (creditChange > 10000){
uint mintAmount = ( (creditChange - 10000) * creditTokensRequired)/10000;
creditToken.mint(borrower,mintAmount );
}else if (creditChange < 10000){
uint burnAmount = ((10000 - creditChange) * creditTokensRequired)/10000;
creditToken.burn(borrower, burnAmount);
}
return true;
}
function calculateCreditChange() internal{
//percentage change expressed in hundreth or percentual points. i.e.: 1 = 0.01% ; 100 = 1%; 1000 = 10%
if ( state != States.Late){
creditChange = 10000 + (interestPaid*2*10000)/(loanAmount * 3);
}
else {
if (block.timestamp < (loanTerm * 1 minutes * 12)/10 + creationTime ){ //CHANGE TO days IN PRODUCTION
uint x = block.timestamp - loanTerm * 1 minutes - creationTime;//CHANGE TO days IN PRODUCTION
uint m = ( 10000 + (interestPaid*10000)/(loanAmount * 3) ) / ((loanTerm * 1 minutes * 2)/10 );//CHANGE TO days IN PRODUCTION
uint b = (interestPaid*2*10000)/(loanAmount * 3);
creditChange = b - m*x;
}else
{creditChange = 0;}
}
}
function payPool() internal returns(bool success){
uint payment = paidFees + interestPaid + paidBack;
lendingPool.receiveFromLoan{value: payment}(paidFees, interestPaid);
return true;
}
function returnAllCreditTokens() public returns(bool success){ //SET TO PRIVATE!!!
creditToken.transfer(borrower, creditToken.balanceOf(address(this) ) );
return true;
}
function calculateInteresestsofPayment() public view returns(uint){
//###### REAL CODE (IN DAYS) ######
// uint nDays = (block.timestamp - lastPayment)/(1 days);
// uint interestPct = ( 10000 + interestRate )**nDays - 10000;
//###### TEST CODE (IN MINUTES) #######
uint nDays = (block.timestamp - lastPayment)/60;
return interestRate*nDays*uint(principal)/10000;
}
function howMuchToPayOff() public view returns(uint){
uint interest = calculateInteresestsofPayment();
if (principal >= 0){
return uint(principal) + interest;
}else{
return 0;
}
}
}
|
..Now that the borrower has put the ETH as collateral, we take the CreditTokens for the loan.and disburse the loanTaking care of excesive Ether sent: ALSO, TAKE CARE OF ATTACK WHERE THE EXCESIVE ETHER WOULD BE ENOUH TO PAYOFF THE DEBT
|
function takeCollateralDisburseLoan() internal{
uint thisSpamFee = (loanAmount * spamFee)/10000;
require(msg.value >= (collateralRequired + thisSpamFee) * 1 wei, "Your collateral is not enough for this loan.");
require(msg.value < (collateralRequired + thisSpamFee + loanAmount) * 1 wei, "You can't pay off loan right away.");
paidFees += thisSpamFee;
uint collateralSent = msg.value - thisSpamFee;
nextState();
getStake();
nextState();
disburseLoan();
principal = int(loanAmount);
if(collateralSent > collateralRequired){
principal -= int(collateralSent - collateralRequired);
paidBack += (collateralSent - collateralRequired);
}
nextState();
}
| 5,453,706
|
pragma solidity ^0.5.8;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
uint256 private entrancyCounter; // Re-entrancy counter to prevent re-entrancy attack
uint256 private totalAirlines; // total of actived airline
mapping(address => uint256) private airlineFund; // Fund submit by airline
mapping(address => Airline) private airlines; // mapping of all registered airlines
mapping(bytes32 => Flight) private flights; // mapping of all registered flights
mapping(address => uint256) private passengerCredits; // Credit relate to passengers
mapping(address => uint256) private authorizedContracts; // Authorize contracts
/********************************************************************************************/
/* STRUCTS && ENUMS */
/********************************************************************************************/
struct Airline {
string name; // name of air line
address payable airlineAddress; // airline address
uint fund; // the fund airline submit
AirlineState airlineState; // State of airline
address[] approveAirlines; // airlines approve for this airline to be registered
}
enum AirlineState {
Registering,
Registered,
Actived
}
struct Flight {
string flight;
bool isRegistered;
uint8 statusCode;
uint256 updatedTimestamp;
address airline;
bool isProcessed;
address[] insurees; // customers who purchase insurance of this flight
mapping(address => uint256) insuranceAmount; // insurance amount relate to each insuree
}
/********************************************************************************************/
/* CONSTRUCTORS */
/********************************************************************************************/
/**
* @dev Constructor
* The deploying account becomes contractOwner.
*/
constructor
(
address payable airlineAddress,
string memory airlineName
)
public
{
contractOwner = msg.sender;
// Init first airline and approve it
_initFirstAirline(airlineAddress, airlineName);
}
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
// The airline is registering.
event Registering(address airline);
// The airline has become registered.
event Registered(address airline);
// The airline has become actived.
event Actived(address airline);
// Flight is registed.
event FlightRegistered(string flight, uint256 timestamp);
// Customer buy insurance for this flight.
event InsuranceBought(address airline, string flight, uint256 timestamp);
// Flight is processed.
event FlightProcessed(address airline, string flight, uint256 timestamp);
// Credit payouts to insuree.
event CreditPayout(address insuree, uint256 amount);
/********************************************************************************************/
/* 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");
_;
}
/**
* @dev Require the caller is an authorized contract.
*/
modifier requireAuthorizedContract()
{
require(authorizedContracts[msg.sender] == 1, "The caller is not authorized");
_;
}
/**
* @dev Modifier that stop re-entrancy from happen.
*/
modifier entrancyGuard()
{
entrancyCounter = entrancyCounter.add(1);
uint256 guard = entrancyCounter;
_;
require(guard == entrancyCounter, "Re-entrancy is not allowed");
}
/**
* @dev Require the airline is new and has not ever on the queue.
*/
modifier requireNewAirline(address airline)
{
require(airlines[airline].airlineAddress == address(0), "The airline is already on the contract");
_;
}
/**
* @dev Required the airline is registering.
*/
modifier requireRegisteringAirline(address airline)
{
require(airlines[airline].airlineState == AirlineState.Registering, "The airline is not registering");
_;
}
/**
* @dev Required the caller is a registered airline.
*/
modifier requireRegisteredAirline()
{
require(airlines[msg.sender].airlineState == AirlineState.Registered, "The caller is not registered");
_;
}
/**
* @dev Required the caller is an actived airline.
*/
modifier requireActivedAirline()
{
require(airlines[msg.sender].airlineState == AirlineState.Actived, "The caller is not actived");
_;
}
/**
* @dev Require the caller has not ever approve this airline.
*/
modifier requireNewApproval(address airline)
{
bool duplicated = false;
address[] memory approveAirlines = airlines[airline].approveAirlines;
for(uint i = 0; i<approveAirlines.length; i++)
if (approveAirlines[i] == msg.sender)
{
duplicated = true;
break;
}
require(duplicated == false, "Duplicate approval found");
_;
}
/**
* @dev Require the caller have enough sufficent fund of 10 ether
*/
modifier requireMin10Ether()
{
require(msg.value >= 10 ether, "Insufficient fund");
_;
}
/**
* @dev Require the caller to submit up to 1 ether.
*/
modifier requireMax1Ether()
{
require(msg.value <= 1 ether, "Fund limit up to 1 ether");
_;
}
/**
* Require the caller is new insuree for this flight.
*/
modifier requireNewBuyer(address airline, string memory flight, uint256 timestamp)
{
bytes32 key = _getFlightKey(airline, flight, timestamp);
require(flights[key].insuranceAmount[msg.sender] == 0, "Flight insurance already bought");
_;
}
/**
* Require the caller is new insuree for this flight.
*/
modifier requireFlightNotProcessed(address airline, string memory flight, uint256 timestamp)
{
bytes32 key = _getFlightKey(airline, flight, timestamp);
require(flights[key].isProcessed == false, "Flight is already processed");
_;
}
/**
* Require the passenger has positive credit to withdraw.
*/
modifier requirePositiveCredit()
{
require(passengerCredits[msg.sender] > 0, "The caller does not have positive credit");
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Get operating status of contract
* @return A bool that is the current operating status
*/
function isOperational()
public
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;
}
/**
* @dev Initialize first airline when deploy the contract
*/
function _initFirstAirline
(
address payable airlineAddress,
string memory airlineName
)
private
{
Airline memory airline;
airline.airlineAddress = airlineAddress;
airline.name = airlineName;
airline.airlineState = AirlineState.Registered;
airlines[airlineAddress] = airline;
airlines[airlineAddress].approveAirlines.push(msg.sender);
emit Registered(airlineAddress);
}
/**
* @dev Taking parameter to init an airline object and add it to a queue.
*
*/
function _initAirline
(
address payable airlineAddress,
string memory airlineName
)
private
{
Airline memory airline;
airline.airlineAddress = airlineAddress;
airline.name = airlineName;
airline.airlineState = AirlineState.Registering;
airlines[airlineAddress] = airline;
}
/**
* @dev Assess the registration of an airline.
* If totalAirline is less than 5, the registration is approved, else, requires multi-party consensus of 50% of registered airlines.
*/
function _assessRegistration
(
address airlineAddress
)
private
{
if (totalAirlines <= 4 || airlines[airlineAddress].approveAirlines.length.mul(2) >= totalAirlines)
{
airlines[airlineAddress].airlineState = AirlineState.Registered;
emit Registered(airlineAddress);
}
else
emit Registering(airlineAddress);
}
/**
* The caller approve registration of this airline.
* Add the caller to approve list of this airline.
*/
function _approveAirline
(
address airlineAddress
)
private
{
airlines[airlineAddress].approveAirlines.push(msg.sender);
}
/**
* @dev Create a unique bytes32 value from parameters.
*/
function _getFlightKey
(
address airline,
string memory flight,
uint256 timestamp
)
private
pure
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
/**
* @dev Initialize and return flight object.
*/
function _initFlight
(
address airline,
string memory flightName,
uint256 timestamp
)
private
pure
returns (Flight memory flight)
{
flight.flight = flightName;
flight.updatedTimestamp = timestamp;
flight.airline = airline;
flight.isRegistered = true;
}
/**
* @dev Credits payouts to insurees in case airline fault.
*/
function _creditInsurees
(
bytes32 key
)
private
{
// Find insuree for this flight and credit them 1.5x
address[] memory insurees = flights[key].insurees;
for (uint i=0; i < insurees.length; i++)
{
uint256 amount = flights[key].insuranceAmount[insurees[i]];
uint256 credit = amount.mul(3).div(2);
passengerCredits[insurees[i]] = passengerCredits[insurees[i]].add(credit);
}
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev The contract owner authorize this caller.
*/
function authorizeCaller
(
address contractAddress
)
external
requireIsOperational
requireContractOwner
{
authorizedContracts[contractAddress] = 1;
}
/**
* @dev The contract owner deauthorize this caller.
*/
function deauthorizedContract
(
address contractAddress
)
external
requireIsOperational
requireContractOwner
{
delete authorizedContracts[contractAddress];
}
/**
* @dev Check if an address is an airline.
*/
function isAirline
(
address airline
)
external
view
requireIsOperational
returns(bool)
{
return airlines[airline].airlineAddress != address(0);
}
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*/
function registerAirline
(
address payable airlineAddress,
string calldata airlineName
)
external
requireIsOperational
requireNewAirline(airlineAddress)
requireActivedAirline
{
_initAirline(airlineAddress, airlineName);
_approveAirline(airlineAddress);
_assessRegistration(airlineAddress);
}
/**
* @dev The caller is an active airline approve registration of an airline.
*/
function approveRegistration
(
address airline
)
external
requireIsOperational
requireActivedAirline
requireNewApproval(airline)
{
_approveAirline(airline);
_assessRegistration(airline);
}
/**
* @dev A registered airline submit the fund to become actived.
* Check-Effect-Interaction and Re-entrancy Guard involved.
*/
function submitFund
(
)
external
payable
requireIsOperational
requireRegisteredAirline
requireMin10Ether
entrancyGuard
{
uint256 amountToReturn = msg.value.sub(10 ether);
msg.sender.transfer(amountToReturn);
airlineFund[msg.sender] = 10 ether;
totalAirlines = totalAirlines.add(1);
emit Actived(msg.sender);
}
/**
* @dev An active airline register a flight.
*/
function registerFlight
(
string calldata flightName,
uint256 timestamp
)
external
requireIsOperational
requireActivedAirline
{
bytes32 key = _getFlightKey(msg.sender, flightName, timestamp);
Flight memory flight = _initFlight(msg.sender, flightName, timestamp);
flights[key] = flight;
emit FlightRegistered(flightName, timestamp);
}
/**
* @dev Customer buy insurance for a flight.
* Re-entrancy guard is implement.
*/
function buy
(
address airline,
string calldata flight,
uint256 timestamp
)
external
payable
requireIsOperational
requireMax1Ether
requireNewBuyer(airline, flight, timestamp)
requireFlightNotProcessed(airline, flight, timestamp)
entrancyGuard
{
bytes32 key = _getFlightKey(airline, flight, timestamp);
flights[key].insurees.push(msg.sender);
flights[key].insuranceAmount[msg.sender] = msg.value;
emit InsuranceBought(airline, flight, timestamp);
}
/**
* @dev Update flight status of the flight.
*/
function processFlightStatus
(
address airline,
string calldata flight,
uint256 timestamp,
uint8 statusCode,
bool isAirlineFault // is flight late because of the airline fault
)
external
requireIsOperational
requireFlightNotProcessed(airline, flight, timestamp)
{
bytes32 key = _getFlightKey(airline, flight, timestamp);
flights[key].statusCode = statusCode;
flights[key].isProcessed = true;
if (isAirlineFault)
_creditInsurees(key);
emit FlightProcessed(airline, flight, timestamp);
}
/**
* @dev Transfers eligible payout funds to insuree.
* Re-entrancy Guard and Check-Effect-Interaction is applied.
*/
function pay
(
)
external
payable
requireIsOperational
requirePositiveCredit
entrancyGuard
{
uint256 amount = passengerCredits[msg.sender];
passengerCredits[msg.sender] = 0;
msg.sender.transfer(amount);
emit CreditPayout(msg.sender, amount);
}
/**
* @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
{
}
/**
* @dev Fallback function for funding smart contract.
*
*/
function()
external
payable
{
fund();
}
}
|
Add an airline to the registration queue Can only be called from FlightSuretyApp contract/
|
function registerAirline
(
address payable airlineAddress,
string calldata airlineName
)
external
requireIsOperational
requireNewAirline(airlineAddress)
requireActivedAirline
{
_initAirline(airlineAddress, airlineName);
_approveAirline(airlineAddress);
_assessRegistration(airlineAddress);
}
| 12,776,805
|
// Copyright (C) 2020 Maker Ecosystem Growth Holdings, INC.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
pragma solidity 0.5.12;
contract DSPauseAbstract {
function SETOWNER297(address) external; //inject NONSTANDARD NAMING
function SETAUTHORITY462(address) external; //inject NONSTANDARD NAMING
function SETDELAY997(uint256) external; //inject NONSTANDARD NAMING
function PLANS194(bytes32) external view returns (bool); //inject NONSTANDARD NAMING
function PROXY33() external view returns (address); //inject NONSTANDARD NAMING
function DELAY572() external view returns (uint256); //inject NONSTANDARD NAMING
function PLOT308(address, bytes32, bytes calldata, uint256) external; //inject NONSTANDARD NAMING
function DROP835(address, bytes32, bytes calldata, uint256) external; //inject NONSTANDARD NAMING
function EXEC528(address, bytes32, bytes calldata, uint256) external returns (bytes memory); //inject NONSTANDARD NAMING
}
contract JugAbstract {
function WARDS993(address) external view returns (uint256); //inject NONSTANDARD NAMING
function RELY27(address) external; //inject NONSTANDARD NAMING
function DENY29(address) external; //inject NONSTANDARD NAMING
function ILKS89(bytes32) external view returns (uint256, uint256); //inject NONSTANDARD NAMING
function VAT322() external view returns (address); //inject NONSTANDARD NAMING
function VOW865() external view returns (address); //inject NONSTANDARD NAMING
function BASE98() external view returns (address); //inject NONSTANDARD NAMING
function INIT382(bytes32) external; //inject NONSTANDARD NAMING
function FILE935(bytes32, bytes32, uint256) external; //inject NONSTANDARD NAMING
function FILE935(bytes32, uint256) external; //inject NONSTANDARD NAMING
function FILE935(bytes32, address) external; //inject NONSTANDARD NAMING
function DRIP851(bytes32) external returns (uint256); //inject NONSTANDARD NAMING
}
contract VatAbstract {
function WARDS993(address) external view returns (uint256); //inject NONSTANDARD NAMING
function RELY27(address) external; //inject NONSTANDARD NAMING
function DENY29(address) external; //inject NONSTANDARD NAMING
function CAN701(address, address) external view returns (uint256); //inject NONSTANDARD NAMING
function HOPE401(address) external; //inject NONSTANDARD NAMING
function NOPE804(address) external; //inject NONSTANDARD NAMING
function ILKS89(bytes32) external view returns (uint256, uint256, uint256, uint256, uint256); //inject NONSTANDARD NAMING
function URNS72(bytes32, address) external view returns (uint256, uint256); //inject NONSTANDARD NAMING
function GEM847(bytes32, address) external view returns (uint256); //inject NONSTANDARD NAMING
function DAI766(address) external view returns (uint256); //inject NONSTANDARD NAMING
function SIN979(address) external view returns (uint256); //inject NONSTANDARD NAMING
function DEBT96() external view returns (uint256); //inject NONSTANDARD NAMING
function VICE796() external view returns (uint256); //inject NONSTANDARD NAMING
function LINE365() external view returns (uint256); //inject NONSTANDARD NAMING
function LIVE39() external view returns (uint256); //inject NONSTANDARD NAMING
function INIT382(bytes32) external; //inject NONSTANDARD NAMING
function FILE935(bytes32, uint256) external; //inject NONSTANDARD NAMING
function FILE935(bytes32, bytes32, uint256) external; //inject NONSTANDARD NAMING
function CAGE573() external; //inject NONSTANDARD NAMING
function SLIP893(bytes32, address, int256) external; //inject NONSTANDARD NAMING
function FLUX455(bytes32, address, address, uint256) external; //inject NONSTANDARD NAMING
function MOVE486(address, address, uint256) external; //inject NONSTANDARD NAMING
function FROB749(bytes32, address, address, address, int256, int256) external; //inject NONSTANDARD NAMING
function FORK68(bytes32, address, address, int256, int256) external; //inject NONSTANDARD NAMING
function GRAB867(bytes32, address, address, address, int256, int256) external; //inject NONSTANDARD NAMING
function HEAL281(uint256) external; //inject NONSTANDARD NAMING
function SUCK979(address, address, uint256) external; //inject NONSTANDARD NAMING
function FOLD739(bytes32, address, int256) external; //inject NONSTANDARD NAMING
}
contract VowAbstract {
function WARDS993(address) external view returns (uint256); //inject NONSTANDARD NAMING
function RELY27(address usr) external; //inject NONSTANDARD NAMING
function DENY29(address usr) external; //inject NONSTANDARD NAMING
function VAT322() external view returns (address); //inject NONSTANDARD NAMING
function FLAPPER608() external view returns (address); //inject NONSTANDARD NAMING
function FLOPPER190() external view returns (address); //inject NONSTANDARD NAMING
function SIN979(uint256) external view returns (uint256); //inject NONSTANDARD NAMING
function SIN979() external view returns (uint256); //inject NONSTANDARD NAMING
function ASH807() external view returns (uint256); //inject NONSTANDARD NAMING
function WAIT426() external view returns (uint256); //inject NONSTANDARD NAMING
function DUMP329() external view returns (uint256); //inject NONSTANDARD NAMING
function SUMP140() external view returns (uint256); //inject NONSTANDARD NAMING
function BUMP430() external view returns (uint256); //inject NONSTANDARD NAMING
function HUMP834() external view returns (uint256); //inject NONSTANDARD NAMING
function LIVE39() external view returns (uint256); //inject NONSTANDARD NAMING
function FILE935(bytes32, uint256) external; //inject NONSTANDARD NAMING
function FILE935(bytes32, address) external; //inject NONSTANDARD NAMING
function FESS945(uint256) external; //inject NONSTANDARD NAMING
function FLOG837(uint256) external; //inject NONSTANDARD NAMING
function HEAL281(uint256) external; //inject NONSTANDARD NAMING
function KISS865(uint256) external; //inject NONSTANDARD NAMING
function FLOP497() external returns (uint256); //inject NONSTANDARD NAMING
function FLAP923() external returns (uint256); //inject NONSTANDARD NAMING
function CAGE573() external; //inject NONSTANDARD NAMING
}
contract IlkRegistryAbstract {
function WARDS993(address) external view returns (uint256); //inject NONSTANDARD NAMING
function RELY27(address) external; //inject NONSTANDARD NAMING
function DENY29(address) external; //inject NONSTANDARD NAMING
function VAT322() external view returns (address); //inject NONSTANDARD NAMING
function CAT738() external view returns (address); //inject NONSTANDARD NAMING
function SPOT274() external view returns (address); //inject NONSTANDARD NAMING
function ILKDATA365(bytes32) external view returns ( //inject NONSTANDARD NAMING
uint256,
address,
address,
address,
address,
uint256,
string memory,
string memory
);
function ILKS89() external view returns (bytes32[] memory); //inject NONSTANDARD NAMING
function ILKS89(uint) external view returns (bytes32); //inject NONSTANDARD NAMING
function ADD269(address) external; //inject NONSTANDARD NAMING
function REMOVE614(bytes32) external; //inject NONSTANDARD NAMING
function REMOVEAUTH234(bytes32) external; //inject NONSTANDARD NAMING
function FILE935(bytes32, bytes32, address) external; //inject NONSTANDARD NAMING
function FILE935(bytes32, bytes32, uint256) external; //inject NONSTANDARD NAMING
function FILE935(bytes32, bytes32, string calldata) external; //inject NONSTANDARD NAMING
function COUNT649() external view returns (uint256); //inject NONSTANDARD NAMING
function LIST141() external view returns (bytes32[] memory); //inject NONSTANDARD NAMING
function LIST141(uint256, uint256) external view returns (bytes32[] memory); //inject NONSTANDARD NAMING
function GET51(uint256) external view returns (bytes32); //inject NONSTANDARD NAMING
function INFO652(bytes32) external view returns ( //inject NONSTANDARD NAMING
string memory,
string memory,
uint256,
address,
address,
address,
address
);
function POS804(bytes32) external view returns (uint256); //inject NONSTANDARD NAMING
function GEM847(bytes32) external view returns (address); //inject NONSTANDARD NAMING
function PIP889(bytes32) external view returns (address); //inject NONSTANDARD NAMING
function JOIN697(bytes32) external view returns (address); //inject NONSTANDARD NAMING
function FLIP981(bytes32) external view returns (address); //inject NONSTANDARD NAMING
function DEC837(bytes32) external view returns (uint256); //inject NONSTANDARD NAMING
function SYMBOL988(bytes32) external view returns (string memory); //inject NONSTANDARD NAMING
function NAME950(bytes32) external view returns (string memory); //inject NONSTANDARD NAMING
}
contract SpellAction {
// Provides a descriptive tag for bot consumption
// This should be modified weekly to provide a summary of the actions
// Hash: seth keccak -- "$(wget https://raw.githubusercontent.com/makerdao/community/c8e9f709f4bc5d0384b47e0109eb7555f08b84fc/governance/votes/Executive%20vote%20-%20August%2014%2C%202020.md -q -O - 2>/dev/null)"
string constant public description524 = //inject NONSTANDARD NAMING
"2020-08-14 MakerDAO Weekly Executive Spell | Hash: 0x97294bc0de2100192a54a618351a84574e5d1998da234152e68b4065ac9bea0f";
// MAINNET ADDRESSES
//
// The contracts in this list should correspond to MCD core contracts, verify
// against the current release list at:
// https://changelog.makerdao.com/releases/mainnet/1.0.9/contracts.json
address constant mcd_vat35 = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; //inject NONSTANDARD NAMING
address constant mcd_jug497 = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; //inject NONSTANDARD NAMING
address constant mcd_vow892 = 0xA950524441892A31ebddF91d3cEEFa04Bf454466; //inject NONSTANDARD NAMING
address constant ilk_registry964 = 0xbE4F921cdFEf2cF5080F9Cf00CC2c14F1F96Bd07; //inject NONSTANDARD NAMING
uint256 constant million677 = 10 ** 6; //inject NONSTANDARD NAMING
uint256 constant rad54 = 10 ** 45; //inject NONSTANDARD NAMING
// Many of the settings that change weekly rely on the rate accumulator
// described at https://docs.makerdao.com/smart-contract-modules/rates-module
// To check this yourself, use the following rate calculation (example 6%):
//
// $ bc -l <<< 'scale=27; e( l(1.06)/(60 * 60 * 24 * 365) )'
//
uint256 constant six_pct_rate891 = 1000000001847694957439350562; //inject NONSTANDARD NAMING
uint256 constant fortyfour_pct_rate631 = 1000000011562757347033522598; //inject NONSTANDARD NAMING
function EXECUTE336() external { //inject NONSTANDARD NAMING
bytes32[] memory ilks = IlkRegistryAbstract(ilk_registry964).LIST141();
for(uint i = 0; i < ilks.length; i++) {
// Set all ilks dust value from 20 Dai to 100 Dai
VatAbstract(mcd_vat35).FILE935(ilks[i], "dust", 100 * rad54);
}
// Set the MANA-A stability fee
// value is determined by the rate accumulator calculation (see above)
// ex. an 8% annual rate will be 1000000002440418608258400030
//
// Existing Rate: 8%
// New Rate: 6%
JugAbstract(mcd_jug497).DRIP851("MANA-A");
JugAbstract(mcd_jug497).FILE935("MANA-A", "duty", six_pct_rate891);
// Set the USDC-B stability fee
// value is determined by the rate accumulator calculation (see above)
// ex. an 8% annual rate will be 1000000002440418608258400030
//
// Existing Rate: 46%
// New Rate: 44%
JugAbstract(mcd_jug497).DRIP851("USDC-B");
JugAbstract(mcd_jug497).FILE935("USDC-B", "duty", fortyfour_pct_rate631);
// Sets the system surplus buffer from 500k Dai to 2mm Dai
VowAbstract(mcd_vow892).FILE935("hump", 2 * million677 * rad54);
}
}
contract DssSpell {
DSPauseAbstract public pause =
DSPauseAbstract(0xbE286431454714F511008713973d3B053A2d38f3);
address public action;
bytes32 public tag;
uint256 public eta;
bytes public sig;
uint256 public expiration;
bool public done;
constructor() public {
sig = abi.encodeWithSignature("execute()");
action = address(new SpellAction());
bytes32 _tag;
address _action = action;
assembly { _tag := extcodehash(_action) }
tag = _tag;
expiration = now + 30 days;
}
function DESCRIPTION887() public view returns (string memory) { //inject NONSTANDARD NAMING
return SpellAction(action).description524();
}
function SCHEDULE900() public { //inject NONSTANDARD NAMING
require(now <= expiration, "This contract has expired");
require(eta == 0, "This spell has already been scheduled");
eta = now + DSPauseAbstract(pause).DELAY572();
pause.PLOT308(action, tag, sig, eta);
}
function CAST355() public { //inject NONSTANDARD NAMING
require(!done, "spell-already-cast");
done = true;
pause.EXEC528(action, tag, sig, eta);
}
}
|
inject NONSTANDARD NAMING
|
function FLOG837(uint256) external;
| 12,918,589
|
./full_match/1/0x7808Ae59f227b8fecEC98000112a67534cea0F1b/sources/vesper-strategies/contracts/strategies/curve/CurveBase.sol
|
Note: Using use_underlying = true to withdraw underlying instead of IB token
|
function _withdrawFrom2LendingPool(uint256 lpAmount_, uint256 minAmountOut_, int128 i_) private {
IStableSwap2xUnderlying(crvPool).remove_liquidity_one_coin(lpAmount_, i_, minAmountOut_, true);
}
| 2,931,802
|
pragma solidity ^0.4.0;
import { Base } from 'Base';
import { Voter } from 'Voter';
import { Bill } from 'Bill';
import { Token } from 'Token';
contract Organization is Base {
/*
Currency of the organization
*/
Token token;
function Organization(){
}
/*
Transfers employee's salary
@param employee - employee's private address
@param voter - employee's voter address
@param amount - salary before taxes
*/
function payEmployee(address employee, Voter voter, uint256 amount) onlyOwner {
// transfer salary to employee
token.transferTaxableIncome(employee, voter, amount);
}
}
|
/ transfer salary to employee
|
function payEmployee(address employee, Voter voter, uint256 amount) onlyOwner {
token.transferTaxableIncome(employee, voter, amount);
}
| 12,855,593
|
/**
*Submitted for verification at Etherscan.io on 2021-02-02
*/
// File: @openzeppelin/contracts/math/SafeMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @bancor/token-governance/contracts/IClaimable.sol
pragma solidity 0.6.12;
/// @title Claimable contract interface
interface IClaimable {
function owner() external view returns (address);
function transferOwnership(address newOwner) external;
function acceptOwnership() external;
}
// File: @bancor/token-governance/contracts/IMintableToken.sol
pragma solidity 0.6.12;
/// @title Mintable Token interface
interface IMintableToken is IERC20, IClaimable {
function issue(address to, uint256 amount) external;
function destroy(address from, uint256 amount) external;
}
// File: @bancor/token-governance/contracts/ITokenGovernance.sol
pragma solidity 0.6.12;
/// @title The interface for mintable/burnable token governance.
interface ITokenGovernance {
// The address of the mintable ERC20 token.
function token() external view returns (IMintableToken);
/// @dev Mints new tokens.
///
/// @param to Account to receive the new amount.
/// @param amount Amount to increase the supply by.
///
function mint(address to, uint256 amount) external;
/// @dev Burns tokens from the caller.
///
/// @param amount Amount to decrease the supply by.
///
function burn(uint256 amount) external;
}
// File: solidity/contracts/utility/interfaces/ICheckpointStore.sol
pragma solidity 0.6.12;
/**
* @dev Checkpoint store contract interface
*/
interface ICheckpointStore {
function addCheckpoint(address _address) external;
function addPastCheckpoint(address _address, uint256 _time) external;
function addPastCheckpoints(address[] calldata _addresses, uint256[] calldata _times) external;
function checkpoint(address _address) external view returns (uint256);
}
// File: solidity/contracts/utility/MathEx.sol
pragma solidity 0.6.12;
/**
* @dev This library provides a set of complex math operations.
*/
library MathEx {
/**
* @dev returns the largest integer smaller than or equal to the square root of a positive integer
*
* @param _num a positive integer
*
* @return the largest integer smaller than or equal to the square root of the positive integer
*/
function floorSqrt(uint256 _num) internal pure returns (uint256) {
uint256 x = _num / 2 + 1;
uint256 y = (x + _num / x) / 2;
while (x > y) {
x = y;
y = (x + _num / x) / 2;
}
return x;
}
/**
* @dev returns the smallest integer larger than or equal to the square root of a positive integer
*
* @param _num a positive integer
*
* @return the smallest integer larger than or equal to the square root of the positive integer
*/
function ceilSqrt(uint256 _num) internal pure returns (uint256) {
uint256 x = floorSqrt(_num);
return x * x == _num ? x : x + 1;
}
/**
* @dev computes a reduced-scalar ratio
*
* @param _n ratio numerator
* @param _d ratio denominator
* @param _max maximum desired scalar
*
* @return ratio's numerator and denominator
*/
function reducedRatio(
uint256 _n,
uint256 _d,
uint256 _max
) internal pure returns (uint256, uint256) {
(uint256 n, uint256 d) = (_n, _d);
if (n > _max || d > _max) {
(n, d) = normalizedRatio(n, d, _max);
}
if (n != d) {
return (n, d);
}
return (1, 1);
}
/**
* @dev computes "scale * a / (a + b)" and "scale * b / (a + b)".
*/
function normalizedRatio(
uint256 _a,
uint256 _b,
uint256 _scale
) internal pure returns (uint256, uint256) {
if (_a <= _b) {
return accurateRatio(_a, _b, _scale);
}
(uint256 y, uint256 x) = accurateRatio(_b, _a, _scale);
return (x, y);
}
/**
* @dev computes "scale * a / (a + b)" and "scale * b / (a + b)", assuming that "a <= b".
*/
function accurateRatio(
uint256 _a,
uint256 _b,
uint256 _scale
) internal pure returns (uint256, uint256) {
uint256 maxVal = uint256(-1) / _scale;
if (_a > maxVal) {
uint256 c = _a / (maxVal + 1) + 1;
_a /= c; // we can now safely compute `_a * _scale`
_b /= c;
}
if (_a != _b) {
uint256 n = _a * _scale;
uint256 d = _a + _b; // can overflow
if (d >= _a) {
// no overflow in `_a + _b`
uint256 x = roundDiv(n, d); // we can now safely compute `_scale - x`
uint256 y = _scale - x;
return (x, y);
}
if (n < _b - (_b - _a) / 2) {
return (0, _scale); // `_a * _scale < (_a + _b) / 2 < MAX_UINT256 < _a + _b`
}
return (1, _scale - 1); // `(_a + _b) / 2 < _a * _scale < MAX_UINT256 < _a + _b`
}
return (_scale / 2, _scale / 2); // allow reduction to `(1, 1)` in the calling function
}
/**
* @dev computes the nearest integer to a given quotient without overflowing or underflowing.
*/
function roundDiv(uint256 _n, uint256 _d) internal pure returns (uint256) {
return _n / _d + (_n % _d) / (_d - _d / 2);
}
/**
* @dev returns the average number of decimal digits in a given list of positive integers
*
* @param _values list of positive integers
*
* @return the average number of decimal digits in the given list of positive integers
*/
function geometricMean(uint256[] memory _values) internal pure returns (uint256) {
uint256 numOfDigits = 0;
uint256 length = _values.length;
for (uint256 i = 0; i < length; i++) {
numOfDigits += decimalLength(_values[i]);
}
return uint256(10)**(roundDivUnsafe(numOfDigits, length) - 1);
}
/**
* @dev returns the number of decimal digits in a given positive integer
*
* @param _x positive integer
*
* @return the number of decimal digits in the given positive integer
*/
function decimalLength(uint256 _x) internal pure returns (uint256) {
uint256 y = 0;
for (uint256 x = _x; x > 0; x /= 10) {
y++;
}
return y;
}
/**
* @dev returns the nearest integer to a given quotient
* the computation is overflow-safe assuming that the input is sufficiently small
*
* @param _n quotient numerator
* @param _d quotient denominator
*
* @return the nearest integer to the given quotient
*/
function roundDivUnsafe(uint256 _n, uint256 _d) internal pure returns (uint256) {
return (_n + _d / 2) / _d;
}
/**
* @dev returns the larger of two values
*
* @param _val1 the first value
* @param _val2 the second value
*/
function max(uint256 _val1, uint256 _val2) internal pure returns (uint256) {
return _val1 > _val2 ? _val1 : _val2;
}
}
// File: solidity/contracts/utility/ReentrancyGuard.sol
pragma solidity 0.6.12;
/**
* @dev This contract provides protection against calling a function
* (directly or indirectly) from within itself.
*/
contract ReentrancyGuard {
uint256 private constant UNLOCKED = 1;
uint256 private constant LOCKED = 2;
// LOCKED while protected code is being executed, UNLOCKED otherwise
uint256 private state = UNLOCKED;
/**
* @dev ensures instantiation only by sub-contracts
*/
constructor() internal {}
// protects a function against reentrancy attacks
modifier protected() {
_protected();
state = LOCKED;
_;
state = UNLOCKED;
}
// error message binary size optimization
function _protected() internal view {
require(state == UNLOCKED, "ERR_REENTRANCY");
}
}
// File: solidity/contracts/utility/interfaces/IOwned.sol
pragma solidity 0.6.12;
/*
Owned contract interface
*/
interface IOwned {
// this function isn't since the compiler emits automatically generated getter functions as external
function owner() external view returns (address);
function transferOwnership(address _newOwner) external;
function acceptOwnership() external;
}
// File: solidity/contracts/utility/Owned.sol
pragma solidity 0.6.12;
/**
* @dev This contract provides support and utilities for contract ownership.
*/
contract Owned is IOwned {
address public override owner;
address public newOwner;
/**
* @dev triggered when the owner is updated
*
* @param _prevOwner previous owner
* @param _newOwner new owner
*/
event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner);
/**
* @dev initializes a new Owned instance
*/
constructor() public {
owner = msg.sender;
}
// allows execution by the owner only
modifier ownerOnly {
_ownerOnly();
_;
}
// error message binary size optimization
function _ownerOnly() internal view {
require(msg.sender == owner, "ERR_ACCESS_DENIED");
}
/**
* @dev allows transferring the contract ownership
* the new owner still needs to accept the transfer
* can only be called by the contract owner
*
* @param _newOwner new contract owner
*/
function transferOwnership(address _newOwner) public override ownerOnly {
require(_newOwner != owner, "ERR_SAME_OWNER");
newOwner = _newOwner;
}
/**
* @dev used by a new owner to accept an ownership transfer
*/
function acceptOwnership() public override {
require(msg.sender == newOwner, "ERR_ACCESS_DENIED");
emit OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// File: solidity/contracts/token/interfaces/IERC20Token.sol
pragma solidity 0.6.12;
/*
ERC20 Standard Token interface
*/
interface IERC20Token {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address _owner) external view returns (uint256);
function allowance(address _owner, address _spender) external view returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool);
function transferFrom(
address _from,
address _to,
uint256 _value
) external returns (bool);
function approve(address _spender, uint256 _value) external returns (bool);
}
// File: solidity/contracts/utility/TokenHandler.sol
pragma solidity 0.6.12;
contract TokenHandler {
bytes4 private constant APPROVE_FUNC_SELECTOR = bytes4(keccak256("approve(address,uint256)"));
bytes4 private constant TRANSFER_FUNC_SELECTOR = bytes4(keccak256("transfer(address,uint256)"));
bytes4 private constant TRANSFER_FROM_FUNC_SELECTOR = bytes4(keccak256("transferFrom(address,address,uint256)"));
/**
* @dev executes the ERC20 token's `approve` function and reverts upon failure
* the main purpose of this function is to prevent a non standard ERC20 token
* from failing silently
*
* @param _token ERC20 token address
* @param _spender approved address
* @param _value allowance amount
*/
function safeApprove(
IERC20Token _token,
address _spender,
uint256 _value
) internal {
(bool success, bytes memory data) = address(_token).call(
abi.encodeWithSelector(APPROVE_FUNC_SELECTOR, _spender, _value)
);
require(success && (data.length == 0 || abi.decode(data, (bool))), "ERR_APPROVE_FAILED");
}
/**
* @dev executes the ERC20 token's `transfer` function and reverts upon failure
* the main purpose of this function is to prevent a non standard ERC20 token
* from failing silently
*
* @param _token ERC20 token address
* @param _to target address
* @param _value transfer amount
*/
function safeTransfer(
IERC20Token _token,
address _to,
uint256 _value
) internal {
(bool success, bytes memory data) = address(_token).call(
abi.encodeWithSelector(TRANSFER_FUNC_SELECTOR, _to, _value)
);
require(success && (data.length == 0 || abi.decode(data, (bool))), "ERR_TRANSFER_FAILED");
}
/**
* @dev executes the ERC20 token's `transferFrom` function and reverts upon failure
* the main purpose of this function is to prevent a non standard ERC20 token
* from failing silently
*
* @param _token ERC20 token address
* @param _from source address
* @param _to target address
* @param _value transfer amount
*/
function safeTransferFrom(
IERC20Token _token,
address _from,
address _to,
uint256 _value
) internal {
(bool success, bytes memory data) = address(_token).call(
abi.encodeWithSelector(TRANSFER_FROM_FUNC_SELECTOR, _from, _to, _value)
);
require(success && (data.length == 0 || abi.decode(data, (bool))), "ERR_TRANSFER_FROM_FAILED");
}
}
// File: solidity/contracts/utility/Types.sol
pragma solidity 0.6.12;
/**
* @dev This contract provides types which can be used by various contracts.
*/
struct Fraction {
uint256 n; // numerator
uint256 d; // denominator
}
// File: solidity/contracts/utility/Time.sol
pragma solidity 0.6.12;
/*
Time implementing contract
*/
contract Time {
/**
* @dev returns the current time
*/
function time() internal view virtual returns (uint256) {
return block.timestamp;
}
}
// File: solidity/contracts/utility/Utils.sol
pragma solidity 0.6.12;
/**
* @dev Utilities & Common Modifiers
*/
contract Utils {
// verifies that a value is greater than zero
modifier greaterThanZero(uint256 _value) {
_greaterThanZero(_value);
_;
}
// error message binary size optimization
function _greaterThanZero(uint256 _value) internal pure {
require(_value > 0, "ERR_ZERO_VALUE");
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address _address) {
_validAddress(_address);
_;
}
// error message binary size optimization
function _validAddress(address _address) internal pure {
require(_address != address(0), "ERR_INVALID_ADDRESS");
}
// verifies that the address is different than this contract address
modifier notThis(address _address) {
_notThis(_address);
_;
}
// error message binary size optimization
function _notThis(address _address) internal view {
require(_address != address(this), "ERR_ADDRESS_IS_SELF");
}
// validates an external address - currently only checks that it isn't null or this
modifier validExternalAddress(address _address) {
_validExternalAddress(_address);
_;
}
// error message binary size optimization
function _validExternalAddress(address _address) internal view {
require(_address != address(0) && _address != address(this), "ERR_INVALID_EXTERNAL_ADDRESS");
}
}
// File: solidity/contracts/converter/interfaces/IConverterAnchor.sol
pragma solidity 0.6.12;
/*
Converter Anchor interface
*/
interface IConverterAnchor is IOwned {
}
// File: solidity/contracts/token/interfaces/IDSToken.sol
pragma solidity 0.6.12;
/*
DSToken interface
*/
interface IDSToken is IConverterAnchor, IERC20Token {
function issue(address _to, uint256 _amount) external;
function destroy(address _from, uint256 _amount) external;
}
// File: solidity/contracts/liquidity-protection/interfaces/ILiquidityProtectionStore.sol
pragma solidity 0.6.12;
/*
Liquidity Protection Store interface
*/
interface ILiquidityProtectionStore is IOwned {
function withdrawTokens(
IERC20Token _token,
address _to,
uint256 _amount
) external;
function protectedLiquidity(uint256 _id)
external
view
returns (
address,
IDSToken,
IERC20Token,
uint256,
uint256,
uint256,
uint256,
uint256
);
function addProtectedLiquidity(
address _provider,
IDSToken _poolToken,
IERC20Token _reserveToken,
uint256 _poolAmount,
uint256 _reserveAmount,
uint256 _reserveRateN,
uint256 _reserveRateD,
uint256 _timestamp
) external returns (uint256);
function updateProtectedLiquidityAmounts(
uint256 _id,
uint256 _poolNewAmount,
uint256 _reserveNewAmount
) external;
function removeProtectedLiquidity(uint256 _id) external;
function lockedBalance(address _provider, uint256 _index) external view returns (uint256, uint256);
function lockedBalanceRange(
address _provider,
uint256 _startIndex,
uint256 _endIndex
) external view returns (uint256[] memory, uint256[] memory);
function addLockedBalance(
address _provider,
uint256 _reserveAmount,
uint256 _expirationTime
) external returns (uint256);
function removeLockedBalance(address _provider, uint256 _index) external;
function systemBalance(IERC20Token _poolToken) external view returns (uint256);
function incSystemBalance(IERC20Token _poolToken, uint256 _poolAmount) external;
function decSystemBalance(IERC20Token _poolToken, uint256 _poolAmount) external;
}
// File: solidity/contracts/liquidity-protection/interfaces/ILiquidityProtectionStats.sol
pragma solidity 0.6.12;
/*
Liquidity Protection Stats interface
*/
interface ILiquidityProtectionStats {
function increaseTotalAmounts(
address provider,
IDSToken poolToken,
IERC20Token reserveToken,
uint256 poolAmount,
uint256 reserveAmount
) external;
function decreaseTotalAmounts(
address provider,
IDSToken poolToken,
IERC20Token reserveToken,
uint256 poolAmount,
uint256 reserveAmount
) external;
function addProviderPool(address provider, IDSToken poolToken) external returns (bool);
function removeProviderPool(address provider, IDSToken poolToken) external returns (bool);
function totalPoolAmount(IDSToken poolToken) external view returns (uint256);
function totalReserveAmount(IDSToken poolToken, IERC20Token reserveToken) external view returns (uint256);
function totalProviderAmount(
address provider,
IDSToken poolToken,
IERC20Token reserveToken
) external view returns (uint256);
function providerPools(address provider) external view returns (IDSToken[] memory);
}
// File: solidity/contracts/liquidity-protection/interfaces/ILiquidityProtectionSettings.sol
pragma solidity 0.6.12;
/*
Liquidity Protection Store Settings interface
*/
interface ILiquidityProtectionSettings {
function addPoolToWhitelist(IConverterAnchor _poolAnchor) external;
function removePoolFromWhitelist(IConverterAnchor _poolAnchor) external;
function isPoolWhitelisted(IConverterAnchor _poolAnchor) external view returns (bool);
function poolWhitelist() external view returns (address[] memory);
function isPoolSupported(IConverterAnchor _poolAnchor) external view returns (bool);
function minNetworkTokenLiquidityForMinting() external view returns (uint256);
function defaultNetworkTokenMintingLimit() external view returns (uint256);
function networkTokenMintingLimits(IConverterAnchor _poolAnchor) external view returns (uint256);
function networkTokensMinted(IConverterAnchor _poolAnchor) external view returns (uint256);
function incNetworkTokensMinted(IConverterAnchor _poolAnchor, uint256 _amount) external;
function decNetworkTokensMinted(IConverterAnchor _poolAnchor, uint256 _amount) external;
function minProtectionDelay() external view returns (uint256);
function maxProtectionDelay() external view returns (uint256);
function setProtectionDelays(uint256 _minProtectionDelay, uint256 _maxProtectionDelay) external;
function minNetworkCompensation() external view returns (uint256);
function setMinNetworkCompensation(uint256 _minCompensation) external;
function lockDuration() external view returns (uint256);
function setLockDuration(uint256 _lockDuration) external;
function averageRateMaxDeviation() external view returns (uint32);
function setAverageRateMaxDeviation(uint32 _averageRateMaxDeviation) external;
}
// File: solidity/contracts/liquidity-protection/interfaces/ILiquidityProtectionSystemStore.sol
pragma solidity 0.6.12;
/*
Liquidity Protection System Store interface
*/
interface ILiquidityProtectionSystemStore {
function systemBalance(IERC20Token poolToken) external view returns (uint256);
function incSystemBalance(IERC20Token poolToken, uint256 poolAmount) external;
function decSystemBalance(IERC20Token poolToken, uint256 poolAmount) external;
function networkTokensMinted(IConverterAnchor poolAnchor) external view returns (uint256);
function incNetworkTokensMinted(IConverterAnchor poolAnchor, uint256 amount) external;
function decNetworkTokensMinted(IConverterAnchor poolAnchor, uint256 amount) external;
}
// File: solidity/contracts/utility/interfaces/ITokenHolder.sol
pragma solidity 0.6.12;
/*
Token Holder interface
*/
interface ITokenHolder is IOwned {
function withdrawTokens(
IERC20Token _token,
address _to,
uint256 _amount
) external;
}
// File: solidity/contracts/liquidity-protection/interfaces/ILiquidityProtection.sol
pragma solidity 0.6.12;
/*
Liquidity Protection interface
*/
interface ILiquidityProtection {
function store() external view returns (ILiquidityProtectionStore);
function stats() external view returns (ILiquidityProtectionStats);
function settings() external view returns (ILiquidityProtectionSettings);
function systemStore() external view returns (ILiquidityProtectionSystemStore);
function wallet() external view returns (ITokenHolder);
function addLiquidityFor(
address owner,
IConverterAnchor poolAnchor,
IERC20Token reserveToken,
uint256 amount
) external payable returns (uint256);
function addLiquidity(
IConverterAnchor poolAnchor,
IERC20Token reserveToken,
uint256 amount
) external payable returns (uint256);
function removeLiquidity(uint256 id, uint32 portion) external;
}
// File: solidity/contracts/liquidity-protection/interfaces/ILiquidityProtectionEventsSubscriber.sol
pragma solidity 0.6.12;
/**
* @dev Liquidity protection events subscriber interface
*/
interface ILiquidityProtectionEventsSubscriber {
function onAddingLiquidity(
address provider,
IConverterAnchor poolAnchor,
IERC20Token reserveToken,
uint256 poolAmount,
uint256 reserveAmount
) external;
function onRemovingLiquidity(
uint256 id,
address provider,
IConverterAnchor poolAnchor,
IERC20Token reserveToken,
uint256 poolAmount,
uint256 reserveAmount
) external;
}
// File: solidity/contracts/converter/interfaces/IConverter.sol
pragma solidity 0.6.12;
/*
Converter interface
*/
interface IConverter is IOwned {
function converterType() external pure returns (uint16);
function anchor() external view returns (IConverterAnchor);
function isActive() external view returns (bool);
function targetAmountAndFee(
IERC20Token _sourceToken,
IERC20Token _targetToken,
uint256 _amount
) external view returns (uint256, uint256);
function convert(
IERC20Token _sourceToken,
IERC20Token _targetToken,
uint256 _amount,
address _trader,
address payable _beneficiary
) external payable returns (uint256);
function conversionFee() external view returns (uint32);
function maxConversionFee() external view returns (uint32);
function reserveBalance(IERC20Token _reserveToken) external view returns (uint256);
receive() external payable;
function transferAnchorOwnership(address _newOwner) external;
function acceptAnchorOwnership() external;
function setConversionFee(uint32 _conversionFee) external;
function withdrawTokens(
IERC20Token _token,
address _to,
uint256 _amount
) external;
function withdrawETH(address payable _to) external;
function addReserve(IERC20Token _token, uint32 _ratio) external;
// deprecated, backward compatibility
function token() external view returns (IConverterAnchor);
function transferTokenOwnership(address _newOwner) external;
function acceptTokenOwnership() external;
function connectors(IERC20Token _address)
external
view
returns (
uint256,
uint32,
bool,
bool,
bool
);
function getConnectorBalance(IERC20Token _connectorToken) external view returns (uint256);
function connectorTokens(uint256 _index) external view returns (IERC20Token);
function connectorTokenCount() external view returns (uint16);
/**
* @dev triggered when the converter is activated
*
* @param _type converter type
* @param _anchor converter anchor
* @param _activated true if the converter was activated, false if it was deactivated
*/
event Activation(uint16 indexed _type, IConverterAnchor indexed _anchor, bool indexed _activated);
/**
* @dev triggered when a conversion between two tokens occurs
*
* @param _fromToken source ERC20 token
* @param _toToken target ERC20 token
* @param _trader wallet that initiated the trade
* @param _amount input amount in units of the source token
* @param _return output amount minus conversion fee in units of the target token
* @param _conversionFee conversion fee in units of the target token
*/
event Conversion(
IERC20Token indexed _fromToken,
IERC20Token indexed _toToken,
address indexed _trader,
uint256 _amount,
uint256 _return,
int256 _conversionFee
);
/**
* @dev triggered when the rate between two tokens in the converter changes
* note that the event might be dispatched for rate updates between any two tokens in the converter
*
* @param _token1 address of the first token
* @param _token2 address of the second token
* @param _rateN rate of 1 unit of `_token1` in `_token2` (numerator)
* @param _rateD rate of 1 unit of `_token1` in `_token2` (denominator)
*/
event TokenRateUpdate(IERC20Token indexed _token1, IERC20Token indexed _token2, uint256 _rateN, uint256 _rateD);
/**
* @dev triggered when the conversion fee is updated
*
* @param _prevFee previous fee percentage, represented in ppm
* @param _newFee new fee percentage, represented in ppm
*/
event ConversionFeeUpdate(uint32 _prevFee, uint32 _newFee);
}
// File: solidity/contracts/converter/interfaces/IConverterRegistry.sol
pragma solidity 0.6.12;
interface IConverterRegistry {
function getAnchorCount() external view returns (uint256);
function getAnchors() external view returns (address[] memory);
function getAnchor(uint256 _index) external view returns (IConverterAnchor);
function isAnchor(address _value) external view returns (bool);
function getLiquidityPoolCount() external view returns (uint256);
function getLiquidityPools() external view returns (address[] memory);
function getLiquidityPool(uint256 _index) external view returns (IConverterAnchor);
function isLiquidityPool(address _value) external view returns (bool);
function getConvertibleTokenCount() external view returns (uint256);
function getConvertibleTokens() external view returns (address[] memory);
function getConvertibleToken(uint256 _index) external view returns (IERC20Token);
function isConvertibleToken(address _value) external view returns (bool);
function getConvertibleTokenAnchorCount(IERC20Token _convertibleToken) external view returns (uint256);
function getConvertibleTokenAnchors(IERC20Token _convertibleToken) external view returns (address[] memory);
function getConvertibleTokenAnchor(IERC20Token _convertibleToken, uint256 _index)
external
view
returns (IConverterAnchor);
function isConvertibleTokenAnchor(IERC20Token _convertibleToken, address _value) external view returns (bool);
}
// File: solidity/contracts/liquidity-protection/LiquidityProtection.sol
pragma solidity 0.6.12;
interface ILiquidityPoolConverter is IConverter {
function addLiquidity(
IERC20Token[] memory _reserveTokens,
uint256[] memory _reserveAmounts,
uint256 _minReturn
) external payable;
function removeLiquidity(
uint256 _amount,
IERC20Token[] memory _reserveTokens,
uint256[] memory _reserveMinReturnAmounts
) external;
function recentAverageRate(IERC20Token _reserveToken) external view returns (uint256, uint256);
}
/**
* @dev This contract implements the liquidity protection mechanism.
*/
contract LiquidityProtection is ILiquidityProtection, TokenHandler, Utils, Owned, ReentrancyGuard, Time {
using SafeMath for uint256;
using MathEx for *;
struct ProtectedLiquidity {
address provider; // liquidity provider
IDSToken poolToken; // pool token address
IERC20Token reserveToken; // reserve token address
uint256 poolAmount; // pool token amount
uint256 reserveAmount; // reserve token amount
uint256 reserveRateN; // rate of 1 protected reserve token in units of the other reserve token (numerator)
uint256 reserveRateD; // rate of 1 protected reserve token in units of the other reserve token (denominator)
uint256 timestamp; // timestamp
}
// various rates between the two reserve tokens. the rate is of 1 unit of the protected reserve token in units of the other reserve token
struct PackedRates {
uint128 addSpotRateN; // spot rate of 1 A in units of B when liquidity was added (numerator)
uint128 addSpotRateD; // spot rate of 1 A in units of B when liquidity was added (denominator)
uint128 removeSpotRateN; // spot rate of 1 A in units of B when liquidity is removed (numerator)
uint128 removeSpotRateD; // spot rate of 1 A in units of B when liquidity is removed (denominator)
uint128 removeAverageRateN; // average rate of 1 A in units of B when liquidity is removed (numerator)
uint128 removeAverageRateD; // average rate of 1 A in units of B when liquidity is removed (denominator)
}
IERC20Token internal constant ETH_RESERVE_ADDRESS = IERC20Token(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
uint32 internal constant PPM_RESOLUTION = 1000000;
uint256 internal constant MAX_UINT128 = 2**128 - 1;
uint256 internal constant MAX_UINT256 = uint256(-1);
ILiquidityProtectionSettings public immutable override settings;
ILiquidityProtectionStore public immutable override store;
ILiquidityProtectionStats public immutable override stats;
ILiquidityProtectionSystemStore public immutable override systemStore;
ITokenHolder public immutable override wallet;
IERC20Token public immutable networkToken;
ITokenGovernance public immutable networkTokenGovernance;
IERC20Token public immutable govToken;
ITokenGovernance public immutable govTokenGovernance;
ICheckpointStore public immutable lastRemoveCheckpointStore;
ILiquidityProtectionEventsSubscriber public eventsSubscriber;
// true if the contract is currently adding/removing liquidity from a converter, used for accepting ETH
bool private updatingLiquidity = false;
/**
* @dev updates the event subscriber
*
* @param _prevEventsSubscriber the previous events subscriber
* @param _newEventsSubscriber the new events subscriber
*/
event EventSubscriberUpdated(
ILiquidityProtectionEventsSubscriber indexed _prevEventsSubscriber,
ILiquidityProtectionEventsSubscriber indexed _newEventsSubscriber
);
/**
* @dev initializes a new LiquidityProtection contract
*
* @param _contractAddresses:
* - [0] liquidity protection settings
* - [1] liquidity protection store
* - [2] liquidity protection stats
* - [3] liquidity protection system store
* - [4] liquidity protection wallet
* - [5] network token governance
* - [6] governance token governance
* - [7] last liquidity removal/unprotection checkpoints store
*/
constructor(address[8] memory _contractAddresses) public {
for (uint256 i = 0; i < _contractAddresses.length; i++) {
_validAddress(_contractAddresses[i]);
}
settings = ILiquidityProtectionSettings(_contractAddresses[0]);
store = ILiquidityProtectionStore(_contractAddresses[1]);
stats = ILiquidityProtectionStats(_contractAddresses[2]);
systemStore = ILiquidityProtectionSystemStore(_contractAddresses[3]);
wallet = ITokenHolder(_contractAddresses[4]);
networkTokenGovernance = ITokenGovernance(_contractAddresses[5]);
govTokenGovernance = ITokenGovernance(_contractAddresses[6]);
lastRemoveCheckpointStore = ICheckpointStore(_contractAddresses[7]);
networkToken = IERC20Token(address(ITokenGovernance(_contractAddresses[5]).token()));
govToken = IERC20Token(address(ITokenGovernance(_contractAddresses[6]).token()));
}
// ensures that the contract is currently removing liquidity from a converter
modifier updatingLiquidityOnly() {
require(updatingLiquidity, "ERR_NOT_UPDATING_LIQUIDITY");
_;
}
// ensures that the portion is valid
modifier validPortion(uint32 _portion) {
_validPortion(_portion);
_;
}
// error message binary size optimization
function _validPortion(uint32 _portion) internal pure {
require(_portion > 0 && _portion <= PPM_RESOLUTION, "ERR_INVALID_PORTION");
}
// ensures that the pool is supported and whitelisted
modifier poolSupportedAndWhitelisted(IConverterAnchor _poolAnchor) {
_poolSupported(_poolAnchor);
_poolWhitelisted(_poolAnchor);
_;
}
// error message binary size optimization
function _poolSupported(IConverterAnchor _poolAnchor) internal view {
require(settings.isPoolSupported(_poolAnchor), "ERR_POOL_NOT_SUPPORTED");
}
// error message binary size optimization
function _poolWhitelisted(IConverterAnchor _poolAnchor) internal view {
require(settings.isPoolWhitelisted(_poolAnchor), "ERR_POOL_NOT_WHITELISTED");
}
// error message binary size optimization
function verifyEthAmount(uint256 _value) internal view {
require(msg.value == _value, "ERR_ETH_AMOUNT_MISMATCH");
}
/**
* @dev accept ETH
* used when removing liquidity from ETH converters
*/
receive() external payable updatingLiquidityOnly() {}
/**
* @dev transfers the ownership of the store
* can only be called by the contract owner
*
* @param _newOwner the new owner of the store
*/
function transferStoreOwnership(address _newOwner) external ownerOnly {
store.transferOwnership(_newOwner);
}
/**
* @dev accepts the ownership of the store
* can only be called by the contract owner
*/
function acceptStoreOwnership() external ownerOnly {
store.acceptOwnership();
}
/**
* @dev transfers the ownership of the wallet
* can only be called by the contract owner
*
* @param _newOwner the new owner of the wallet
*/
function transferWalletOwnership(address _newOwner) external ownerOnly {
wallet.transferOwnership(_newOwner);
}
/**
* @dev accepts the ownership of the wallet
* can only be called by the contract owner
*/
function acceptWalletOwnership() external ownerOnly {
wallet.acceptOwnership();
}
/**
* @dev migrates all funds from the store to the wallet
* @dev migrates system balances from the store to the system-store
* @dev migrates minted amounts from the settings to the system-store
*/
function migrateData() external {
// save local copies of storage variables
address storeAddress = address(store);
address walletAddress = address(wallet);
IERC20Token networkTokenLocal = networkToken;
address[] memory poolWhitelist = settings.poolWhitelist();
for (uint256 i = 0; i < poolWhitelist.length; i++) {
IERC20Token poolToken = IERC20Token(poolWhitelist[i]);
store.withdrawTokens(poolToken, walletAddress, poolToken.balanceOf(storeAddress));
uint256 systemBalance = store.systemBalance(poolToken);
systemStore.incSystemBalance(poolToken, systemBalance);
store.decSystemBalance(poolToken, systemBalance);
uint256 networkTokensMinted = settings.networkTokensMinted(IConverterAnchor(address(poolToken)));
systemStore.incNetworkTokensMinted(IConverterAnchor(address(poolToken)), networkTokensMinted);
settings.decNetworkTokensMinted(IConverterAnchor(address(poolToken)), networkTokensMinted);
}
store.withdrawTokens(networkTokenLocal, walletAddress, networkTokenLocal.balanceOf(storeAddress));
}
/**
* @dev sets the events subscriber
*/
function setEventsSubscriber(ILiquidityProtectionEventsSubscriber _eventsSubscriber)
external
ownerOnly
validAddress(address(_eventsSubscriber))
notThis(address(_eventsSubscriber))
{
emit EventSubscriberUpdated(eventsSubscriber, _eventsSubscriber);
eventsSubscriber = _eventsSubscriber;
}
/**
* @dev adds protected liquidity to a pool for a specific recipient
* also mints new governance tokens for the caller if the caller adds network tokens
*
* @param _owner protected liquidity owner
* @param _poolAnchor anchor of the pool
* @param _reserveToken reserve token to add to the pool
* @param _amount amount of tokens to add to the pool
* @return new protected liquidity id
*/
function addLiquidityFor(
address _owner,
IConverterAnchor _poolAnchor,
IERC20Token _reserveToken,
uint256 _amount
)
external
payable
override
protected
validAddress(_owner)
poolSupportedAndWhitelisted(_poolAnchor)
greaterThanZero(_amount)
returns (uint256)
{
return addLiquidity(_owner, _poolAnchor, _reserveToken, _amount);
}
/**
* @dev adds protected liquidity to a pool
* also mints new governance tokens for the caller if the caller adds network tokens
*
* @param _poolAnchor anchor of the pool
* @param _reserveToken reserve token to add to the pool
* @param _amount amount of tokens to add to the pool
* @return new protected liquidity id
*/
function addLiquidity(
IConverterAnchor _poolAnchor,
IERC20Token _reserveToken,
uint256 _amount
)
external
payable
override
protected
poolSupportedAndWhitelisted(_poolAnchor)
greaterThanZero(_amount)
returns (uint256)
{
return addLiquidity(msg.sender, _poolAnchor, _reserveToken, _amount);
}
/**
* @dev adds protected liquidity to a pool for a specific recipient
* also mints new governance tokens for the caller if the caller adds network tokens
*
* @param _owner protected liquidity owner
* @param _poolAnchor anchor of the pool
* @param _reserveToken reserve token to add to the pool
* @param _amount amount of tokens to add to the pool
* @return new protected liquidity id
*/
function addLiquidity(
address _owner,
IConverterAnchor _poolAnchor,
IERC20Token _reserveToken,
uint256 _amount
) private returns (uint256) {
// save a local copy of `networkToken`
IERC20Token networkTokenLocal = networkToken;
if (_reserveToken == networkTokenLocal) {
verifyEthAmount(0);
return addNetworkTokenLiquidity(_owner, _poolAnchor, networkTokenLocal, _amount);
}
// verify that ETH was passed with the call if needed
verifyEthAmount(_reserveToken == ETH_RESERVE_ADDRESS ? _amount : 0);
return addBaseTokenLiquidity(_owner, _poolAnchor, _reserveToken, networkTokenLocal, _amount);
}
/**
* @dev adds protected network token liquidity to a pool
* also mints new governance tokens for the caller
*
* @param _owner protected liquidity owner
* @param _poolAnchor anchor of the pool
* @param _networkToken the network reserve token of the pool
* @param _amount amount of tokens to add to the pool
* @return new protected liquidity id
*/
function addNetworkTokenLiquidity(
address _owner,
IConverterAnchor _poolAnchor,
IERC20Token _networkToken,
uint256 _amount
) internal returns (uint256) {
IDSToken poolToken = IDSToken(address(_poolAnchor));
// get the rate between the pool token and the reserve
Fraction memory poolRate = poolTokenRate(poolToken, _networkToken);
// calculate the amount of pool tokens based on the amount of reserve tokens
uint256 poolTokenAmount = _amount.mul(poolRate.d).div(poolRate.n);
// remove the pool tokens from the system's ownership (will revert if not enough tokens are available)
systemStore.decSystemBalance(poolToken, poolTokenAmount);
// add protected liquidity for the recipient
uint256 id = addProtectedLiquidity(_owner, poolToken, _networkToken, poolTokenAmount, _amount);
// burns the network tokens from the caller. we need to transfer the tokens to the contract itself, since only
// token holders can burn their tokens
safeTransferFrom(_networkToken, msg.sender, address(this), _amount);
burnNetworkTokens(_poolAnchor, _amount);
// mint governance tokens to the recipient
govTokenGovernance.mint(_owner, _amount);
return id;
}
/**
* @dev adds protected base token liquidity to a pool
*
* @param _owner protected liquidity owner
* @param _poolAnchor anchor of the pool
* @param _baseToken the base reserve token of the pool
* @param _networkToken the network reserve token of the pool
* @param _amount amount of tokens to add to the pool
* @return new protected liquidity id
*/
function addBaseTokenLiquidity(
address _owner,
IConverterAnchor _poolAnchor,
IERC20Token _baseToken,
IERC20Token _networkToken,
uint256 _amount
) internal returns (uint256) {
IDSToken poolToken = IDSToken(address(_poolAnchor));
// get the reserve balances
ILiquidityPoolConverter converter = ILiquidityPoolConverter(payable(ownedBy(_poolAnchor)));
(uint256 reserveBalanceBase, uint256 reserveBalanceNetwork) =
converterReserveBalances(converter, _baseToken, _networkToken);
require(reserveBalanceNetwork >= settings.minNetworkTokenLiquidityForMinting(), "ERR_NOT_ENOUGH_LIQUIDITY");
// calculate and mint the required amount of network tokens for adding liquidity
uint256 newNetworkLiquidityAmount = _amount.mul(reserveBalanceNetwork).div(reserveBalanceBase);
// verify network token minting limit
uint256 mintingLimit = settings.networkTokenMintingLimits(_poolAnchor);
if (mintingLimit == 0) {
mintingLimit = settings.defaultNetworkTokenMintingLimit();
}
uint256 newNetworkTokensMinted = systemStore.networkTokensMinted(_poolAnchor).add(newNetworkLiquidityAmount);
require(newNetworkTokensMinted <= mintingLimit, "ERR_MAX_AMOUNT_REACHED");
// issue new network tokens to the system
mintNetworkTokens(address(this), _poolAnchor, newNetworkLiquidityAmount);
// transfer the base tokens from the caller and approve the converter
ensureAllowance(_networkToken, address(converter), newNetworkLiquidityAmount);
if (_baseToken != ETH_RESERVE_ADDRESS) {
safeTransferFrom(_baseToken, msg.sender, address(this), _amount);
ensureAllowance(_baseToken, address(converter), _amount);
}
// add liquidity
addLiquidity(converter, _baseToken, _networkToken, _amount, newNetworkLiquidityAmount, msg.value);
// transfer the new pool tokens to the wallet
uint256 poolTokenAmount = poolToken.balanceOf(address(this));
safeTransfer(poolToken, address(wallet), poolTokenAmount);
// the system splits the pool tokens with the caller
// increase the system's pool token balance and add protected liquidity for the caller
systemStore.incSystemBalance(poolToken, poolTokenAmount - poolTokenAmount / 2); // account for rounding errors
return addProtectedLiquidity(_owner, poolToken, _baseToken, poolTokenAmount / 2, _amount);
}
/**
* @dev returns the single-side staking limits of a given pool
*
* @param _poolAnchor anchor of the pool
* @return maximum amount of base tokens that can be single-side staked in the pool
* @return maximum amount of network tokens that can be single-side staked in the pool
*/
function poolAvailableSpace(IConverterAnchor _poolAnchor)
external
view
poolSupportedAndWhitelisted(_poolAnchor)
returns (uint256, uint256)
{
IERC20Token networkTokenLocal = networkToken;
return (
baseTokenAvailableSpace(_poolAnchor, networkTokenLocal),
networkTokenAvailableSpace(_poolAnchor, networkTokenLocal)
);
}
/**
* @dev returns the base-token staking limits of a given pool
*
* @param _poolAnchor anchor of the pool
* @return maximum amount of base tokens that can be single-side staked in the pool
*/
function baseTokenAvailableSpace(IConverterAnchor _poolAnchor)
external
view
poolSupportedAndWhitelisted(_poolAnchor)
returns (uint256)
{
return baseTokenAvailableSpace(_poolAnchor, networkToken);
}
/**
* @dev returns the network-token staking limits of a given pool
*
* @param _poolAnchor anchor of the pool
* @return maximum amount of network tokens that can be single-side staked in the pool
*/
function networkTokenAvailableSpace(IConverterAnchor _poolAnchor)
external
view
poolSupportedAndWhitelisted(_poolAnchor)
returns (uint256)
{
return networkTokenAvailableSpace(_poolAnchor, networkToken);
}
/**
* @dev returns the base-token staking limits of a given pool
*
* @param _poolAnchor anchor of the pool
* @param _networkToken the network token
* @return maximum amount of base tokens that can be single-side staked in the pool
*/
function baseTokenAvailableSpace(IConverterAnchor _poolAnchor, IERC20Token _networkToken)
internal
view
returns (uint256)
{
// get the pool converter
ILiquidityPoolConverter converter = ILiquidityPoolConverter(payable(ownedBy(_poolAnchor)));
// get the base token
IERC20Token baseToken = converterOtherReserve(converter, _networkToken);
// get the reserve balances
(uint256 reserveBalanceBase, uint256 reserveBalanceNetwork) =
converterReserveBalances(converter, baseToken, _networkToken);
// get the network token minting limit
uint256 mintingLimit = settings.networkTokenMintingLimits(_poolAnchor);
if (mintingLimit == 0) {
mintingLimit = settings.defaultNetworkTokenMintingLimit();
}
// get the amount of network tokens already minted for the pool
uint256 networkTokensMinted = systemStore.networkTokensMinted(_poolAnchor);
// get the amount of network tokens which can minted for the pool
uint256 networkTokensCanBeMinted = MathEx.max(mintingLimit, networkTokensMinted) - networkTokensMinted;
// return the maximum amount of base token liquidity that can be single-sided staked in the pool
return networkTokensCanBeMinted.mul(reserveBalanceBase).div(reserveBalanceNetwork);
}
/**
* @dev returns the network-token staking limits of a given pool
*
* @param _poolAnchor anchor of the pool
* @param _networkToken the network token
* @return maximum amount of network tokens that can be single-side staked in the pool
*/
function networkTokenAvailableSpace(IConverterAnchor _poolAnchor, IERC20Token _networkToken)
internal
view
returns (uint256)
{
// get the pool token
IDSToken poolToken = IDSToken(address(_poolAnchor));
// get the pool token rate
Fraction memory poolRate = poolTokenRate(poolToken, _networkToken);
// return the maximum amount of network token liquidity that can be single-sided staked in the pool
return systemStore.systemBalance(poolToken).mul(poolRate.n).add(poolRate.n).sub(1).div(poolRate.d);
}
/**
* @dev returns the expected/actual amounts the provider will receive for removing liquidity
* it's also possible to provide the remove liquidity time to get an estimation
* for the return at that given point
*
* @param _id protected liquidity id
* @param _portion portion of liquidity to remove, in PPM
* @param _removeTimestamp time at which the liquidity is removed
* @return expected return amount in the reserve token
* @return actual return amount in the reserve token
* @return compensation in the network token
*/
function removeLiquidityReturn(
uint256 _id,
uint32 _portion,
uint256 _removeTimestamp
)
external
view
validPortion(_portion)
returns (
uint256,
uint256,
uint256
)
{
ProtectedLiquidity memory liquidity = protectedLiquidity(_id);
// verify input
require(liquidity.provider != address(0), "ERR_INVALID_ID");
require(_removeTimestamp >= liquidity.timestamp, "ERR_INVALID_TIMESTAMP");
// calculate the portion of the liquidity to remove
if (_portion != PPM_RESOLUTION) {
liquidity.poolAmount = liquidity.poolAmount.mul(_portion) / PPM_RESOLUTION;
liquidity.reserveAmount = liquidity.reserveAmount.mul(_portion) / PPM_RESOLUTION;
}
// get the various rates between the reserves upon adding liquidity and now
PackedRates memory packedRates =
packRates(
liquidity.poolToken,
liquidity.reserveToken,
liquidity.reserveRateN,
liquidity.reserveRateD,
false
);
uint256 targetAmount =
removeLiquidityTargetAmount(
liquidity.poolToken,
liquidity.reserveToken,
liquidity.poolAmount,
liquidity.reserveAmount,
packedRates,
liquidity.timestamp,
_removeTimestamp
);
// for network token, the return amount is identical to the target amount
if (liquidity.reserveToken == networkToken) {
return (targetAmount, targetAmount, 0);
}
// handle base token return
// calculate the amount of pool tokens required for liquidation
// note that the amount is doubled since it's not possible to liquidate one reserve only
Fraction memory poolRate = poolTokenRate(liquidity.poolToken, liquidity.reserveToken);
uint256 poolAmount = targetAmount.mul(poolRate.d).div(poolRate.n / 2);
// limit the amount of pool tokens by the amount the system/caller holds
uint256 availableBalance = systemStore.systemBalance(liquidity.poolToken).add(liquidity.poolAmount);
poolAmount = poolAmount > availableBalance ? availableBalance : poolAmount;
// calculate the base token amount received by liquidating the pool tokens
// note that the amount is divided by 2 since the pool amount represents both reserves
uint256 baseAmount = poolAmount.mul(poolRate.n / 2).div(poolRate.d);
uint256 networkAmount = getNetworkCompensation(targetAmount, baseAmount, packedRates);
return (targetAmount, baseAmount, networkAmount);
}
/**
* @dev removes protected liquidity from a pool
* also burns governance tokens from the caller if the caller removes network tokens
*
* @param _id id in the caller's list of protected liquidity
* @param _portion portion of liquidity to remove, in PPM
*/
function removeLiquidity(uint256 _id, uint32 _portion) external override protected validPortion(_portion) {
removeLiquidity(msg.sender, _id, _portion);
}
/**
* @dev removes protected liquidity from a pool
* also burns governance tokens from the caller if the caller removes network tokens
*
* @param _provider protected liquidity provider
* @param _id id in the caller's list of protected liquidity
* @param _portion portion of liquidity to remove, in PPM
*/
function removeLiquidity(
address payable _provider,
uint256 _id,
uint32 _portion
) internal {
ProtectedLiquidity memory liquidity = protectedLiquidity(_id, _provider);
// save a local copy of `networkToken`
IERC20Token networkTokenLocal = networkToken;
// verify that the pool is whitelisted
_poolWhitelisted(liquidity.poolToken);
// verify that the protected liquidity is not removed on the same block in which it was added
require(liquidity.timestamp < time(), "ERR_TOO_EARLY");
if (_portion == PPM_RESOLUTION) {
// notify event subscribers
if (address(eventsSubscriber) != address(0)) {
eventsSubscriber.onRemovingLiquidity(
_id,
_provider,
liquidity.poolToken,
liquidity.reserveToken,
liquidity.poolAmount,
liquidity.reserveAmount
);
}
// remove the protected liquidity from the provider
store.removeProtectedLiquidity(_id);
} else {
// remove a portion of the protected liquidity from the provider
uint256 fullPoolAmount = liquidity.poolAmount;
uint256 fullReserveAmount = liquidity.reserveAmount;
liquidity.poolAmount = liquidity.poolAmount.mul(_portion) / PPM_RESOLUTION;
liquidity.reserveAmount = liquidity.reserveAmount.mul(_portion) / PPM_RESOLUTION;
// notify event subscribers
if (address(eventsSubscriber) != address(0)) {
eventsSubscriber.onRemovingLiquidity(
_id,
_provider,
liquidity.poolToken,
liquidity.reserveToken,
liquidity.poolAmount,
liquidity.reserveAmount
);
}
store.updateProtectedLiquidityAmounts(
_id,
fullPoolAmount - liquidity.poolAmount,
fullReserveAmount - liquidity.reserveAmount
);
}
// update the statistics
stats.decreaseTotalAmounts(
liquidity.provider,
liquidity.poolToken,
liquidity.reserveToken,
liquidity.poolAmount,
liquidity.reserveAmount
);
// update last liquidity removal checkpoint
lastRemoveCheckpointStore.addCheckpoint(_provider);
// add the pool tokens to the system
systemStore.incSystemBalance(liquidity.poolToken, liquidity.poolAmount);
// if removing network token liquidity, burn the governance tokens from the caller. we need to transfer the
// tokens to the contract itself, since only token holders can burn their tokens
if (liquidity.reserveToken == networkTokenLocal) {
safeTransferFrom(govToken, _provider, address(this), liquidity.reserveAmount);
govTokenGovernance.burn(liquidity.reserveAmount);
}
// get the various rates between the reserves upon adding liquidity and now
PackedRates memory packedRates =
packRates(
liquidity.poolToken,
liquidity.reserveToken,
liquidity.reserveRateN,
liquidity.reserveRateD,
true
);
// get the target token amount
uint256 targetAmount =
removeLiquidityTargetAmount(
liquidity.poolToken,
liquidity.reserveToken,
liquidity.poolAmount,
liquidity.reserveAmount,
packedRates,
liquidity.timestamp,
time()
);
// remove network token liquidity
if (liquidity.reserveToken == networkTokenLocal) {
// mint network tokens for the caller and lock them
mintNetworkTokens(address(wallet), liquidity.poolToken, targetAmount);
lockTokens(_provider, targetAmount);
return;
}
// remove base token liquidity
// calculate the amount of pool tokens required for liquidation
// note that the amount is doubled since it's not possible to liquidate one reserve only
Fraction memory poolRate = poolTokenRate(liquidity.poolToken, liquidity.reserveToken);
uint256 poolAmount = targetAmount.mul(poolRate.d).div(poolRate.n / 2);
// limit the amount of pool tokens by the amount the system holds
uint256 systemBalance = systemStore.systemBalance(liquidity.poolToken);
poolAmount = poolAmount > systemBalance ? systemBalance : poolAmount;
// withdraw the pool tokens from the wallet
systemStore.decSystemBalance(liquidity.poolToken, poolAmount);
wallet.withdrawTokens(liquidity.poolToken, address(this), poolAmount);
// remove liquidity
removeLiquidity(liquidity.poolToken, poolAmount, liquidity.reserveToken, networkTokenLocal);
// transfer the base tokens to the caller
uint256 baseBalance;
if (liquidity.reserveToken == ETH_RESERVE_ADDRESS) {
baseBalance = address(this).balance;
_provider.transfer(baseBalance);
} else {
baseBalance = liquidity.reserveToken.balanceOf(address(this));
safeTransfer(liquidity.reserveToken, _provider, baseBalance);
}
// compensate the caller with network tokens if still needed
uint256 delta = getNetworkCompensation(targetAmount, baseBalance, packedRates);
if (delta > 0) {
// check if there's enough network token balance, otherwise mint more
uint256 networkBalance = networkTokenLocal.balanceOf(address(this));
if (networkBalance < delta) {
networkTokenGovernance.mint(address(this), delta - networkBalance);
}
// lock network tokens for the caller
safeTransfer(networkTokenLocal, address(wallet), delta);
lockTokens(_provider, delta);
}
// if the contract still holds network tokens, burn them
uint256 networkBalance = networkTokenLocal.balanceOf(address(this));
if (networkBalance > 0) {
burnNetworkTokens(liquidity.poolToken, networkBalance);
}
}
/**
* @dev returns the amount the provider will receive for removing liquidity
* it's also possible to provide the remove liquidity rate & time to get an estimation
* for the return at that given point
*
* @param _poolToken pool token
* @param _reserveToken reserve token
* @param _poolAmount pool token amount when the liquidity was added
* @param _reserveAmount reserve token amount that was added
* @param _packedRates see `struct PackedRates`
* @param _addTimestamp time at which the liquidity was added
* @param _removeTimestamp time at which the liquidity is removed
* @return amount received for removing liquidity
*/
function removeLiquidityTargetAmount(
IDSToken _poolToken,
IERC20Token _reserveToken,
uint256 _poolAmount,
uint256 _reserveAmount,
PackedRates memory _packedRates,
uint256 _addTimestamp,
uint256 _removeTimestamp
) internal view returns (uint256) {
// get the rate between the pool token and the reserve token
Fraction memory poolRate = poolTokenRate(_poolToken, _reserveToken);
// get the rate between the reserves upon adding liquidity and now
Fraction memory addSpotRate = Fraction({ n: _packedRates.addSpotRateN, d: _packedRates.addSpotRateD });
Fraction memory removeSpotRate = Fraction({ n: _packedRates.removeSpotRateN, d: _packedRates.removeSpotRateD });
Fraction memory removeAverageRate =
Fraction({ n: _packedRates.removeAverageRateN, d: _packedRates.removeAverageRateD });
// calculate the protected amount of reserve tokens plus accumulated fee before compensation
uint256 total = protectedAmountPlusFee(_poolAmount, poolRate, addSpotRate, removeSpotRate);
// calculate the impermanent loss
Fraction memory loss = impLoss(addSpotRate, removeAverageRate);
// calculate the protection level
Fraction memory level = protectionLevel(_addTimestamp, _removeTimestamp);
// calculate the compensation amount
return compensationAmount(_reserveAmount, MathEx.max(_reserveAmount, total), loss, level);
}
/**
* @dev allows the caller to claim network token balance that is no longer locked
* note that the function can revert if the range is too large
*
* @param _startIndex start index in the caller's list of locked balances
* @param _endIndex end index in the caller's list of locked balances (exclusive)
*/
function claimBalance(uint256 _startIndex, uint256 _endIndex) external protected {
// get the locked balances from the store
(uint256[] memory amounts, uint256[] memory expirationTimes) =
store.lockedBalanceRange(msg.sender, _startIndex, _endIndex);
uint256 totalAmount = 0;
uint256 length = amounts.length;
assert(length == expirationTimes.length);
// reverse iteration since we're removing from the list
for (uint256 i = length; i > 0; i--) {
uint256 index = i - 1;
if (expirationTimes[index] > time()) {
continue;
}
// remove the locked balance item
store.removeLockedBalance(msg.sender, _startIndex + index);
totalAmount = totalAmount.add(amounts[index]);
}
if (totalAmount > 0) {
// transfer the tokens to the caller in a single call
wallet.withdrawTokens(networkToken, msg.sender, totalAmount);
}
}
/**
* @dev returns the ROI for removing liquidity in the current state after providing liquidity with the given args
* the function assumes full protection is in effect
* return value is in PPM and can be larger than PPM_RESOLUTION for positive ROI, 1M = 0% ROI
*
* @param _poolToken pool token
* @param _reserveToken reserve token
* @param _reserveAmount reserve token amount that was added
* @param _poolRateN rate of 1 pool token in reserve token units when the liquidity was added (numerator)
* @param _poolRateD rate of 1 pool token in reserve token units when the liquidity was added (denominator)
* @param _reserveRateN rate of 1 reserve token in the other reserve token units when the liquidity was added (numerator)
* @param _reserveRateD rate of 1 reserve token in the other reserve token units when the liquidity was added (denominator)
* @return ROI in PPM
*/
function poolROI(
IDSToken _poolToken,
IERC20Token _reserveToken,
uint256 _reserveAmount,
uint256 _poolRateN,
uint256 _poolRateD,
uint256 _reserveRateN,
uint256 _reserveRateD
) external view returns (uint256) {
// calculate the amount of pool tokens based on the amount of reserve tokens
uint256 poolAmount = _reserveAmount.mul(_poolRateD).div(_poolRateN);
// get the various rates between the reserves upon adding liquidity and now
PackedRates memory packedRates = packRates(_poolToken, _reserveToken, _reserveRateN, _reserveRateD, false);
// get the current return
uint256 protectedReturn =
removeLiquidityTargetAmount(
_poolToken,
_reserveToken,
poolAmount,
_reserveAmount,
packedRates,
time().sub(settings.maxProtectionDelay()),
time()
);
// calculate the ROI as the ratio between the current fully protected return and the initial amount
return protectedReturn.mul(PPM_RESOLUTION).div(_reserveAmount);
}
/**
* @dev adds protected liquidity for the caller to the store
*
* @param _provider protected liquidity provider
* @param _poolToken pool token
* @param _reserveToken reserve token
* @param _poolAmount amount of pool tokens to protect
* @param _reserveAmount amount of reserve tokens to protect
* @return new protected liquidity id
*/
function addProtectedLiquidity(
address _provider,
IDSToken _poolToken,
IERC20Token _reserveToken,
uint256 _poolAmount,
uint256 _reserveAmount
) internal returns (uint256) {
// notify event subscribers
if (address(eventsSubscriber) != address(0)) {
eventsSubscriber.onAddingLiquidity(_provider, _poolToken, _reserveToken, _poolAmount, _reserveAmount);
}
Fraction memory rate = reserveTokenAverageRate(_poolToken, _reserveToken, true);
stats.increaseTotalAmounts(_provider, _poolToken, _reserveToken, _poolAmount, _reserveAmount);
stats.addProviderPool(_provider, _poolToken);
return
store.addProtectedLiquidity(
_provider,
_poolToken,
_reserveToken,
_poolAmount,
_reserveAmount,
rate.n,
rate.d,
time()
);
}
/**
* @dev locks network tokens for the provider and emits the tokens locked event
*
* @param _provider tokens provider
* @param _amount amount of network tokens
*/
function lockTokens(address _provider, uint256 _amount) internal {
uint256 expirationTime = time().add(settings.lockDuration());
store.addLockedBalance(_provider, _amount, expirationTime);
}
/**
* @dev returns the rate of 1 pool token in reserve token units
*
* @param _poolToken pool token
* @param _reserveToken reserve token
*/
function poolTokenRate(IDSToken _poolToken, IERC20Token _reserveToken)
internal
view
virtual
returns (Fraction memory)
{
// get the pool token supply
uint256 poolTokenSupply = _poolToken.totalSupply();
// get the reserve balance
IConverter converter = IConverter(payable(ownedBy(_poolToken)));
uint256 reserveBalance = converter.getConnectorBalance(_reserveToken);
// for standard pools, 50% of the pool supply value equals the value of each reserve
return Fraction({ n: reserveBalance.mul(2), d: poolTokenSupply });
}
/**
* @dev returns the average rate of 1 reserve token in the other reserve token units
*
* @param _poolToken pool token
* @param _reserveToken reserve token
* @param _validateAverageRate true to validate the average rate; false otherwise
*/
function reserveTokenAverageRate(
IDSToken _poolToken,
IERC20Token _reserveToken,
bool _validateAverageRate
) internal view returns (Fraction memory) {
(, , uint256 averageRateN, uint256 averageRateD) =
reserveTokenRates(_poolToken, _reserveToken, _validateAverageRate);
return Fraction(averageRateN, averageRateD);
}
/**
* @dev returns the spot rate and average rate of 1 reserve token in the other reserve token units
*
* @param _poolToken pool token
* @param _reserveToken reserve token
* @param _validateAverageRate true to validate the average rate; false otherwise
*/
function reserveTokenRates(
IDSToken _poolToken,
IERC20Token _reserveToken,
bool _validateAverageRate
)
internal
view
returns (
uint256,
uint256,
uint256,
uint256
)
{
ILiquidityPoolConverter converter = ILiquidityPoolConverter(payable(ownedBy(_poolToken)));
IERC20Token otherReserve = converterOtherReserve(converter, _reserveToken);
(uint256 spotRateN, uint256 spotRateD) = converterReserveBalances(converter, otherReserve, _reserveToken);
(uint256 averageRateN, uint256 averageRateD) = converter.recentAverageRate(_reserveToken);
require(
!_validateAverageRate ||
averageRateInRange(
spotRateN,
spotRateD,
averageRateN,
averageRateD,
settings.averageRateMaxDeviation()
),
"ERR_INVALID_RATE"
);
return (spotRateN, spotRateD, averageRateN, averageRateD);
}
/**
* @dev returns the various rates between the reserves
*
* @param _poolToken pool token
* @param _reserveToken reserve token
* @param _addSpotRateN add spot rate numerator
* @param _addSpotRateD add spot rate denominator
* @param _validateAverageRate true to validate the average rate; false otherwise
* @return see `struct PackedRates`
*/
function packRates(
IDSToken _poolToken,
IERC20Token _reserveToken,
uint256 _addSpotRateN,
uint256 _addSpotRateD,
bool _validateAverageRate
) internal view returns (PackedRates memory) {
(uint256 removeSpotRateN, uint256 removeSpotRateD, uint256 removeAverageRateN, uint256 removeAverageRateD) =
reserveTokenRates(_poolToken, _reserveToken, _validateAverageRate);
require(
(_addSpotRateN <= MAX_UINT128 && _addSpotRateD <= MAX_UINT128) &&
(removeSpotRateN <= MAX_UINT128 && removeSpotRateD <= MAX_UINT128) &&
(removeAverageRateN <= MAX_UINT128 && removeAverageRateD <= MAX_UINT128),
"ERR_INVALID_RATE"
);
return
PackedRates({
addSpotRateN: uint128(_addSpotRateN),
addSpotRateD: uint128(_addSpotRateD),
removeSpotRateN: uint128(removeSpotRateN),
removeSpotRateD: uint128(removeSpotRateD),
removeAverageRateN: uint128(removeAverageRateN),
removeAverageRateD: uint128(removeAverageRateD)
});
}
/**
* @dev returns whether or not the deviation of the average rate from the spot rate is within range
* for example, if the maximum permitted deviation is 5%, then return `95/100 <= average/spot <= 100/95`
*
* @param _spotRateN spot rate numerator
* @param _spotRateD spot rate denominator
* @param _averageRateN average rate numerator
* @param _averageRateD average rate denominator
* @param _maxDeviation the maximum permitted deviation of the average rate from the spot rate
*/
function averageRateInRange(
uint256 _spotRateN,
uint256 _spotRateD,
uint256 _averageRateN,
uint256 _averageRateD,
uint32 _maxDeviation
) internal pure returns (bool) {
uint256 ppmDelta = PPM_RESOLUTION - _maxDeviation;
uint256 min = _spotRateN.mul(_averageRateD).mul(ppmDelta).mul(ppmDelta);
uint256 mid = _spotRateD.mul(_averageRateN).mul(ppmDelta).mul(PPM_RESOLUTION);
uint256 max = _spotRateN.mul(_averageRateD).mul(PPM_RESOLUTION).mul(PPM_RESOLUTION);
return min <= mid && mid <= max;
}
/**
* @dev utility to add liquidity to a converter
*
* @param _converter converter
* @param _reserveToken1 reserve token 1
* @param _reserveToken2 reserve token 2
* @param _reserveAmount1 reserve amount 1
* @param _reserveAmount2 reserve amount 2
* @param _value ETH amount to add
*/
function addLiquidity(
ILiquidityPoolConverter _converter,
IERC20Token _reserveToken1,
IERC20Token _reserveToken2,
uint256 _reserveAmount1,
uint256 _reserveAmount2,
uint256 _value
) internal {
// ensure that the contract can receive ETH
updatingLiquidity = true;
IERC20Token[] memory reserveTokens = new IERC20Token[](2);
uint256[] memory amounts = new uint256[](2);
reserveTokens[0] = _reserveToken1;
reserveTokens[1] = _reserveToken2;
amounts[0] = _reserveAmount1;
amounts[1] = _reserveAmount2;
_converter.addLiquidity{ value: _value }(reserveTokens, amounts, 1);
// ensure that the contract can receive ETH
updatingLiquidity = false;
}
/**
* @dev utility to remove liquidity from a converter
*
* @param _poolToken pool token of the converter
* @param _poolAmount amount of pool tokens to remove
* @param _reserveToken1 reserve token 1
* @param _reserveToken2 reserve token 2
*/
function removeLiquidity(
IDSToken _poolToken,
uint256 _poolAmount,
IERC20Token _reserveToken1,
IERC20Token _reserveToken2
) internal {
ILiquidityPoolConverter converter = ILiquidityPoolConverter(payable(ownedBy(_poolToken)));
// ensure that the contract can receive ETH
updatingLiquidity = true;
IERC20Token[] memory reserveTokens = new IERC20Token[](2);
uint256[] memory minReturns = new uint256[](2);
reserveTokens[0] = _reserveToken1;
reserveTokens[1] = _reserveToken2;
minReturns[0] = 1;
minReturns[1] = 1;
converter.removeLiquidity(_poolAmount, reserveTokens, minReturns);
// ensure that the contract can receive ETH
updatingLiquidity = false;
}
/**
* @dev returns a protected liquidity from the store
*
* @param _id protected liquidity id
* @return protected liquidity
*/
function protectedLiquidity(uint256 _id) internal view returns (ProtectedLiquidity memory) {
ProtectedLiquidity memory liquidity;
(
liquidity.provider,
liquidity.poolToken,
liquidity.reserveToken,
liquidity.poolAmount,
liquidity.reserveAmount,
liquidity.reserveRateN,
liquidity.reserveRateD,
liquidity.timestamp
) = store.protectedLiquidity(_id);
return liquidity;
}
/**
* @dev returns a protected liquidity from the store
*
* @param _id protected liquidity id
* @param _provider authorized provider
* @return protected liquidity
*/
function protectedLiquidity(uint256 _id, address _provider) internal view returns (ProtectedLiquidity memory) {
ProtectedLiquidity memory liquidity = protectedLiquidity(_id);
require(liquidity.provider == _provider, "ERR_ACCESS_DENIED");
return liquidity;
}
/**
* @dev returns the protected amount of reserve tokens plus accumulated fee before compensation
*
* @param _poolAmount pool token amount when the liquidity was added
* @param _poolRate rate of 1 pool token in the related reserve token units
* @param _addRate rate of 1 reserve token in the other reserve token units when the liquidity was added
* @param _removeRate rate of 1 reserve token in the other reserve token units when the liquidity is removed
* @return protected amount of reserve tokens plus accumulated fee = sqrt(_removeRate / _addRate) * _poolRate * _poolAmount
*/
function protectedAmountPlusFee(
uint256 _poolAmount,
Fraction memory _poolRate,
Fraction memory _addRate,
Fraction memory _removeRate
) internal pure returns (uint256) {
uint256 n = MathEx.ceilSqrt(_addRate.d.mul(_removeRate.n)).mul(_poolRate.n);
uint256 d = MathEx.floorSqrt(_addRate.n.mul(_removeRate.d)).mul(_poolRate.d);
uint256 x = n * _poolAmount;
if (x / n == _poolAmount) {
return x / d;
}
(uint256 hi, uint256 lo) = n > _poolAmount ? (n, _poolAmount) : (_poolAmount, n);
(uint256 p, uint256 q) = MathEx.reducedRatio(hi, d, MAX_UINT256 / lo);
uint256 min = (hi / d).mul(lo);
if (q > 0) {
return MathEx.max(min, (p * lo) / q);
}
return min;
}
/**
* @dev returns the impermanent loss incurred due to the change in rates between the reserve tokens
*
* @param _prevRate previous rate between the reserves
* @param _newRate new rate between the reserves
* @return impermanent loss (as a ratio)
*/
function impLoss(Fraction memory _prevRate, Fraction memory _newRate) internal pure returns (Fraction memory) {
uint256 ratioN = _newRate.n.mul(_prevRate.d);
uint256 ratioD = _newRate.d.mul(_prevRate.n);
uint256 prod = ratioN * ratioD;
uint256 root =
prod / ratioN == ratioD ? MathEx.floorSqrt(prod) : MathEx.floorSqrt(ratioN) * MathEx.floorSqrt(ratioD);
uint256 sum = ratioN.add(ratioD);
// the arithmetic below is safe because `x + y >= sqrt(x * y) * 2`
if (sum % 2 == 0) {
sum /= 2;
return Fraction({ n: sum - root, d: sum });
}
return Fraction({ n: sum - root * 2, d: sum });
}
/**
* @dev returns the protection level based on the timestamp and protection delays
*
* @param _addTimestamp time at which the liquidity was added
* @param _removeTimestamp time at which the liquidity is removed
* @return protection level (as a ratio)
*/
function protectionLevel(uint256 _addTimestamp, uint256 _removeTimestamp) internal view returns (Fraction memory) {
uint256 timeElapsed = _removeTimestamp.sub(_addTimestamp);
uint256 minProtectionDelay = settings.minProtectionDelay();
uint256 maxProtectionDelay = settings.maxProtectionDelay();
if (timeElapsed < minProtectionDelay) {
return Fraction({ n: 0, d: 1 });
}
if (timeElapsed >= maxProtectionDelay) {
return Fraction({ n: 1, d: 1 });
}
return Fraction({ n: timeElapsed, d: maxProtectionDelay });
}
/**
* @dev returns the compensation amount based on the impermanent loss and the protection level
*
* @param _amount protected amount in units of the reserve token
* @param _total amount plus fee in units of the reserve token
* @param _loss protection level (as a ratio between 0 and 1)
* @param _level impermanent loss (as a ratio between 0 and 1)
* @return compensation amount
*/
function compensationAmount(
uint256 _amount,
uint256 _total,
Fraction memory _loss,
Fraction memory _level
) internal pure returns (uint256) {
uint256 levelN = _level.n.mul(_amount);
uint256 levelD = _level.d;
uint256 maxVal = MathEx.max(MathEx.max(levelN, levelD), _total);
(uint256 lossN, uint256 lossD) = MathEx.reducedRatio(_loss.n, _loss.d, MAX_UINT256 / maxVal);
return _total.mul(lossD.sub(lossN)).div(lossD).add(lossN.mul(levelN).div(lossD.mul(levelD)));
}
function getNetworkCompensation(
uint256 _targetAmount,
uint256 _baseAmount,
PackedRates memory _packedRates
) internal view returns (uint256) {
if (_targetAmount <= _baseAmount) {
return 0;
}
// calculate the delta in network tokens
uint256 delta =
(_targetAmount - _baseAmount).mul(_packedRates.removeAverageRateN).div(_packedRates.removeAverageRateD);
// the delta might be very small due to precision loss
// in which case no compensation will take place (gas optimization)
if (delta >= settings.minNetworkCompensation()) {
return delta;
}
return 0;
}
/**
* @dev utility, checks whether allowance for the given spender exists and approves one if it doesn't.
* note that we use the non standard erc-20 interface in which `approve` has no return value so that
* this function will work for both standard and non standard tokens
*
* @param _token token to check the allowance in
* @param _spender approved address
* @param _value allowance amount
*/
function ensureAllowance(
IERC20Token _token,
address _spender,
uint256 _value
) private {
uint256 allowance = _token.allowance(address(this), _spender);
if (allowance < _value) {
if (allowance > 0) safeApprove(_token, _spender, 0);
safeApprove(_token, _spender, _value);
}
}
// utility to mint network tokens
function mintNetworkTokens(
address _owner,
IConverterAnchor _poolAnchor,
uint256 _amount
) private {
networkTokenGovernance.mint(_owner, _amount);
systemStore.incNetworkTokensMinted(_poolAnchor, _amount);
}
// utility to burn network tokens
function burnNetworkTokens(IConverterAnchor _poolAnchor, uint256 _amount) private {
networkTokenGovernance.burn(_amount);
systemStore.decNetworkTokensMinted(_poolAnchor, _amount);
}
// utility to get the reserve balances
function converterReserveBalances(
IConverter _converter,
IERC20Token _reserveToken1,
IERC20Token _reserveToken2
) private view returns (uint256, uint256) {
return (_converter.getConnectorBalance(_reserveToken1), _converter.getConnectorBalance(_reserveToken2));
}
// utility to get the other reserve
function converterOtherReserve(IConverter _converter, IERC20Token _thisReserve) private view returns (IERC20Token) {
IERC20Token otherReserve = _converter.connectorTokens(0);
return otherReserve != _thisReserve ? otherReserve : _converter.connectorTokens(1);
}
// utility to get the owner
function ownedBy(IOwned _owned) private view returns (address) {
return _owned.owner();
}
}
|
returns the ROI for removing liquidity in the current state after providing liquidity with the given args the function assumes full protection is in effect return value is in PPM and can be larger than PPM_RESOLUTION for positive ROI, 1M = 0% ROI _poolToken pool token _reserveToken reserve token _reserveAmount reserve token amount that was added _poolRateN rate of 1 pool token in reserve token units when the liquidity was added (numerator) _poolRateD rate of 1 pool token in reserve token units when the liquidity was added (denominator) _reserveRateN rate of 1 reserve token in the other reserve token units when the liquidity was added (numerator) _reserveRateD rate of 1 reserve token in the other reserve token units when the liquidity was added (denominator) return ROI in PPM/ calculate the amount of pool tokens based on the amount of reserve tokens get the various rates between the reserves upon adding liquidity and now get the current return calculate the ROI as the ratio between the current fully protected return and the initial amount
|
function poolROI(
IDSToken _poolToken,
IERC20Token _reserveToken,
uint256 _reserveAmount,
uint256 _poolRateN,
uint256 _poolRateD,
uint256 _reserveRateN,
uint256 _reserveRateD
) external view returns (uint256) {
uint256 poolAmount = _reserveAmount.mul(_poolRateD).div(_poolRateN);
PackedRates memory packedRates = packRates(_poolToken, _reserveToken, _reserveRateN, _reserveRateD, false);
uint256 protectedReturn =
removeLiquidityTargetAmount(
_poolToken,
_reserveToken,
poolAmount,
_reserveAmount,
packedRates,
time().sub(settings.maxProtectionDelay()),
time()
);
return protectedReturn.mul(PPM_RESOLUTION).div(_reserveAmount);
}
| 2,294,292
|
./partial_match/1/0x6D0B05ef27C5D5A0783e86F6056B531616284D14/sources/contracts/RadbroWebringV2.sol
|
Set the price of a radbro in ETH.
|
function setETHPrice(uint256 _ethPrice) external onlyOperator {
ethPrice = _ethPrice;
}
| 3,621,255
|
/*
Copyright 2018 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.4.24;
import { AddressArrayUtils } from "cryptofin-solidity/contracts/array-utils/AddressArrayUtils.sol";
import { DetailedERC20 } from "zeppelin-solidity/contracts/token/ERC20/DetailedERC20.sol";
import { Math } from "zeppelin-solidity/contracts/math/Math.sol";
import { SafeMath } from "zeppelin-solidity/contracts/math/SafeMath.sol";
import { StandardToken } from "zeppelin-solidity/contracts/token/ERC20/StandardToken.sol";
import { Bytes32 } from "../lib/Bytes32.sol";
import { CommonMath } from "../lib/CommonMath.sol";
import { ERC20Wrapper } from "../lib/ERC20Wrapper.sol";
import { IAuctionPriceCurve } from "./lib/auction-price-libraries/IAuctionPriceCurve.sol";
import { ICore } from "./interfaces/ICore.sol";
import { IRebalancingSetFactory } from "./interfaces/IRebalancingSetFactory.sol";
import { ISetToken } from "./interfaces/ISetToken.sol";
import { IVault } from "./interfaces/IVault.sol";
/**
* @title SetToken
* @author Set Protocol
*
* Implementation of Rebalancing Set token.
*/
contract RebalancingSetToken is
StandardToken,
DetailedERC20
{
using SafeMath for uint256;
using Bytes32 for bytes32;
using AddressArrayUtils for address[];
/* ============ Enums ============ */
enum State { Default, Proposal, Rebalance }
/* ============ State Variables ============ */
address public factory;
// All rebalancingSetTokens have same natural unit, still allows for
// small amounts to be issued and attempts to reduce slippage as much
// as possible.
uint256 public naturalUnit = 10 ** 10;
address public manager;
State public rebalanceState;
// State updated after every rebalance
address public currentSet;
uint256 public unitShares;
uint256 public lastRebalanceTimestamp;
// Fee setting, values in basis points
uint256 public entranceFee;
uint256 public rebalanceFee;
// State governing rebalance cycle
uint256 public proposalPeriod;
uint256 public rebalanceInterval;
// State to track proposal period
uint256 public proposalStartTime;
// State needed for auction/rebalance
uint256 public auctionStartTime;
address public nextSet;
address public auctionLibrary;
uint256 public auctionPriceDivisor;
uint256 public auctionStartPrice;
uint256 public minimumBid;
uint256 public curveCoefficient;
address[] public combinedTokenArray;
uint256[] public combinedCurrentUnits;
uint256[] public combinedNextSetUnits;
uint256 public remainingCurrentSets;
/* ============ Events ============ */
event NewManagerAdded(
address newManager,
address oldManager
);
event RebalanceProposed(
address nextSet,
address indexed auctionLibrary,
uint256 indexed proposalPeriodEndTime
);
event RebalanceStarted(
address oldSet,
address newSet
);
/* ============ Constructor ============ */
/**
* Constructor function for Rebalancing Set Token
*
*
* @param _factory Factory used to create the Rebalancing Set
* @param _manager Manager of the Rebalancing Set
* @param _initialSet Initial set that collateralizes the Rebalancing set
* @param _initialUnitShares Units of currentSet that equals one share
* @param _proposalPeriod Amount of time for users to inspect a rebalance proposal
* @param _rebalanceInterval Minimum amount of time between rebalances
* @param _entranceFee Entrance fee as a percentage of initialSet when minting the Rebalancing Set
* @param _rebalanceFee Rebalance fee as a percentage of the nextSet when rebalance is settled
* @param _name The bytes32 encoded name of the new RebalancingSetToken
* @param _symbol The bytes32 encoded symbol of the new RebalancingSetToken
*/
constructor(
address _factory,
address _manager,
address _initialSet,
uint256 _initialUnitShares,
uint256 _proposalPeriod,
uint256 _rebalanceInterval,
uint256 _entranceFee,
uint256 _rebalanceFee,
bytes32 _name,
bytes32 _symbol
)
public
DetailedERC20(
_name.bytes32ToString(),
_symbol.bytes32ToString(),
18
)
{
// Require initial unit shares is non-zero
require(_initialUnitShares > 0, "UNIT_SHARES_MUST_BE_NON_ZERO");
// Require manager address is non-zero
require(_manager != address(0), "MANAGER_MUST_BE_NON_NULL");
// Require minimum rebalance interval and proposal period from factory
IRebalancingSetFactory tokenFactory = IRebalancingSetFactory(_factory);
require(_proposalPeriod >= tokenFactory.minimumProposalPeriod(), "PROPOSAL_PERIOD_TOO_SHORT");
require(_rebalanceInterval >= tokenFactory.minimumRebalanceInterval(), "REBALANCE_INTERVAL_TOO_SHORT");
factory = _factory;
manager = _manager;
entranceFee = _entranceFee;
rebalanceFee = _rebalanceFee;
currentSet = _initialSet;
unitShares = _initialUnitShares;
proposalPeriod = _proposalPeriod;
rebalanceInterval = _rebalanceInterval;
lastRebalanceTimestamp = block.timestamp;
rebalanceState = State.Default;
}
/* ============ Public Functions ============ */
/**
* Function used to set the terms of the next rebalance and start the proposal period
*
*
* @param _nextSet The Set to rebalance into
* @param _auctionLibrary The library used to calculate the Dutch Auction price
* @param _curveCoefficient The slope (or convexity) of the price curve
* @param _auctionPriceDivisor The granularity with which the prices change
* @param _auctionStartPrice The price to start the auction at
*/
function propose(
address _nextSet,
address _auctionLibrary,
uint256 _curveCoefficient,
uint256 _auctionStartPrice,
uint256 _auctionPriceDivisor
)
external
{
ICore core = ICore(IRebalancingSetFactory(factory).core());
// Make sure it is manager that is proposing the rebalance
require(msg.sender == manager, "ONLY_MANAGER_CAN_PROPOSE");
// New proposal cannot be made during a rebalance period
require(rebalanceState != State.Rebalance, "PROPOSE_CALLED_DURING_REBALANCE");
// Make sure enough time has passed from last rebalance to start a new proposal
require(block.timestamp >= lastRebalanceTimestamp.add(rebalanceInterval), "PROPOSE_CALLED_TOO_EARLY");
// Check that new proposed Set is valid Set created by Core
require(core.validSets(_nextSet), "PROPOSED_SET_INVALID");
// Check that the auction library is a valid priceLibrary tracked by Core
require(core.validPriceLibraries(_auctionLibrary), "PRICE_LIB_MUST_BE_VALID");
// Assert price divisor is non-zero, ensuring a positive slope
require(_auctionPriceDivisor > 0, "PRICE_DIV_MUST_BE_NON_ZERO");
// Assert curve coefficient > 0, ensuring a positive slope
require(_curveCoefficient > 0, "CURVE_COEF_MUST_BE_NON_ZERO");
// Check that the propoosed set natural unit is a multiple of current set natural unit, or vice versa.
// Done to make sure that when calculating token units there will are no rounding errors.
uint256 currentNaturalUnit = ISetToken(currentSet).naturalUnit();
uint256 nextSetNaturalUnit = ISetToken(_nextSet).naturalUnit();
require(
Math.max256(currentNaturalUnit, nextSetNaturalUnit) %
Math.min256(currentNaturalUnit, nextSetNaturalUnit) == 0,
"SET_NATURAL_UNITS_NOT_MULTIPLES"
);
// Set auction parameters
nextSet = _nextSet;
auctionLibrary = _auctionLibrary;
curveCoefficient = _curveCoefficient;
auctionStartPrice = _auctionStartPrice;
auctionPriceDivisor = _auctionPriceDivisor;
// Update state parameters
proposalStartTime = block.timestamp;
rebalanceState = State.Proposal;
emit RebalanceProposed(
_nextSet,
_auctionLibrary,
proposalStartTime.add(proposalPeriod)
);
}
/*
* Initiate rebalance for the rebalancing set. Users can now submit bids.
*
*/
function rebalance()
external
{
// Must be in "Proposal" state before going into "Rebalance" state
require(rebalanceState == State.Proposal, "ONLY_CALLABLE_FROM_PROPOSE_STATE");
// Be sure the full proposal period has elapsed
require(block.timestamp >= proposalStartTime.add(proposalPeriod), "PROPOSAL_PERIOD_NOT_ELAPSED");
// Get core address from factory and create core interface
ICore core = ICore(IRebalancingSetFactory(factory).core());
// Create token arrays needed for auction
auctionSetUp();
// Get currentSet natural unit
uint256 currentSetNaturalUnit = ISetToken(currentSet).naturalUnit();
// Get remainingCurrentSets and make it divisible by currentSet natural unit
remainingCurrentSets = IVault(core.vault()).getOwnerBalance(
currentSet,
this
);
remainingCurrentSets = remainingCurrentSets.div(currentSetNaturalUnit).mul(currentSetNaturalUnit);
// Redeem current set held by rebalancing token in vault
core.redeemInVault(currentSet, remainingCurrentSets);
// Update state parameters
auctionStartTime = block.timestamp;
rebalanceState = State.Rebalance;
emit RebalanceStarted(currentSet, nextSet);
}
/*
* Initiate settlement for the rebalancing set. Full functionality now returned to
* set owners.
*
*/
function settleRebalance()
external
{
// Must be in Rebalance state to call settlement
require(rebalanceState == State.Rebalance, "NEED_ACTIVE_REBALANCE_TO_SETTLE");
// Make sure all currentSets have been rebalanced
require(remainingCurrentSets < minimumBid, "REBALANCE_NOT_FINISHED");
// Creating pointer to Core to Issue next set and Deposit into vault and to nextSet token
// to transfer fees
ICore core = ICore(IRebalancingSetFactory(factory).core());
ISetToken nextSetInstance = ISetToken(nextSet);
address protocolAddress = core.protocolAddress();
// Issue nextSet to RebalancingSetToken
uint256 issueAmount;
uint256 totalFees;
uint256 managerFee;
uint256 protocolFee;
(issueAmount, unitShares, totalFees) = calculateNextSetIssueQuantity();
(managerFee, protocolFee) = calculateFeeSplit(totalFees);
core.issue(
nextSet,
issueAmount
);
// Ensure transfer proxy has enough spender allowance to move issued nextSet to vault
ERC20Wrapper.ensureAllowance(
nextSet,
this,
core.transferProxy(),
issueAmount
);
// Deposit newly created nextSets in Vault
core.deposit(
nextSet,
issueAmount.sub(totalFees)
);
nextSetInstance.transfer(
manager,
managerFee
);
if (protocolFee > 0) {
nextSetInstance.transfer(
protocolAddress,
protocolFee
);
}
// Set current set to be rebalancing set
currentSet = nextSet;
// Update state parameters
lastRebalanceTimestamp = block.timestamp;
rebalanceState = State.Default;
}
/*
* Place bid during rebalance auction. Can only be called by Core.
*
* @param _quantity The amount of currentSet to be rebalanced
* @return combinedTokenArray Array of token addresses invovled in rebalancing
* @return inflowUnitArray Array of amount of tokens inserted into system in bid
* @return outflowUnitArray Array of amount of tokens taken out of system in bid
*/
function placeBid(
uint256 _quantity
)
external
returns (address[], uint256[], uint256[])
{
// Make sure sender is Core
require(msg.sender == IRebalancingSetFactory(factory).core(), "ONLY_CORE_CAN_PLACE_BID");
// Confirm in Rebalance State
require(rebalanceState == State.Rebalance, "NEED_ACTIVE_REBALANCE_TO_BID");
// Make sure that bid amount is multiple of minimum bid amount
require(_quantity % minimumBid == 0, "NOT_MINIMUM_BID_MULTIPLE");
// Make sure that bid Amount is less than remainingCurrentSets
require(_quantity <= remainingCurrentSets, "BID_SIZE_TOO_LARGE");
// Calculate token inflow and outflow arrays
uint256[] memory inflowUnitArray = new uint256[](combinedTokenArray.length);
uint256[] memory outflowUnitArray = new uint256[](combinedTokenArray.length);
(inflowUnitArray, outflowUnitArray) = getBidPrice(_quantity);
remainingCurrentSets = remainingCurrentSets.sub(_quantity);
return (combinedTokenArray, inflowUnitArray, outflowUnitArray);
}
/*
* Get token inflows and outflows required for bid. Also the amount of Rebalancing
* Sets that would be generated.
*
* @param _quantity The amount of currentSet to be rebalanced
* @return inflowUnitArray Array of amount of tokens inserted into system in bid
* @return outflowUnitArray Array of amount of tokens taken out of system in bid
*/
function getBidPrice(
uint256 _quantity
)
public
view
returns (uint256[], uint256[])
{
// Confirm in Rebalance State
require(rebalanceState == State.Rebalance, "NEED_ACTIVE_REBALANCE_TO_PRICE");
// Declare unit arrays in memory
uint256[] memory inflowUnitArray = new uint256[](combinedTokenArray.length);
uint256[] memory outflowUnitArray = new uint256[](combinedTokenArray.length);
// Get bid conversion price, currently static placeholder for calling auctionlibrary
uint256 priceNumerator = IAuctionPriceCurve(auctionLibrary).getCurrentPrice(
auctionStartTime,
auctionStartPrice,
curveCoefficient
);
// Normalized quantity amount
uint256 unitsMultiplier = _quantity.div(minimumBid).mul(auctionPriceDivisor);
for (uint256 i = 0; i < combinedTokenArray.length; i++) {
uint256 nextUnit = combinedNextSetUnits[i];
uint256 currentUnit = combinedCurrentUnits[i];
/*
* Below is a mathematically simplified formula for calculating token inflows and
* outflows, the following is it's derivation:
* token_flow = (bidQuantity/price)*(nextUnit - price*currentUnit)
*
* Where,
* 1) price = (priceNumerator/auctionPriceDivisor),
* 2) nextUnit and currentUnit are the amount of component i needed for a
* standardAmount of sets to be rebalanced where one standardAmount =
* max(natural unit nextSet, natural unit currentSet), and
* 3) bidQuantity is a normalized amount in terms of the standardAmount used
* to calculate nextUnit and currentUnit. This is represented by the unitsMultiplier
* variable.
*
* Given these definitions we can derive the below formula as follows:
* token_flow = (unitsMultiplier/(priceNumerator/auctionPriceDivisor))*
* (nextUnit - (priceNumerator/auctionPriceDivisor)*currentUnit)
*
* We can then multiply this equation by (auctionPriceDivisor/auctionPriceDivisor)
* which simplifies the above equation to:
*
* (unitsMultiplier/priceNumerator)* (nextUnit*auctionPriceDivisor - currentUnit*priceNumerator)
*
* This is the equation seen below, but since unsigned integers are used we must check to see if
* nextUnit*auctionPriceDivisor > currentUnit*priceNumerator, otherwise those two terms must be
* flipped in the equation.
*/
if (nextUnit.mul(auctionPriceDivisor) > currentUnit.mul(priceNumerator)) {
inflowUnitArray[i] = unitsMultiplier.mul(
nextUnit.mul(auctionPriceDivisor).sub(currentUnit.mul(priceNumerator))
).div(priceNumerator);
// Set outflow amount to 0 for component i, since tokens need to be injected in rebalance
outflowUnitArray[i] = 0;
} else {
// Calculate outflow amount
outflowUnitArray[i] = unitsMultiplier.mul(
currentUnit.mul(priceNumerator).sub(nextUnit.mul(auctionPriceDivisor))
).div(priceNumerator);
// Set inflow amount to 0 for component i, since tokens need to be returned in rebalance
inflowUnitArray[i] = 0;
}
}
return (inflowUnitArray, outflowUnitArray);
}
/*
* Mint set token for given address.
* Can only be called by Core contract.
*
* @param _issuer The address of the issuing account
* @param _quantity The number of sets to attribute to issuer
*/
function mint(
address _issuer,
uint256 _quantity
)
external
{
// Check that function caller is Core
require(msg.sender == IRebalancingSetFactory(factory).core(), "ONLY_CORE_CAN_MINT_REBAL_SET");
// Check that set is not in Rebalancing State
require(rebalanceState != State.Rebalance, "MINT_PAUSED_DURING_REBALANCE");
uint256 totalFees = _quantity.mul(entranceFee).div(10000);
uint256 issuerTotal = _quantity.sub(totalFees);
uint256 managerFee;
uint256 protocolFee;
(managerFee, protocolFee) = calculateFeeSplit(totalFees);
// Update token balance of the manager
balances[_issuer] = balances[_issuer].add(issuerTotal);
balances[manager] = balances[manager].add(managerFee);
if (protocolFee > 0) {
// Get protocol address and add fees to protocol and issuer
address protocolAddress = ICore(IRebalancingSetFactory(factory).core()).protocolAddress();
balances[protocolAddress] = balances[protocolAddress].add(protocolFee);
// Emit transfer log for protocol fee
emit Transfer(address(0), protocolAddress, protocolFee);
}
// Update the total supply of the set token
totalSupply_ = totalSupply_.add(_quantity);
// Emit a transfer log for issuer and manager fee
emit Transfer(address(0), _issuer, issuerTotal);
emit Transfer(address(0), manager, managerFee);
}
/*
* Burn set token for given address.
* Can only be called by authorized contracts.
*
* @param _from The address of the redeeming account
* @param _quantity The number of sets to burn from redeemer
*/
function burn(
address _from,
uint256 _quantity
)
external
{
// Check that function caller is Core
require(msg.sender == IRebalancingSetFactory(factory).core(), "ONLY_CORE_CAN_BURN_REBAL_SET");
// Check that set is not in Rebalancing State
require(rebalanceState != State.Rebalance, "BURN_PAUSED_DURING_REBALANCE");
// Require user has tokens to burn
require(balances[_from] >= _quantity, "NOT_ENOUGH_TOKENS_TO_BURN");
// Update token balance of user
balances[_from] = balances[_from].sub(_quantity);
// Update total supply of Set Token
totalSupply_ = totalSupply_.sub(_quantity);
// Emit a transfer log with to address being 0 indicating burn
emit Transfer(_from, address(0), _quantity);
}
/*
* Set new manager address
*
* @param _newManager The address of the redeeming account
*/
function setManager(
address _newManager
)
external
{
require(msg.sender == manager, "ONLY_MANAGER_CAN_SET");
emit NewManagerAdded(_newManager, manager);
manager = _newManager;
}
/* ============ Getter Functions ============ */
/*
* Get addresses of setToken underlying the Rebalancing Set
*
* @return componentAddresses Array of currentSet
*/
function getComponents()
external
view
returns(address[])
{
address[] memory components = new address[](1);
components[0] = currentSet;
return components;
}
/*
* Get unitShares of Rebalancing Set
*
* @return units Array of component unit
*/
function getUnits()
external
view
returns(uint256[])
{
uint256[] memory units = new uint256[](1);
units[0] = unitShares;
return units;
}
/*
* Get combinedTokenArray of Rebalancing Set
*
* @return combinedTokenArray
*/
function getCombinedTokenArrayLength()
external
view
returns(uint256)
{
return combinedTokenArray.length;
}
/*
* Get combinedTokenArray of Rebalancing Set
*
* @return combinedTokenArray
*/
function getCombinedTokenArray()
external
view
returns(address[])
{
return combinedTokenArray;
}
/*
* Get combinedCurrentUnits of Rebalancing Set
*
* @return combinedCurrentUnits
*/
function getCombinedCurrentUnits()
external
view
returns(uint256[])
{
return combinedCurrentUnits;
}
/*
* Get combinedNextSetUnits of Rebalancing Set
*
* @return combinedNextSetUnits
*/
function getCombinedNextSetUnits()
external
view
returns(uint256[])
{
return combinedNextSetUnits;
}
/* ============ Internal Functions ============ */
/**
* Create array that represents all components in currentSet and nextSet.
* Calcualate unit difference between both sets relative to the largest natural
* unit of the two sets.
*/
function auctionSetUp()
private
{
// Create interfaces for interacting with sets
ISetToken currentSetInstance = ISetToken(currentSet);
ISetToken nextSetInstance = ISetToken(nextSet);
// Create combined token Array
address[] memory oldComponents = currentSetInstance.getComponents();
address[] memory newComponents = nextSetInstance.getComponents();
combinedTokenArray = oldComponents.union(newComponents);
// Get naturalUnit of both sets
uint256 currentSetNaturalUnit = currentSetInstance.naturalUnit();
uint256 nextSetNaturalUnit = nextSetInstance.naturalUnit();
// Get units arrays for both sets
uint256[] memory currentSetUnits = currentSetInstance.getUnits();
uint256[] memory nextSetUnits = nextSetInstance.getUnits();
// Create memory version of combinedNextSetUnits and combinedCurrentUnits to only make one
// call to storage once arrays have been created
uint256[] memory memoryCombinedCurrentUnits = new uint256[](combinedTokenArray.length);
uint256[] memory memoryCombinedNextSetUnits = new uint256[](combinedTokenArray.length);
minimumBid = Math.max256(
currentSetNaturalUnit.mul(auctionPriceDivisor),
nextSetNaturalUnit.mul(auctionPriceDivisor)
);
for (uint256 i=0; i < combinedTokenArray.length; i++) {
// Check if component in arrays and get index if it is
(uint256 indexCurrent, bool isInCurrent) = oldComponents.indexOf(combinedTokenArray[i]);
(uint256 indexRebalance, bool isInNext) = newComponents.indexOf(combinedTokenArray[i]);
// Compute and push unit amounts of token in currentSet, push 0 if not in set
if (isInCurrent) {
memoryCombinedCurrentUnits[i] = computeUnits(currentSetUnits[indexCurrent], currentSetNaturalUnit);
} else {
memoryCombinedCurrentUnits[i] = uint256(0);
}
// Compute and push unit amounts of token in nextSet, push 0 if not in set
if (isInNext) {
memoryCombinedNextSetUnits[i] = computeUnits(nextSetUnits[indexRebalance], nextSetNaturalUnit);
} else {
memoryCombinedNextSetUnits[i] = uint256(0);
}
}
// Set combinedCurrentUnits and combinedNextSetUnits to memory versions of arrays
combinedCurrentUnits = memoryCombinedCurrentUnits;
combinedNextSetUnits = memoryCombinedNextSetUnits;
}
/**
* Calculate the amount of nextSets to issue by using the component amounts in the
* vault, unitShares following from this calculation.
* @return uint256 Amount of nextSets to issue
* @return uint256 New unitShares for the rebalancingSetToken
*/
function calculateNextSetIssueQuantity()
private
returns (uint256, uint256, uint256)
{
// Collect data necessary to compute issueAmounts
uint256 nextNaturalUnit = ISetToken(nextSet).naturalUnit();
address[] memory nextComponents = ISetToken(nextSet).getComponents();
uint256[] memory nextUnits = ISetToken(nextSet).getUnits();
uint256 maxIssueAmount = CommonMath.maxUInt256();
// Set up vault interface
address vaultAddress = ICore(IRebalancingSetFactory(factory).core()).vault();
IVault vault = IVault(vaultAddress);
for (uint256 i = 0; i < nextComponents.length; i++) {
// Get amount of components in vault owned by rebalancingSetToken
uint256 componentAmount = vault.getOwnerBalance(
nextComponents[i],
this
);
// Calculate amount of Sets that can be issued from those components, if less than amount for other
// components then set that as maxIssueAmount
uint256 componentIssueAmount = componentAmount.div(nextUnits[i]).mul(nextNaturalUnit);
if (componentIssueAmount < maxIssueAmount) {
maxIssueAmount = componentIssueAmount;
}
}
// Calculate the amount of naturalUnits worth of rebalancingSetToken outstanding
uint256 naturalUnitsOutstanding = totalSupply_.div(naturalUnit);
// Issue amount of Sets that is closest multiple of nextNaturalUnit to the maxIssueAmount
// Since the initial division will round down to the nearest whole number when we multiply
// by that same number we will return the closest multiple less than the maxIssueAmount
uint256 issueAmount = maxIssueAmount.div(nextNaturalUnit).mul(nextNaturalUnit);
uint256 totalFees = issueAmount.mul(rebalanceFee).div(10000);
// Divide final issueAmount by naturalUnitsOutstanding to get newUnitShares
uint256 newUnitShares = issueAmount.sub(totalFees).div(naturalUnitsOutstanding);
return (issueAmount, newUnitShares, totalFees);
}
/**
* Function to calculate the transfer value of a component given 1 Set
*
* @param _unit The units of the component token
* @param _naturalUnit The natural unit of the Set token
* @return uint256 Amount of tokens per minimumBid/auctionPriceDivisor
*/
function computeUnits(
uint256 _unit,
uint256 _naturalUnit
)
private
returns (uint256)
{
return minimumBid.mul(_unit).div(_naturalUnit).div(auctionPriceDivisor);
}
/**
* Function to calculate splitting fees between manager and protocol
*
* @param totalFees Total amount of fees to split up
* @return uint256 Amount of tokens to send to manager
* @return uint256 Amount of tokens to send to protocol
*/
function calculateFeeSplit(
uint256 totalFees
)
private
returns (uint256, uint256)
{
uint256 protocolFee = totalFees.mul(ICore(IRebalancingSetFactory(factory).core()).protocolFee())
.div(10000);
uint256 managerFee = totalFees.sub(protocolFee);
return (managerFee, protocolFee);
}
}
|
============ Internal Functions ============ / Create array that represents all components in currentSet and nextSet. Calcualate unit difference between both sets relative to the largest natural unit of the two sets./ Create interfaces for interacting with sets Create combined token Array Get naturalUnit of both sets Get units arrays for both sets Create memory version of combinedNextSetUnits and combinedCurrentUnits to only make one call to storage once arrays have been created Check if component in arrays and get index if it is Compute and push unit amounts of token in currentSet, push 0 if not in set Compute and push unit amounts of token in nextSet, push 0 if not in set
|
function auctionSetUp()
private
{
ISetToken currentSetInstance = ISetToken(currentSet);
ISetToken nextSetInstance = ISetToken(nextSet);
address[] memory oldComponents = currentSetInstance.getComponents();
address[] memory newComponents = nextSetInstance.getComponents();
combinedTokenArray = oldComponents.union(newComponents);
uint256 currentSetNaturalUnit = currentSetInstance.naturalUnit();
uint256 nextSetNaturalUnit = nextSetInstance.naturalUnit();
uint256[] memory currentSetUnits = currentSetInstance.getUnits();
uint256[] memory nextSetUnits = nextSetInstance.getUnits();
uint256[] memory memoryCombinedCurrentUnits = new uint256[](combinedTokenArray.length);
uint256[] memory memoryCombinedNextSetUnits = new uint256[](combinedTokenArray.length);
minimumBid = Math.max256(
currentSetNaturalUnit.mul(auctionPriceDivisor),
nextSetNaturalUnit.mul(auctionPriceDivisor)
);
for (uint256 i=0; i < combinedTokenArray.length; i++) {
(uint256 indexCurrent, bool isInCurrent) = oldComponents.indexOf(combinedTokenArray[i]);
(uint256 indexRebalance, bool isInNext) = newComponents.indexOf(combinedTokenArray[i]);
if (isInCurrent) {
memoryCombinedCurrentUnits[i] = computeUnits(currentSetUnits[indexCurrent], currentSetNaturalUnit);
memoryCombinedCurrentUnits[i] = uint256(0);
}
if (isInNext) {
memoryCombinedNextSetUnits[i] = computeUnits(nextSetUnits[indexRebalance], nextSetNaturalUnit);
memoryCombinedNextSetUnits[i] = uint256(0);
}
}
combinedNextSetUnits = memoryCombinedNextSetUnits;
}
| 13,031,660
|
/**
*Submitted for verification at Etherscan.io on 2021-01-12
*/
// File: @openzeppelin\contracts\token\ERC20\IERC20.sol
// 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);
}
// File: node_modules\@openzeppelin\contracts\math\SafeMath.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, 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: node_modules\@openzeppelin\contracts\utils\Address.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
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\SafeERC20.sol
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\uniswapv2\interfaces\IUniswapV2Pair.sol
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;
}
// File: contracts\uniswapv2\interfaces\IUniswapV2Router01.sol
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 view returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external view 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);
}
// File: contracts\uniswapv2\interfaces\IUniswapV2Factory.sol
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 withdrawFeeTo() external view returns (address);
function swapFee() external view returns (uint);
function withdrawFee() external view returns (uint);
function feeSetter() external view returns (address);
function migrator() 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 setWithdrawFeeTo(address) external;
function setSwapFee(uint) external;
function setFeeSetter(address) external;
function setMigrator(address) external;
}
// File: contracts\uniswapv2\libraries\UniswapV2Library.sol
pragma solidity >=0.5.0;
library UniswapV2Library {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}
function pairFor(address factory, address tokenA, address tokenB) internal view returns (address pair) {
return IUniswapV2Factory(factory).getPair(tokenA, tokenB);
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
address pair = pairFor(factory, tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pair).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut, uint swapFee) internal pure returns (uint amountOut) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(1000 - swapFee);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut, uint swapFee) internal pure returns (uint amountIn) {
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(1000 - swapFee);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path, uint swapFee) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut, swapFee);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path, uint swapFee) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut, swapFee);
}
}
}
// File: contracts\LuaRoll.sol
pragma solidity 0.6.12;
// LuaRoll helps your migrate your existing Uniswap LP tokens to LuaSwap LP ones
contract LuaRoll {
using SafeERC20 for IERC20;
IUniswapV2Router01 public oldRouter;
IUniswapV2Router01 public router;
constructor(IUniswapV2Router01 _oldRouter, IUniswapV2Router01 _router) public {
oldRouter = _oldRouter;
router = _router;
}
function migrateWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public {
IUniswapV2Pair pair = IUniswapV2Pair(pairForOldRouter(tokenA, tokenB));
pair.permit(msg.sender, address(this), liquidity, deadline, v, r, s);
migrate(tokenA, tokenB, liquidity, amountAMin, amountBMin, deadline);
}
// msg.sender should have approved 'liquidity' amount of LP token of 'tokenA' and 'tokenB'
function migrate(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
uint256 deadline
) public {
require(deadline >= block.timestamp, 'LuaSwap: EXPIRED');
// Remove liquidity from the old router with permit
(uint256 amountA, uint256 amountB) = removeLiquidity(
tokenA,
tokenB,
liquidity,
amountAMin,
amountBMin,
deadline
);
// Add liquidity to the new router
(uint256 pooledAmountA, uint256 pooledAmountB) = addLiquidity(tokenA, tokenB, amountA, amountB);
// Send remaining tokens to msg.sender
if (amountA > pooledAmountA) {
IERC20(tokenA).safeTransfer(msg.sender, amountA - pooledAmountA);
}
if (amountB > pooledAmountB) {
IERC20(tokenB).safeTransfer(msg.sender, amountB - pooledAmountB);
}
}
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
uint256 deadline
) internal returns (uint256 amountA, uint256 amountB) {
IUniswapV2Pair pair = IUniswapV2Pair(pairForOldRouter(tokenA, tokenB));
pair.transferFrom(msg.sender, address(pair), liquidity);
(uint256 amount0, uint256 amount1) = pair.burn(address(this));
(address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB);
(amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);
require(amountA >= amountAMin, 'LuaRoll: INSUFFICIENT_A_AMOUNT');
require(amountB >= amountBMin, 'LuaRoll: INSUFFICIENT_B_AMOUNT');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairForOldRouter(address tokenA, address tokenB) internal view returns (address pair) {
(address token0, address token1) = UniswapV2Library.sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
oldRouter.factory(),
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired
) internal returns (uint amountA, uint amountB) {
(amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired);
address pair = UniswapV2Library.pairFor(router.factory(), tokenA, tokenB);
IERC20(tokenA).safeTransfer(pair, amountA);
IERC20(tokenB).safeTransfer(pair, amountB);
IUniswapV2Pair(pair).mint(msg.sender);
}
function _addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired
) internal returns (uint256 amountA, uint256 amountB) {
// create the pair if it doesn't exist yet
IUniswapV2Factory factory = IUniswapV2Factory(router.factory());
if (factory.getPair(tokenA, tokenB) == address(0)) {
factory.createPair(tokenA, tokenB);
}
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(address(factory), tokenA, tokenB);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
} else {
uint256 amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
(amountA, amountB) = (amountADesired, amountBOptimal);
} else {
uint256 amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA);
assert(amountAOptimal <= amountADesired);
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}
}
|
msg.sender should have approved 'liquidity' amount of LP token of 'tokenA' and 'tokenB' Remove liquidity from the old router with permit Add liquidity to the new router Send remaining tokens to msg.sender
|
function migrate(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
uint256 deadline
) public {
require(deadline >= block.timestamp, 'LuaSwap: EXPIRED');
(uint256 amountA, uint256 amountB) = removeLiquidity(
tokenA,
tokenB,
liquidity,
amountAMin,
amountBMin,
deadline
);
(uint256 pooledAmountA, uint256 pooledAmountB) = addLiquidity(tokenA, tokenB, amountA, amountB);
if (amountA > pooledAmountA) {
IERC20(tokenA).safeTransfer(msg.sender, amountA - pooledAmountA);
}
if (amountB > pooledAmountB) {
IERC20(tokenB).safeTransfer(msg.sender, amountB - pooledAmountB);
}
}
| 7,956,888
|
/*
* Welcome to the 𝐄𝐭𝐡𝐞𝐫𝐚𝐟𝐟𝐥𝐞 Smart-Contract!
* The 𝐎𝐍𝐋𝐘 decentralized, charitable blockchain lottery!
*
* ##########################################
* ##########################################
* ### ###
* ### 𝐏𝐥𝐚𝐲 & 𝐖𝐢𝐧 𝐄𝐭𝐡𝐞𝐫 ###
* ### at ###
* ### 𝐄𝐓𝐇𝐄𝐑𝐀𝐅𝐅𝐋𝐄.𝐂𝐎𝐌 ###
* ### ###
* ##########################################
* ##########################################
*
* Etheraffle is designed to give 𝐡𝐮𝐠𝐞 𝐩𝐫𝐢𝐳𝐞𝐬 to
* players, sustainable 𝐄𝐓𝐇 𝐝𝐢𝐯𝐢𝐝𝐞𝐧𝐝𝐬 to 𝐋𝐎𝐓 token
* holders, and 𝐥𝐢𝐟𝐞-𝐜𝐡𝐚𝐧𝐠𝐢𝐧𝐠 𝐟𝐮𝐧𝐝𝐢𝐧𝐠 to charities.
*
* Learn more & get involved at 𝐞𝐭𝐡𝐞𝐫𝐚𝐟𝐟𝐥𝐞.𝐜𝐨𝐦/𝐈𝐂𝐎 to become a
* 𝐋𝐎𝐓 token holder today! Holding 𝐋𝐎𝐓 tokens automatically
* makes you a part of the decentralized, autonomous organisation
* that 𝐎𝐖𝐍𝐒 Etheraffle. Take your place in this decentralized,
* altruistic vision of the future!
*
* If you want to chat to us you have loads of options:
* On 𝐓𝐞𝐥𝐞𝐠𝐫𝐚𝐦 @ 𝐡𝐭𝐭𝐩𝐬://𝐭.𝐦𝐞/𝐞𝐭𝐡𝐞𝐫𝐚𝐟𝐟𝐥𝐞
* Or on 𝐓𝐰𝐢𝐭𝐭𝐞𝐫 @ 𝐡𝐭𝐭𝐩𝐬://𝐭𝐰𝐢𝐭𝐭𝐞𝐫.𝐜𝐨𝐦/𝐞𝐭𝐡𝐞𝐫𝐚𝐟𝐟𝐥𝐞
* Or on 𝐑𝐞𝐝𝐝𝐢𝐭 @ 𝐡𝐭𝐭𝐩𝐬://𝐞𝐭𝐡𝐞𝐫𝐚𝐟𝐟𝐥𝐞.𝐫𝐞𝐝𝐝𝐢𝐭.𝐜𝐨𝐦
*
*/
pragma solidity^0.4.21;
/*
* @title String & slice utility library for Solidity contracts.
* @author Nick Johnson <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bedfccdfddd6d0d7dafed0d1cadad1ca90d0dbca">[email protected]</a>>
*
* @dev Functionality in this library is largely implemented using an
* abstraction called a 'slice'. A slice represents a part of a string -
* anything from the entire string to a single character, or even no
* characters at all (a 0-length slice). Since a slice only has to specify
* an offset and a length, copying and manipulating slices is a lot less
* expensive than copying and manipulating the strings they reference.
*
* To further reduce gas costs, most functions on slice that need to return
* a slice modify the original one instead of allocating a new one; for
* instance, `s.split(".")` will return the text up to the first '.',
* modifying s to only contain the remainder of the string after the '.'.
* In situations where you do not want to modify the original slice, you
* can make a copy first with `.copy()`, for example:
* `s.copy().split(".")`. Try and avoid using this idiom in loops; since
* Solidity has no memory management, it will result in allocating many
* short-lived slices that are later discarded.
*
* Functions that return two slices come in two versions: a non-allocating
* version that takes the second slice as an argument, modifying it in
* place, and an allocating version that allocates and returns the second
* slice; see `nextRune` for example.
*
* Functions that have to copy string data will return strings rather than
* slices; these can be cast back to slices for further processing if
* required.
*
* For convenience, some functions are provided with non-modifying
* variants that create a new slice and return both; for instance,
* `s.splitNew('.')` leaves s unmodified, and returns two values
* corresponding to the left and right parts of the string.
*/
//pragma solidity ^0.4.14;
library strings {
struct slice {
uint _len;
uint _ptr;
}
function memcpy(uint dest, uint src, uint len) private {
// Copy word-length chunks while possible
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/*
* @dev Returns a slice containing the entire string.
* @param self The string to make a slice from.
* @return A newly allocated slice containing the entire string.
*/
function toSlice(string self) internal returns (slice) {
uint ptr;
assembly {
ptr := add(self, 0x20)
}
return slice(bytes(self).length, ptr);
}
/*
* @dev Returns the length of a null-terminated bytes32 string.
* @param self The value to find the length of.
* @return The length of the string, from 0 to 32.
*/
function len(bytes32 self) internal returns (uint) {
uint ret;
if (self == 0)
return 0;
if (self & 0xffffffffffffffffffffffffffffffff == 0) {
ret += 16;
self = bytes32(uint(self) / 0x100000000000000000000000000000000);
}
if (self & 0xffffffffffffffff == 0) {
ret += 8;
self = bytes32(uint(self) / 0x10000000000000000);
}
if (self & 0xffffffff == 0) {
ret += 4;
self = bytes32(uint(self) / 0x100000000);
}
if (self & 0xffff == 0) {
ret += 2;
self = bytes32(uint(self) / 0x10000);
}
if (self & 0xff == 0) {
ret += 1;
}
return 32 - ret;
}
/*
* @dev Returns a slice containing the entire bytes32, interpreted as a
* null-termintaed utf-8 string.
* @param self The bytes32 value to convert to a slice.
* @return A new slice containing the value of the input argument up to the
* first null.
*/
function toSliceB32(bytes32 self) internal returns (slice ret) {
// Allocate space for `self` in memory, copy it there, and point ret at it
assembly {
let ptr := mload(0x40)
mstore(0x40, add(ptr, 0x20))
mstore(ptr, self)
mstore(add(ret, 0x20), ptr)
}
ret._len = len(self);
}
/*
* @dev Returns a new slice containing the same data as the current slice.
* @param self The slice to copy.
* @return A new slice containing the same data as `self`.
*/
function copy(slice self) internal returns (slice) {
return slice(self._len, self._ptr);
}
/*
* @dev Copies a slice to a new string.
* @param self The slice to copy.
* @return A newly allocated string containing the slice's text.
*/
function toString(slice self) internal returns (string) {
var ret = new string(self._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
return ret;
}
/*
* @dev Returns the length in runes of the slice. Note that this operation
* takes time proportional to the length of the slice; avoid using it
* in loops, and call `slice.empty()` if you only need to know whether
* the slice is empty or not.
* @param self The slice to operate on.
* @return The length of the slice in runes.
*/
function len(slice self) internal returns (uint l) {
// Starting at ptr-31 means the LSB will be the byte we care about
var ptr = self._ptr - 31;
var end = ptr + self._len;
for (l = 0; ptr < end; l++) {
uint8 b;
assembly { b := and(mload(ptr), 0xFF) }
if (b < 0x80) {
ptr += 1;
} else if(b < 0xE0) {
ptr += 2;
} else if(b < 0xF0) {
ptr += 3;
} else if(b < 0xF8) {
ptr += 4;
} else if(b < 0xFC) {
ptr += 5;
} else {
ptr += 6;
}
}
}
/*
* @dev Returns true if the slice is empty (has a length of 0).
* @param self The slice to operate on.
* @return True if the slice is empty, False otherwise.
*/
function empty(slice self) internal returns (bool) {
return self._len == 0;
}
/*
* @dev Returns a positive number if `other` comes lexicographically after
* `self`, a negative number if it comes before, or zero if the
* contents of the two slices are equal. Comparison is done per-rune,
* on unicode codepoints.
* @param self The first slice to compare.
* @param other The second slice to compare.
* @return The result of the comparison.
*/
function compare(slice self, slice other) internal returns (int) {
uint shortest = self._len;
if (other._len < self._len)
shortest = other._len;
var selfptr = self._ptr;
var otherptr = other._ptr;
for (uint idx = 0; idx < shortest; idx += 32) {
uint a;
uint b;
assembly {
a := mload(selfptr)
b := mload(otherptr)
}
if (a != b) {
// Mask out irrelevant bytes and check again
uint mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);
var diff = (a & mask) - (b & mask);
if (diff != 0)
return int(diff);
}
selfptr += 32;
otherptr += 32;
}
return int(self._len) - int(other._len);
}
/*
* @dev Returns true if the two slices contain the same text.
* @param self The first slice to compare.
* @param self The second slice to compare.
* @return True if the slices are equal, false otherwise.
*/
function equals(slice self, slice other) internal returns (bool) {
return compare(self, other) == 0;
}
/*
* @dev Extracts the first rune in the slice into `rune`, advancing the
* slice to point to the next rune and returning `self`.
* @param self The slice to operate on.
* @param rune The slice that will contain the first rune.
* @return `rune`.
*/
function nextRune(slice self, slice rune) internal returns (slice) {
rune._ptr = self._ptr;
if (self._len == 0) {
rune._len = 0;
return rune;
}
uint len;
uint b;
// Load the first byte of the rune into the LSBs of b
assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) }
if (b < 0x80) {
len = 1;
} else if(b < 0xE0) {
len = 2;
} else if(b < 0xF0) {
len = 3;
} else {
len = 4;
}
// Check for truncated codepoints
if (len > self._len) {
rune._len = self._len;
self._ptr += self._len;
self._len = 0;
return rune;
}
self._ptr += len;
self._len -= len;
rune._len = len;
return rune;
}
/*
* @dev Returns the first rune in the slice, advancing the slice to point
* to the next rune.
* @param self The slice to operate on.
* @return A slice containing only the first rune from `self`.
*/
function nextRune(slice self) internal returns (slice ret) {
nextRune(self, ret);
}
/*
* @dev Returns the number of the first codepoint in the slice.
* @param self The slice to operate on.
* @return The number of the first codepoint in the slice.
*/
function ord(slice self) internal returns (uint ret) {
if (self._len == 0) {
return 0;
}
uint word;
uint length;
uint divisor = 2 ** 248;
// Load the rune into the MSBs of b
assembly { word:= mload(mload(add(self, 32))) }
var b = word / divisor;
if (b < 0x80) {
ret = b;
length = 1;
} else if(b < 0xE0) {
ret = b & 0x1F;
length = 2;
} else if(b < 0xF0) {
ret = b & 0x0F;
length = 3;
} else {
ret = b & 0x07;
length = 4;
}
// Check for truncated codepoints
if (length > self._len) {
return 0;
}
for (uint i = 1; i < length; i++) {
divisor = divisor / 256;
b = (word / divisor) & 0xFF;
if (b & 0xC0 != 0x80) {
// Invalid UTF-8 sequence
return 0;
}
ret = (ret * 64) | (b & 0x3F);
}
return ret;
}
/*
* @dev Returns the keccak-256 hash of the slice.
* @param self The slice to hash.
* @return The hash of the slice.
*/
function keccak(slice self) internal returns (bytes32 ret) {
assembly {
ret := keccak256(mload(add(self, 32)), mload(self))
}
}
/*
* @dev Returns true if `self` starts with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function startsWith(slice self, slice needle) internal returns (bool) {
if (self._len < needle._len) {
return false;
}
if (self._ptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev If `self` starts with `needle`, `needle` is removed from the
* beginning of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function beyond(slice self, slice needle) internal returns (slice) {
if (self._len < needle._len) {
return self;
}
bool equal = true;
if (self._ptr != needle._ptr) {
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(sha3(selfptr, length), sha3(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
self._ptr += needle._len;
}
return self;
}
/*
* @dev Returns true if the slice ends with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function endsWith(slice self, slice needle) internal returns (bool) {
if (self._len < needle._len) {
return false;
}
var selfptr = self._ptr + self._len - needle._len;
if (selfptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev If `self` ends with `needle`, `needle` is removed from the
* end of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function until(slice self, slice needle) internal returns (slice) {
if (self._len < needle._len) {
return self;
}
var selfptr = self._ptr + self._len - needle._len;
bool equal = true;
if (selfptr != needle._ptr) {
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
}
return self;
}
// Returns the memory address of the first byte of the first occurrence of
// `needle` in `self`, or the first byte after `self` if not found.
function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private returns (uint) {
uint ptr;
uint idx;
if (needlelen <= selflen) {
if (needlelen <= 32) {
// Optimized assembly for 68 gas per byte on short strings
assembly {
let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1))
let needledata := and(mload(needleptr), mask)
let end := add(selfptr, sub(selflen, needlelen))
ptr := selfptr
loop:
jumpi(exit, eq(and(mload(ptr), mask), needledata))
ptr := add(ptr, 1)
jumpi(loop, lt(sub(ptr, 1), end))
ptr := add(selfptr, selflen)
exit:
}
return ptr;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := sha3(needleptr, needlelen) }
ptr = selfptr;
for (idx = 0; idx <= selflen - needlelen; idx++) {
bytes32 testHash;
assembly { testHash := sha3(ptr, needlelen) }
if (hash == testHash)
return ptr;
ptr += 1;
}
}
}
return selfptr + selflen;
}
// Returns the memory address of the first byte after the last occurrence of
// `needle` in `self`, or the address of `self` if not found.
function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private returns (uint) {
uint ptr;
if (needlelen <= selflen) {
if (needlelen <= 32) {
// Optimized assembly for 69 gas per byte on short strings
assembly {
let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1))
let needledata := and(mload(needleptr), mask)
ptr := add(selfptr, sub(selflen, needlelen))
loop:
jumpi(ret, eq(and(mload(ptr), mask), needledata))
ptr := sub(ptr, 1)
jumpi(loop, gt(add(ptr, 1), selfptr))
ptr := selfptr
jump(exit)
ret:
ptr := add(ptr, needlelen)
exit:
}
return ptr;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := sha3(needleptr, needlelen) }
ptr = selfptr + (selflen - needlelen);
while (ptr >= selfptr) {
bytes32 testHash;
assembly { testHash := sha3(ptr, needlelen) }
if (hash == testHash)
return ptr + needlelen;
ptr -= 1;
}
}
}
return selfptr;
}
/*
* @dev Modifies `self` to contain everything from the first occurrence of
* `needle` to the end of the slice. `self` is set to the empty slice
* if `needle` is not found.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function find(slice self, slice needle) internal returns (slice) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);
self._len -= ptr - self._ptr;
self._ptr = ptr;
return self;
}
/*
* @dev Modifies `self` to contain the part of the string from the start of
* `self` to the end of the first occurrence of `needle`. If `needle`
* is not found, `self` is set to the empty slice.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function rfind(slice self, slice needle) internal returns (slice) {
uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);
self._len = ptr - self._ptr;
return self;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and `token` to everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function split(slice self, slice needle, slice token) internal returns (slice) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = self._ptr;
token._len = ptr - self._ptr;
if (ptr == self._ptr + self._len) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
self._ptr = ptr + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and returning everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` up to the first occurrence of `delim`.
*/
function split(slice self, slice needle) internal returns (slice token) {
split(self, needle, token);
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and `token` to everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function rsplit(slice self, slice needle, slice token) internal returns (slice) {
uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = ptr;
token._len = self._len - (ptr - self._ptr);
if (ptr == self._ptr) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and returning everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` after the last occurrence of `delim`.
*/
function rsplit(slice self, slice needle) internal returns (slice token) {
rsplit(self, needle, token);
}
/*
* @dev Counts the number of nonoverlapping occurrences of `needle` in `self`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return The number of occurrences of `needle` found in `self`.
*/
function count(slice self, slice needle) internal returns (uint cnt) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len;
while (ptr <= self._ptr + self._len) {
cnt++;
ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len;
}
}
/*
* @dev Returns True if `self` contains `needle`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return True if `needle` is found in `self`, false otherwise.
*/
function contains(slice self, slice needle) internal returns (bool) {
return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr;
}
/*
* @dev Returns a newly allocated string containing the concatenation of
* `self` and `other`.
* @param self The first slice to concatenate.
* @param other The second slice to concatenate.
* @return The concatenation of the two strings.
*/
function concat(slice self, slice other) internal returns (string) {
var ret = new string(self._len + other._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
memcpy(retptr + self._len, other._ptr, other._len);
return ret;
}
/*
* @dev Joins an array of slices, using `self` as a delimiter, returning a
* newly allocated string.
* @param self The delimiter to use.
* @param parts A list of slices to join.
* @return A newly allocated string containing all the slices in `parts`,
* joined with `self`.
*/
function join(slice self, slice[] parts) internal returns (string) {
if (parts.length == 0)
return "";
uint length = self._len * (parts.length - 1);
for(uint i = 0; i < parts.length; i++)
length += parts[i]._len;
var ret = new string(length);
uint retptr;
assembly { retptr := add(ret, 32) }
for(i = 0; i < parts.length; i++) {
memcpy(retptr, parts[i]._ptr, parts[i]._len);
retptr += parts[i]._len;
if (i < parts.length - 1) {
memcpy(retptr, self._ptr, self._len);
retptr += self._len;
}
}
return ret;
}
}
// <ORACLIZE_API>
/*
Copyright (c) 2015-2016 Oraclize SRL
Copyright (c) 2016 Oraclize LTD
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
//pragma solidity ^0.4.0;//please import oraclizeAPI_pre0.4.sol when solidity < 0.4.0
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);
function randomDS_getSessionPubKeyHash() returns(bytes32);
}
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 proofType_Android = 0x20;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Native = 0xF0;
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);
if(address(oraclize) != OAR.getAddress())
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);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
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_useCoupon(string code) oraclizeAPI internal {
oraclize.useCoupon(code);
}
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_query(string datasource, bytes[] 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 = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] 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 = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] 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 = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] 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 = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](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, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](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, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](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, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](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, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](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, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](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, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](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, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](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, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](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, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](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, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](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 oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
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 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
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;
}
function ba2cbor(bytes[] 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;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
if ((_nbytes == 0)||(_nbytes > 32)) throw;
// Convert from seconds to ledger timer ticks
_delay *= 10;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes memory delay = new bytes(32);
assembly {
mstore(add(delay, 0x20), _delay)
}
bytes memory delay_bytes8 = new bytes(8);
copyBytes(delay, 24, 8, delay_bytes8, 0);
bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay];
bytes32 queryId = oraclize_query("random", args, _customGasLimit);
bytes memory delay_bytes8_left = new bytes(8);
assembly {
let x := mload(add(delay_bytes8, 0x20))
mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000))
}
oraclize_randomDS_setCommitment(queryId, sha3(delay_bytes8_left, args[1], sha256(args[0]), args[2]));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
oraclize_randomDS_args[queryId] = commitment;
}
mapping(bytes32=>bytes32) oraclize_randomDS_args;
mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;
function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4+(uint(dersig[3]) - 0x20);
sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs);
if (address(sha3(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(sha3(pubkey)) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
bool sigok;
// Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH)
bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2);
copyBytes(proof, sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(proof, 3+1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1+65+32);
tosign2[0] = 1; //role
copyBytes(proof, sig2offset-65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1+65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (sigok == false) return false;
// Step 7: verify the APPKEY1 provenance (must be signed by Ledger)
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1+65);
tosign3[0] = 0xFE;
copyBytes(proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(proof[3+65+1])+2);
copyBytes(proof, 3+65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) throw;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) throw;
_;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) return 2;
return 0;
}
function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal returns (bool){
bool match_ = true;
if (prefix.length != n_random_bytes) throw;
for (uint256 i=0; i< n_random_bytes; i++) {
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
// Step 2: the unique keyhash has to match with the sha256 of (context name + queryId)
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
if (!(sha3(keyhash) == sha3(sha256(context_name, queryId)))) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
// Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1)
if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;
// Step 4: commitment match verification, sha3(delay, nbytes, unonce, sessionKeyHash) == commitment in storage.
// This is to verify that the computed args match with the ones specified in the query.
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == sha3(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match
delete oraclize_randomDS_args[queryId];
} else return false;
// Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey)
bytes memory tosign1 = new bytes(32+8+1+32);
copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false;
// verify if sessionPubkeyHash was verified already, if not.. let's do it!
if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal returns (bytes) {
uint minLength = length + toOffset;
if (to.length < minLength) {
// Buffer too small
throw; // Should be a better way?
}
// NOTE: the offset 32 is added to skip the `size` field of both bytes variables
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
// Duplicate Solidity's ecrecover, but catching the CALL return value
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
// We do our own memory management here. Solidity uses memory offset
// 0x40 to store the current end of memory. We write past it (as
// writes are memory extensions), but don't update the offset so
// Solidity will reuse it. The memory used here is only needed for
// this context.
// FIXME: inline assembly can't access return values
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
// NOTE: we can reuse the request memory because we deal with
// the return code
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
// The signature format is a compact form of:
// {bytes32 r}{bytes32 s}{uint8 v}
// Compact means, uint8 is not padded to 32 bytes.
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
// Here we are loading the last 32 bytes. We exploit the fact that
// 'mload' will pad with zeroes if we overread.
// There is no 'mload8' to do this, but that would be nicer.
v := byte(0, mload(add(sig, 96)))
// Alternative solution:
// 'byte' is not working due to the Solidity parser, so lets
// use the second best option, 'and'
// v := and(mload(add(sig, 65)), 255)
}
// albeit non-transactional signatures are not specified by the YP, one would expect it
// to match the YP range of [27, 28]
//
// geth uses [0, 1] and some clients have followed. This might change, see:
// https://github.com/ethereum/go-ethereum/issues/2053
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
}
// </ORACLIZE_API>
contract ReceiverInterface {
function receiveEther() external payable {}
}
contract EtheraffleUpgrade {
function addToPrizePool() payable external {}
}
contract FreeLOTInterface {
function mint(address _to, uint _amt) external {}
function destroy(address _from, uint _amt) external {}
function balanceOf(address who) constant public returns (uint) {}
}
contract Etheraffle is usingOraclize {
using strings for *;
uint public week;
bool public paused;
uint public upgraded;
uint public prizePool;
address public ethRelief;
address public etheraffle;
address public upgradeAddr;
address public disburseAddr;
uint public take = 150; // ppt
uint public gasAmt = 500000;
uint public resultsDelay = 3600;
uint public matchesDelay = 3600;
uint public rafEnd = 500400; // 7:00pm Saturdays
uint public wdrawBfr = 6048000;
uint public gasPrc = 20000000000; // 20 gwei
uint public tktPrice = 2000000000000000;
uint public oracCost = 1500000000000000; // $1 @ $700
uint[] public pctOfPool = [520, 114, 47, 319]; // ppt...
uint[] public odds = [56, 1032, 54200, 13983816]; // Rounded down to nearest whole
uint constant WEEKDUR = 604800;
uint constant BIRTHDAY = 1500249600;//Etheraffle's birthday <3
FreeLOTInterface freeLOT;
string randomStr1 = "[URL] ['json(https://api.random.org/json-rpc/1/invoke).result.random[\"data\", \"serialNumber\"]','\\n{\"jsonrpc\": \"2.0\",\"method\":\"generateSignedIntegers\",\"id\":\"";
string randomStr2 = "\",\"params\":{\"n\":\"6\",\"min\":1,\"max\":49,\"replacement\":false,\"base\":10,\"apiKey\":${[decrypt] BIaCXRwykpLeDE9h1dQaAUi0LPTD4Jz0kwh6SVTftO+zromdgBhmdQhFwPsaLEGDHHn8bhQA8ksyjOZJpjDzKcVWlkBx5C07udHFtMnvG9g9VITYGxoMOhpFCTnoIKTBlIbNe5D1rIgl9OYUVX4ibTT8fCEE8TkWqQ==}}']";
string apiStr1 = "[URL] ['json(https://etheraffle.com/api/a).m','{\"r\":\"";
string apiStr2 = "\",\"k\":${[decrypt] BDzj/WPcHzGWYRL2cXvMNvInBxhutESn6Xj8pVzUUH+oEeWBoyycp23B7FSjqKJww6uH5AxvD4srlX0D/Rhl678YcKSNX2oMJJ47ciZrCnj6+28GHCLBV+XiA/1GDis9p5Q9NIKI}}']";
mapping (uint => rafStruct) public raffle;
struct rafStruct {
mapping (address => uint[][]) entries;
uint unclaimed;
uint[] winNums;
uint[] winAmts;
uint timeStamp;
bool wdrawOpen;
uint numEntries;
uint freeEntries;
}
mapping (bytes32 => qIDStruct) public qID;
struct qIDStruct {
uint weekNo;
bool isRandom;
bool isManual;
}
/**
* @dev Modifier to prepend to functions adding the additional
* conditional requiring caller of the method to be the
* etheraffle address.
*/
modifier onlyEtheraffle() {
require(msg.sender == etheraffle);
_;
}
/**
* @dev Modifier to prepend to functions adding the additional
* conditional requiring the paused bool to be false.
*/
modifier onlyIfNotPaused() {
require(!paused);
_;
}
event LogFunctionsPaused(uint identifier, uint atTime);
event LogQuerySent(bytes32 queryID, uint dueAt, uint sendTime);
event LogReclaim(uint indexed fromRaffle, uint amount, uint atTime);
event LogUpgrade(address newContract, uint ethTransferred, uint atTime);
event LogPrizePoolAddition(address fromWhom, uint howMuch, uint atTime);
event LogFreeLOTWin(uint indexed forRaffle, address toWhom, uint entryNumber, uint amount, uint atTime);
event LogOraclizeCallback(address functionCaller, bytes32 queryID, string result, uint indexed forRaffle, uint atTime);
event LogFundsDisbursed(uint indexed forRaffle, uint oraclizeTotal, uint amount, address indexed toAddress, uint atTime);
event LogWithdraw(uint indexed forRaffle, address indexed toWhom, uint forEntryNumber, uint matches, uint amountWon, uint atTime);
event LogWinningNumbers(uint indexed forRaffle, uint numberOfEntries, uint[] wNumbers, uint currentPrizePool, uint randomSerialNo, uint atTime);
event LogTicketBought(uint indexed forRaffle, uint indexed entryNumber, address indexed theEntrant, uint[] chosenNumbers, uint personalEntryNumber, uint tktCost, uint atTime, uint affiliateID);
event LogPrizePoolsUpdated(uint newMainPrizePool, uint indexed forRaffle, uint unclaimedPrizePool, uint threeMatchWinAmt, uint fourMatchWinAmt, uint fiveMatchWinAmt, uint sixMatchwinAmt, uint atTime);
/**
* @dev Constructor - sets the Etheraffle contract address &
* the disbursal contract address for investors, calls
* the newRaffle() function with sets the current
* raffle ID global var plus sets up the first raffle's
* struct with correct time stamp. Sets the withdraw
* before time to a ten week period, and prepares the
* initial oraclize call which will begin the recursive
* function.
*
* @param _freeLOT The address of the Etheraffle FreeLOT special token.
* @param _dsbrs The address of the Etheraffle disbursal contract.
* @param _msig The address of the Etheraffle managerial multisig wallet.
* @param _ethRelief The address of the EthRelief charity contract.
*/
function Etheraffle(address _freeLOT, address _dsbrs, address _msig, address _ethRelief) payable {
week = getWeek();
etheraffle = _msig;
disburseAddr = _dsbrs;
ethRelief = _ethRelief;
freeLOT = FreeLOTInterface(_freeLOT);
uint delay = (week * WEEKDUR) + BIRTHDAY + rafEnd + resultsDelay;
raffle[week].timeStamp = (week * WEEKDUR) + BIRTHDAY;
bytes32 query = oraclize_query(delay, "nested", strConcat(randomStr1, uint2str(getWeek()), randomStr2), gasAmt);
qID[query].weekNo = week;
qID[query].isRandom = true;
emit LogQuerySent(query, delay, now);
}
/**
* @dev Function using Etheraffle's birthday to calculate the
* week number since then.
*/
function getWeek() public constant returns (uint) {
uint curWeek = (now - BIRTHDAY) / WEEKDUR;
if (now - ((curWeek * WEEKDUR) + BIRTHDAY) > rafEnd) {
curWeek++;
}
return curWeek;
}
/**
* @dev Function which gets current week number and if different
* from the global var week number, it updates that and sets
* up the new raffle struct. Should only be called once a
* week after the raffle is closed. Should it get called
* sooner, the contract is paused for inspection.
*/
function newRaffle() internal {
uint newWeek = getWeek();
if (newWeek == week) {
pauseContract(4);
return;
} else {//∴ new raffle...
week = newWeek;
raffle[newWeek].timeStamp = BIRTHDAY + (newWeek * WEEKDUR);
}
}
/**
* @dev To pause the contract's functions should the need arise. Internal.
* Logs an event of the pausing.
*
* @param _id A uint to identify the caller of this function.
*/
function pauseContract(uint _id) internal {
paused = true;
emit LogFunctionsPaused(_id, now);
}
/**
* @dev Function to enter the raffle. Requires the caller to send ether
* of amount greater than or equal to the ticket price.
*
* @param _cNums Ordered array of entrant's six selected numbers.
* @param _affID Affiliate ID of the source of this entry.
*/
function enterRaffle(uint[] _cNums, uint _affID) payable external onlyIfNotPaused {
require(msg.value >= tktPrice);
buyTicket(_cNums, msg.sender, msg.value, _affID);
}
/**
* @dev Function to enter the raffle on behalf of another address. Requires the
* caller to send ether of amount greater than or equal to the ticket price.
* In the event of a win, only the onBehalfOf address can claim it.
*
* @param _cNums Ordered array of entrant's six selected numbers.
* @param _affID Affiliate ID of the source of this entry.
* @param _onBehalfOf The address to be entered on behalf of.
*/
function enterOnBehalfOf(uint[] _cNums, uint _affID, address _onBehalfOf) payable external onlyIfNotPaused {
require(msg.value >= tktPrice);
buyTicket(_cNums, _onBehalfOf, msg.value, _affID);
}
/**
* @dev Function to enter the raffle for free. Requires the caller's
* balance of the Etheraffle freeLOT token to be greater than
* zero. Function destroys one freeLOT token, increments the
* freeEntries variable in the raffle struct then purchases the
* ticket.
*
* @param _cNums Ordered array of entrant's six selected numbers.
* @param _affID Affiliate ID of the source of this entry.
*/
function enterFreeRaffle(uint[] _cNums, uint _affID) payable external onlyIfNotPaused {
freeLOT.destroy(msg.sender, 1);
raffle[week].freeEntries++;
buyTicket(_cNums, msg.sender, msg.value, _affID);
}
/**
* @dev Function to buy tickets. Internal. Requires the entry number
* array to be of length 6, requires the timestamp of the current
* raffle struct to have been set, and for this time this function
* is call to be before the end of the raffle. Then requires that
* the chosen numbers are ordered lowest to highest & bound between
* 1 and 49. Function increments the total number of entries in the
* current raffle's struct, increments the prize pool accordingly
* and pushes the chosen number array into the entries map and then
* logs the ticket purchase.
*
* @param _cNums Array of users selected numbers.
* @param _entrant Entrant's ethereum address.
* @param _value The ticket purchase price.
* @param _affID The affiliate ID of the source of this entry.
*/
function buyTicket
(
uint[] _cNums,
address _entrant,
uint _value,
uint _affID
)
internal
{
require
(
_cNums.length == 6 &&
raffle[week].timeStamp > 0 &&
now < raffle[week].timeStamp + rafEnd &&
0 < _cNums[0] &&
_cNums[0] < _cNums[1] &&
_cNums[1] < _cNums[2] &&
_cNums[2] < _cNums[3] &&
_cNums[3] < _cNums[4] &&
_cNums[4] < _cNums[5] &&
_cNums[5] <= 49
);
raffle[week].numEntries++;
prizePool += _value;
raffle[week].entries[_entrant].push(_cNums);
emit LogTicketBought(week, raffle[week].numEntries, _entrant, _cNums, raffle[week].entries[_entrant].length, _value, now, _affID);
}
/**
* @dev Withdraw Winnings function. User calls this function in order to withdraw
* whatever winnings they are owed. Function can be paused via the modifier
* function "onlyIfNotPaused"
*
* @param _week Week number of the raffle the winning entry is from
* @param _entryNum The entrants entry number into this raffle
*/
function withdrawWinnings(uint _week, uint _entryNum) onlyIfNotPaused external {
require
(
raffle[_week].timeStamp > 0 &&
now - raffle[_week].timeStamp > WEEKDUR - (WEEKDUR / 7) &&
now - raffle[_week].timeStamp < wdrawBfr &&
raffle[_week].wdrawOpen == true &&
raffle[_week].entries[msg.sender][_entryNum - 1].length == 6
);
uint matches = getMatches(_week, msg.sender, _entryNum);
if (matches == 2) return winFreeGo(_week, _entryNum);
require
(
matches >= 3 &&
raffle[_week].winAmts[matches - 3] > 0 &&
raffle[_week].winAmts[matches - 3] <= this.balance
);
raffle[_week].entries[msg.sender][_entryNum - 1].push(1);
if (raffle[_week].winAmts[matches - 3] <= raffle[_week].unclaimed) {
raffle[_week].unclaimed -= raffle[_week].winAmts[matches - 3];
} else {
raffle[_week].unclaimed = 0;
pauseContract(5);
}
msg.sender.transfer(raffle[_week].winAmts[matches - 3]);
emit LogWithdraw(_week, msg.sender, _entryNum, matches, raffle[_week].winAmts[matches - 3], now);
}
/*
* @dev Mints a FreeLOT coupon to a two match winner allowing them
* a free entry to Etheraffle. Function pausable by pause toggle.
*/
function winFreeGo(uint _week, uint _entryNum) onlyIfNotPaused internal {
raffle[_week].entries[msg.sender][_entryNum - 1].push(1);
freeLOT.mint(msg.sender, 1);
emit LogFreeLOTWin(_week, msg.sender, _entryNum, 1, now);
}
/**
* @dev Called by the weekly oraclize callback. Checks raffle 10
* weeks older than current raffle for any unclaimed prize
* pool. If any found, returns it to the main prizePool and
* zeros the amount.
*/
function reclaimUnclaimed() internal {
uint old = getWeek() - 11;
prizePool += raffle[old].unclaimed;
emit LogReclaim(old, raffle[old].unclaimed, now);
}
/**
* @dev Function totals up oraclize cost for the raffle, subtracts
* it from the prizepool (if less than, if greater than if
* pauses the contract and fires an event). Calculates profit
* based on raffle's tickets sales and the take percentage,
* then forwards that amount of ether to the disbursal contract.
*
* @param _week The week number of the raffle in question.
*/
function disburseFunds(uint _week) internal {
uint oracTot = 2 * ((gasAmt * gasPrc) + oracCost);//2 queries per draw...
if (oracTot > prizePool) return pauseContract(1);
prizePool -= oracTot;
uint profit;
if (raffle[_week].numEntries > 0) {
profit = ((raffle[_week].numEntries - raffle[_week].freeEntries) * tktPrice * take) / 1000;
prizePool -= profit;
uint half = profit / 2;
ReceiverInterface(disburseAddr).receiveEther.value(half)();
ReceiverInterface(ethRelief).receiveEther.value(profit - half)();
emit LogFundsDisbursed(_week, oracTot, profit - half, ethRelief, now);
emit LogFundsDisbursed(_week, oracTot, half, disburseAddr, now);
return;
}
emit LogFundsDisbursed(_week, oracTot, profit, 0, now);
}
/**
* @dev The Oralize call back function. The oracalize api calls are
* recursive. One to random.org for the draw and the other to
* the Etheraffle api for the numbers of matches each entry made
* against the winning numbers. Each calls the other recursively.
* The former when calledback closes and reclaims any unclaimed
* prizepool from the raffle ten weeks previous to now. Then it
* disburses profit to the disbursal contract, then it sets the
* winning numbers received from random.org into the raffle
* struct. Finally it prepares the next oraclize call. Which
* latter callback first sets up the new raffle struct, then
* sets the payouts based on the number of winners in each tier
* returned from the api call, then prepares the next oraclize
* query for a week later to draw the next raffle's winning
* numbers.
*
* @param _myID bytes32 - Unique id oraclize provides with their
* callbacks.
* @param _result string - The result of the api call.
*/
function __callback(bytes32 _myID, string _result) onlyIfNotPaused {
require(msg.sender == oraclize_cbAddress() || msg.sender == etheraffle);
emit LogOraclizeCallback(msg.sender, _myID, _result, qID[_myID].weekNo, now);
if (qID[_myID].isRandom == true) {
reclaimUnclaimed();
disburseFunds(qID[_myID].weekNo);
setWinningNumbers(qID[_myID].weekNo, _result);
if (qID[_myID].isManual == true) return;
bytes32 query = oraclize_query(matchesDelay, "nested", strConcat(apiStr1, uint2str(qID[_myID].weekNo), apiStr2), gasAmt);
qID[query].weekNo = qID[_myID].weekNo;
emit LogQuerySent(query, matchesDelay + now, now);
} else {
newRaffle();
setPayOuts(qID[_myID].weekNo, _result);
if (qID[_myID].isManual == true) return;
uint delay = (getWeek() * WEEKDUR) + BIRTHDAY + rafEnd + resultsDelay;
query = oraclize_query(delay, "nested", strConcat(randomStr1, uint2str(getWeek()), randomStr2), gasAmt);
qID[query].weekNo = getWeek();
qID[query].isRandom = true;
emit LogQuerySent(query, delay, now);
}
}
/**
* @dev Slices a string according to specified delimiter, returning
* the sliced parts in an array.
*
* @param _string The string to be sliced.
*/
function stringToArray(string _string) internal returns (string[]) {
var str = _string.toSlice();
var delim = ",".toSlice();
var parts = new string[](str.count(delim) + 1);
for (uint i = 0; i < parts.length; i++) {
parts[i] = str.split(delim).toString();
}
return parts;
}
/**
* @dev Takes oraclize random.org api call result string and splits
* it at the commas into an array, parses those strings in that
* array as integers and pushes them into the winning numbers
* array in the raffle's struct. Fires event logging the data,
* including the serial number of the random.org callback so
* its veracity can be proven.
*
* @param _week The week number of the raffle in question.
* @param _result The results string from oraclize callback.
*/
function setWinningNumbers(uint _week, string _result) internal {
string[] memory arr = stringToArray(_result);
for (uint i = 0; i < arr.length; i++){
raffle[_week].winNums.push(parseInt(arr[i]));
}
uint serialNo = parseInt(arr[6]);
emit LogWinningNumbers(_week, raffle[_week].numEntries, raffle[_week].winNums, prizePool, serialNo, now);
}
/*
* @dev Returns TOTAL payout per tier when calculated using the odds method.
*
* @param _numWinners Number of X match winners
* @param _matchesIndex Index of matches array (∴ 3 match win, 4 match win etc)
*/
function oddsTotal(uint _numWinners, uint _matchesIndex) internal view returns (uint) {
return oddsSingle(_matchesIndex) * _numWinners;
}
/*
* @dev Returns TOTAL payout per tier when calculated using the splits method.
*
* @param _numWinners Number of X match winners
* @param _matchesIndex Index of matches array (∴ 3 match win, 4 match win etc)
*/
function splitsTotal(uint _numWinners, uint _matchesIndex) internal view returns (uint) {
return splitsSingle(_numWinners, _matchesIndex) * _numWinners;
}
/*
* @dev Returns single payout when calculated using the odds method.
*
* @param _matchesIndex Index of matches array (∴ 3 match win, 4 match win etc)
*/
function oddsSingle(uint _matchesIndex) internal view returns (uint) {
return tktPrice * odds[_matchesIndex];
}
/*
* @dev Returns a single payout when calculated using the splits method.
*
* @param _numWinners Number of X match winners
* @param _matchesIndex Index of matches array (∴ 3 match win, 4 match win etc)
*/
function splitsSingle(uint _numWinners, uint _matchesIndex) internal view returns (uint) {
return (prizePool * pctOfPool[_matchesIndex]) / (_numWinners * 1000);
}
/**
* @dev Takes the results of the oraclize Etheraffle api call back
* and uses them to calculate the prizes due to each tier
* (3 matches, 4 matches etc) then pushes them into the winning
* amounts array in the raffle in question's struct. Calculates
* the total winnings of the raffle, subtracts it from the
* global prize pool sequesters that amount into the raffle's
* struct "unclaimed" variable, ∴ "rolling over" the unwon
* ether. Enables winner withdrawals by setting the withdraw
* open bool to true.
*
* @param _week The week number of the raffle in question.
* @param _result The results string from oraclize callback.
*/
function setPayOuts(uint _week, string _result) internal {
string[] memory numWinnersStr = stringToArray(_result);
if (numWinnersStr.length < 4) return pauseContract(2);
uint[] memory numWinnersInt = new uint[](4);
for (uint i = 0; i < 4; i++) {
numWinnersInt[i] = parseInt(numWinnersStr[i]);
}
uint[] memory payOuts = new uint[](4);
uint total;
for (i = 0; i < 4; i++) {
if (numWinnersInt[i] != 0) {
uint amt = oddsTotal(numWinnersInt[i], i) <= splitsTotal(numWinnersInt[i], i)
? oddsSingle(i)
: splitsSingle(numWinnersInt[i], i);
payOuts[i] = amt;
total += payOuts[i] * numWinnersInt[i];
}
}
raffle[_week].unclaimed = total;
if (raffle[_week].unclaimed > prizePool) return pauseContract(3);
prizePool -= raffle[_week].unclaimed;
for (i = 0; i < payOuts.length; i++) {
raffle[_week].winAmts.push(payOuts[i]);
}
raffle[_week].wdrawOpen = true;
emit LogPrizePoolsUpdated(prizePool, _week, raffle[_week].unclaimed, payOuts[0], payOuts[1], payOuts[2], payOuts[3], now);
}
/**
* @dev Function compares array of entrant's 6 chosen numbers to
* the raffle in question's winning numbers, counting how
* many matches there are.
*
* @param _week The week number of the Raffle in question
* @param _entrant Entrant's ethereum address
* @param _entryNum number of entrant's entry in question.
*/
function getMatches(uint _week, address _entrant, uint _entryNum) constant internal returns (uint) {
uint matches;
for (uint i = 0; i < 6; i++) {
for (uint j = 0; j < 6; j++) {
if (raffle[_week].entries[_entrant][_entryNum - 1][i] == raffle[_week].winNums[j]) {
matches++;
break;
}
}
}
return matches;
}
/**
* @dev Manually make an Oraclize API call, incase of automation
* failure. Only callable by the Etheraffle address.
*
* @param _delay Either a time in seconds before desired callback
* time for the API call, or a future UTC format time for
* the desired time for the API callback.
* @param _week The week number this query is for.
* @param _isRandom Whether or not the api call being made is for
* the random.org results draw, or for the Etheraffle
* API results call.
* @param _isManual The Oraclize call back is a recursive function in
* which each call fires off another call in perpetuity.
* This bool allows that recursiveness for this call to be
* turned on or off depending on caller's requirements.
*/
function manuallyMakeOraclizeCall
(
uint _week,
uint _delay,
bool _isRandom,
bool _isManual,
bool _status
)
onlyEtheraffle external
{
paused = _status;
string memory weekNumStr = uint2str(_week);
if (_isRandom == true){
bytes32 query = oraclize_query(_delay, "nested", strConcat(randomStr1, weekNumStr, randomStr2), gasAmt);
qID[query].weekNo = _week;
qID[query].isRandom = true;
qID[query].isManual = _isManual;
} else {
query = oraclize_query(_delay, "nested", strConcat(apiStr1, weekNumStr, apiStr2), gasAmt);
qID[query].weekNo = _week;
qID[query].isManual = _isManual;
}
}
/**
* @dev Set the Oraclize strings, in case of url changes. Only callable by
* the Etheraffle address .
*
* @param _newRandomHalfOne string - with properly escaped characters for
* the first half of the random.org call string.
* @param _newRandomHalfTwo string - with properly escaped characters for
* the second half of the random.org call string.
* @param _newEtheraffleHalfOne string - with properly escaped characters for
* the first half of the EtheraffleAPI call string.
* @param _newEtheraffleHalfTwo string - with properly escaped characters for
* the second half of the EtheraffleAPI call string.
*
*/
function setOraclizeString
(
string _newRandomHalfOne,
string _newRandomHalfTwo,
string _newEtheraffleHalfOne,
string _newEtheraffleHalfTwo
)
onlyEtheraffle external
{
randomStr1 = _newRandomHalfOne;
randomStr2 = _newRandomHalfTwo;
apiStr1 = _newEtheraffleHalfOne;
apiStr2 = _newEtheraffleHalfTwo;
}
/**
* @dev Set the ticket price of the raffle. Only callable by the
* Etheraffle address.
*
* @param _newPrice uint - The desired new ticket price.
*
*/
function setTktPrice(uint _newPrice) onlyEtheraffle external {
tktPrice = _newPrice;
}
/**
* @dev Set new take percentage. Only callable by the Etheraffle
* address.
*
* @param _newTake uint - The desired new take, parts per thousand.
*
*/
function setTake(uint _newTake) onlyEtheraffle external {
take = _newTake;
}
/**
* @dev Set the payouts manually, in case of a failed Oraclize call.
* Only callable by the Etheraffle address.
*
* @param _week The week number of the raffle to set the payouts for.
* @param _numMatches Number of matches. Comma-separated STRING of 4
* integers long, consisting of the number of 3 match
* winners, 4 match winners, 5 & 6 match winners in
* that order.
*/
function setPayouts(uint _week, string _numMatches) onlyEtheraffle external {
setPayOuts(_week, _numMatches);
}
/**
* @dev Set the FreeLOT token contract address, in case of future updrades.
* Only allable by the Etheraffle address.
*
* @param _newAddr New address of FreeLOT contract.
*/
function setFreeLOT(address _newAddr) onlyEtheraffle external {
freeLOT = FreeLOTInterface(_newAddr);
}
/**
* @dev Set the EthRelief contract address, and gas required to run
* the receiving function. Only allable by the Etheraffle address.
*
* @param _newAddr New address of the EthRelief contract.
*/
function setEthRelief(address _newAddr) onlyEtheraffle external {
ethRelief = _newAddr;
}
/**
* @dev Set the dividend contract address, and gas required to run
* the receive ether function. Only callable by the Etheraffle
* address.
*
* @param _newAddr New address of dividend contract.
*/
function setDisbursingAddr(address _newAddr) onlyEtheraffle external {
disburseAddr = _newAddr;
}
/**
* @dev Set the Etheraffle multisig contract address, in case of future
* upgrades. Only callable by the current Etheraffle address.
*
* @param _newAddr New address of Etheraffle multisig contract.
*/
function setEtheraffle(address _newAddr) onlyEtheraffle external {
etheraffle = _newAddr;
}
/**
* @dev Set the raffle end time, in number of seconds passed
* the start time of 00:00am Monday. Only callable by
* the Etheraffle address.
*
* @param _newTime The time desired in seconds.
*/
function setRafEnd(uint _newTime) onlyEtheraffle external {
rafEnd = _newTime;
}
/**
* @dev Set the wdrawBfr time - the time a winner has to withdraw
* their winnings before the unclaimed prizepool is rolled
* back into the global prizepool. Only callable by the
* Etheraffle address.
*
* @param _newTime The time desired in seconds.
*/
function setWithdrawBeforeTime(uint _newTime) onlyEtheraffle external {
wdrawBfr = _newTime;
}
/**
* @dev Set the paused status of the raffles. Only callable by
* the Etheraffle address.
*
* @param _status The desired status of the raffles.
*/
function setPaused(bool _status) onlyEtheraffle external {
paused = _status;
}
/**
* @dev Set the percentage-of-prizepool array. Only callable by the
* Etheraffle address.
*
* @param _newPoP An array of four integers totalling 1000.
*/
function setPercentOfPool(uint[] _newPoP) onlyEtheraffle external {
pctOfPool = _newPoP;
}
/**
* @dev Get a entrant's number of entries into a specific raffle
*
* @param _week The week number of the queried raffle.
* @param _entrant The entrant in question.
*/
function getUserNumEntries(address _entrant, uint _week) constant external returns (uint) {
return raffle[_week].entries[_entrant].length;
}
/**
* @dev Get chosen numbers of an entrant, for a specific raffle.
* Returns an array.
*
* @param _entrant The entrant in question's address.
* @param _week The week number of the queried raffle.
* @param _entryNum The entrant's entry number in this raffle.
*/
function getChosenNumbers(address _entrant, uint _week, uint _entryNum) constant external returns (uint[]) {
return raffle[_week].entries[_entrant][_entryNum-1];
}
/**
* @dev Get winning details of a raffle, ie, it's winning numbers
* and the prize amounts. Returns two arrays.
*
* @param _week The week number of the raffle in question.
*/
function getWinningDetails(uint _week) constant external returns (uint[], uint[]) {
return (raffle[_week].winNums, raffle[_week].winAmts);
}
/**
* @dev Upgrades the Etheraffle contract. Only callable by the
* Etheraffle address. Calls an addToPrizePool method as
* per the abstract contract above. Function renders the
* entry method uncallable, cancels the Oraclize recursion,
* then zeroes the prizepool and sends the funds to the new
* contract. Sets a var tracking when upgrade occurred and logs
* the event.
*
* @param _newAddr The new contract address.
*/
function upgradeContract(address _newAddr) onlyEtheraffle external {
require(upgraded == 0 && upgradeAddr == address(0));
uint amt = prizePool;
upgradeAddr = _newAddr;
upgraded = now;
week = 0;
prizePool = 0;
gasAmt = 0;
apiStr1 = "";
randomStr1 = "";
require(this.balance >= amt);
EtheraffleUpgrade(_newAddr).addToPrizePool.value(amt)();
emit LogUpgrade(_newAddr, amt, upgraded);
}
/**
* @dev Self destruct contract. Only callable by Etheraffle address.
* function. It deletes all contract code and data and forwards
* any remaining ether from non-claimed winning raffle tickets
* to the EthRelief charity contract. Requires the upgrade contract
* method to have been called 10 or more weeks prior, to allow
* winning tickets to be claimed within the usual withdrawal time
* frame.
*/
function selfDestruct() onlyEtheraffle external {
require(now - upgraded > WEEKDUR * 10);
selfdestruct(ethRelief);
}
/**
* @dev Function allowing manual addition to the global prizepool.
* Requires the caller to send ether.
*/
function addToPrizePool() payable external {
require(msg.value > 0);
prizePool += msg.value;
emit LogPrizePoolAddition(msg.sender, msg.value, now);
}
/**
* @dev Fallback function.
*/
function () payable external {}
}
|
The Oralize call back function. The oracalize api calls are recursive. One to random.org for the draw and the other to the Etheraffle api for the numbers of matches each entry made against the winning numbers. Each calls the other recursively. The former when calledback closes and reclaims any unclaimed prizepool from the raffle ten weeks previous to now. Then it disburses profit to the disbursal contract, then it sets the winning numbers received from random.org into the raffle struct. Finally it prepares the next oraclize call. Which latter callback first sets up the new raffle struct, then sets the payouts based on the number of winners in each tier returned from the api call, then prepares the next oraclize query for a week later to draw the next raffle&39;s winning numbers. _myID bytes32 - Unique id oraclize provides with their callbacks. _result string - The result of the api call./
|
function __callback(bytes32 _myID, string _result) onlyIfNotPaused {
require(msg.sender == oraclize_cbAddress() || msg.sender == etheraffle);
emit LogOraclizeCallback(msg.sender, _myID, _result, qID[_myID].weekNo, now);
if (qID[_myID].isRandom == true) {
reclaimUnclaimed();
disburseFunds(qID[_myID].weekNo);
setWinningNumbers(qID[_myID].weekNo, _result);
if (qID[_myID].isManual == true) return;
bytes32 query = oraclize_query(matchesDelay, "nested", strConcat(apiStr1, uint2str(qID[_myID].weekNo), apiStr2), gasAmt);
qID[query].weekNo = qID[_myID].weekNo;
emit LogQuerySent(query, matchesDelay + now, now);
newRaffle();
setPayOuts(qID[_myID].weekNo, _result);
if (qID[_myID].isManual == true) return;
uint delay = (getWeek() * WEEKDUR) + BIRTHDAY + rafEnd + resultsDelay;
query = oraclize_query(delay, "nested", strConcat(randomStr1, uint2str(getWeek()), randomStr2), gasAmt);
qID[query].weekNo = getWeek();
qID[query].isRandom = true;
emit LogQuerySent(query, delay, now);
}
}
| 10,772,786
|
./partial_match/1/0x253162cEe078572D33f239106246eeC18a59f0F0/sources/WorldMillionaireChallengeNft.sol
|
bytes4(keccak256(bytes('transfer(address,uint256)')));
|
function _transferErc20(
address token,
uint256 amount,
address recipient
) private {
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(0xa9059cbb, recipient, amount)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"Recoverable: TRANSFER_FAILED"
);
}
| 9,290,692
|
pragma solidity ^0.4.24;
// File: contracts\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\openzeppelin-solidity\contracts\lifecycle\Pausable.sol
/**
* @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() public onlyOwner whenNotPaused {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpause();
}
}
// File: contracts\openzeppelin-solidity\contracts\token\ERC20\ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: contracts\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: contracts\openzeppelin-solidity\contracts\token\ERC20\BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
uint256 internal totalSupply_;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
// File: contracts\openzeppelin-solidity\contracts\token\ERC20\ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address _owner, address _spender)
public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: contracts\openzeppelin-solidity\contracts\token\ERC20\StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/issues/20
* Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: contracts\openzeppelin-solidity\contracts\token\ERC20\MintableToken.sol
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address _to,
uint256 _amount
)
public
hasMintPermission
canMint
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() public onlyOwner canMint returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
// File: contracts\openzeppelin-solidity\contracts\token\ERC20\BurnableToken.sol
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
// File: contracts\AccountLockableToken.sol
/**
* @title Account Lockable Token
*/
contract AccountLockableToken is Ownable {
mapping(address => bool) public lockStates;
event LockAccount(address indexed lockAccount);
event UnlockAccount(address indexed unlockAccount);
/**
* @dev Throws if called by locked account
*/
modifier whenNotLocked() {
require(!lockStates[msg.sender]);
_;
}
/**
* @dev Lock target account
* @param _target Target account to lock
*/
function lockAccount(address _target) public
onlyOwner
returns (bool)
{
require(_target != owner);
require(!lockStates[_target]);
lockStates[_target] = true;
emit LockAccount(_target);
return true;
}
/**
* @dev Unlock target account
* @param _target Target account to unlock
*/
function unlockAccount(address _target) public
onlyOwner
returns (bool)
{
require(_target != owner);
require(lockStates[_target]);
lockStates[_target] = false;
emit UnlockAccount(_target);
return true;
}
}
// File: contracts\WithdrawableToken.sol
/**
* @title Withdrawable token
* @dev Token that can be the withdrawal.
*/
contract WithdrawableToken is BasicToken, Ownable {
using SafeMath for uint256;
bool public withdrawingFinished = false;
event Withdraw(address _from, address _to, uint256 _value);
event WithdrawFinished();
modifier canWithdraw() {
require(!withdrawingFinished);
_;
}
modifier hasWithdrawPermission() {
require(msg.sender == owner);
_;
}
/**
* @dev Withdraw the amount of tokens to onwer.
* @param _from address The address which owner want to withdraw tokens form.
* @param _value uint256 the amount of tokens to be transferred.
*/
function withdraw(address _from, uint256 _value) public
hasWithdrawPermission
canWithdraw
returns (bool)
{
require(_value <= balances[_from]);
balances[_from] = balances[_from].sub(_value);
balances[owner] = balances[owner].add(_value);
emit Transfer(_from, owner, _value);
emit Withdraw(_from, owner, _value);
return true;
}
/**
* @dev Withdraw the amount of tokens to another.
* @param _from address The address which owner want to withdraw tokens from.
* @param _to address The address which owner want to transfer to.
* @param _value uint256 the amount of tokens to be transferred.
*/
function withdrawFrom(address _from, address _to, uint256 _value) public
hasWithdrawPermission
canWithdraw
returns (bool)
{
require(_value <= balances[_from]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(_from, _to, _value);
emit Withdraw(_from, _to, _value);
return true;
}
/**
* @dev Function to stop withdrawing new tokens.
* @return True if the operation was successful.
*/
function finishingWithdrawing() public
onlyOwner
canWithdraw
returns (bool)
{
withdrawingFinished = true;
emit WithdrawFinished();
return true;
}
}
// File: contracts\MilestoneLockToken.sol
/**
* @title Milestone Lock Token
* @dev Token lock that can be the milestone policy applied.
*/
contract MilestoneLockToken is StandardToken, Ownable {
using SafeMath for uint256;
struct Policy {
uint256 kickOff;
uint256[] periods;
uint8[] percentages;
}
struct MilestoneLock {
uint8[] policies;
uint256[] standardBalances;
}
uint8 constant MAX_POLICY = 100;
uint256 constant MAX_PERCENTAGE = 100;
mapping(uint8 => Policy) internal policies;
mapping(address => MilestoneLock) internal milestoneLocks;
event SetPolicyKickOff(uint8 policy, uint256 kickOff);
event PolicyAdded(uint8 policy);
event PolicyRemoved(uint8 policy);
event PolicyAttributeAdded(uint8 policy, uint256 period, uint8 percentage);
event PolicyAttributeRemoved(uint8 policy, uint256 period);
event PolicyAttributeModified(uint8 policy, uint256 period, uint8 percentage);
/**
* @dev Transfer token for a specified address when enough available unlock balance.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public
returns (bool)
{
require(getAvailableBalance(msg.sender) >= _value);
return super.transfer(_to, _value);
}
/**
* @dev Transfer tokens from one address to another when enough available unlock balance.
* @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(getAvailableBalance(_from) >= _value);
return super.transferFrom(_from, _to, _value);
}
/**
* @dev Distribute the amounts of tokens to from owner's balance with the milestone policy to a policy-free user.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
* @param _policy index of milestone policy to apply.
*/
function distributeWithPolicy(address _to, uint256 _value, uint8 _policy) public
onlyOwner
returns (bool)
{
require(_to != address(0));
require(_value <= balances[owner]);
require(_policy < MAX_POLICY);
require(_checkPolicyEnabled(_policy));
balances[owner] = balances[owner].sub(_value);
balances[_to] = balances[_to].add(_value);
_setMilestoneTo(_to, _value, _policy);
emit Transfer(owner, _to, _value);
return true;
}
/**
* @dev add milestone policy.
* @param _policy index of the milestone policy you want to add.
* @param _periods periods of the milestone you want to add.
* @param _percentages unlock percentages of the milestone you want to add.
*/
function addPolicy(uint8 _policy, uint256[] _periods, uint8[] _percentages) public
onlyOwner
returns (bool)
{
require(_policy < MAX_POLICY);
require(!_checkPolicyEnabled(_policy));
require(_periods.length > 0);
require(_percentages.length > 0);
require(_periods.length == _percentages.length);
policies[_policy].periods = _periods;
policies[_policy].percentages = _percentages;
emit PolicyAdded(_policy);
return true;
}
/**
* @dev remove milestone policy.
* @param _policy index of the milestone policy you want to remove.
*/
function removePolicy(uint8 _policy) public
onlyOwner
returns (bool)
{
require(_policy < MAX_POLICY);
delete policies[_policy];
emit PolicyRemoved(_policy);
return true;
}
/**
* @dev get milestone policy information.
* @param _policy index of milestone policy.
*/
function getPolicy(uint8 _policy) public
view
returns (uint256 kickOff, uint256[] periods, uint8[] percentages)
{
require(_policy < MAX_POLICY);
return (
policies[_policy].kickOff,
policies[_policy].periods,
policies[_policy].percentages
);
}
/**
* @dev set milestone policy's kickoff time.
* @param _policy index of milestone poicy.
* @param _time kickoff time of policy.
*/
function setKickOff(uint8 _policy, uint256 _time) public
onlyOwner
returns (bool)
{
require(_policy < MAX_POLICY);
require(_checkPolicyEnabled(_policy));
policies[_policy].kickOff = _time;
return true;
}
/**
* @dev add attribute to milestone policy.
* @param _policy index of milestone policy.
* @param _period period of policy attribute.
* @param _percentage percentage of unlocking when reaching policy.
*/
function addPolicyAttribute(uint8 _policy, uint256 _period, uint8 _percentage) public
onlyOwner
returns (bool)
{
require(_policy < MAX_POLICY);
require(_checkPolicyEnabled(_policy));
Policy storage policy = policies[_policy];
for (uint256 i = 0; i < policy.periods.length; i++) {
if (policy.periods[i] == _period) {
revert();
return false;
}
}
policy.periods.push(_period);
policy.percentages.push(_percentage);
emit PolicyAttributeAdded(_policy, _period, _percentage);
return true;
}
/**
* @dev remove attribute from milestone policy.
* @param _policy index of milestone policy attribute.
* @param _period period of target policy.
*/
function removePolicyAttribute(uint8 _policy, uint256 _period) public
onlyOwner
returns (bool)
{
require(_policy < MAX_POLICY);
Policy storage policy = policies[_policy];
for (uint256 i = 0; i < policy.periods.length; i++) {
if (policy.periods[i] == _period) {
_removeElementAt256(policy.periods, i);
_removeElementAt8(policy.percentages, i);
emit PolicyAttributeRemoved(_policy, _period);
return true;
}
}
revert();
return false;
}
/**
* @dev modify attribute from milestone policy.
* @param _policy index of milestone policy.
* @param _period period of target policy attribute.
* @param _percentage percentage to modified.
*/
function modifyPolicyAttribute(uint8 _policy, uint256 _period, uint8 _percentage) public
onlyOwner
returns (bool)
{
require(_policy < MAX_POLICY);
Policy storage policy = policies[_policy];
for (uint256 i = 0; i < policy.periods.length; i++) {
if (policy.periods[i] == _period) {
policy.percentages[i] = _percentage;
emit PolicyAttributeModified(_policy, _period, _percentage);
return true;
}
}
revert();
return false;
}
/**
* @dev get policy's locked percentage of milestone policy from now.
* @param _policy index of milestone policy for calculate locked percentage.
*/
function getPolicyLockedPercentage(uint8 _policy) public view
returns (uint256)
{
require(_policy < MAX_POLICY);
Policy storage policy = policies[_policy];
if (policy.periods.length == 0) {
return 0;
}
if (policy.kickOff == 0 ||
policy.kickOff > now) {
return MAX_PERCENTAGE;
}
uint256 unlockedPercentage = 0;
for (uint256 i = 0; i < policy.periods.length; i++) {
if (policy.kickOff.add(policy.periods[i]) <= now) {
unlockedPercentage =
unlockedPercentage.add(policy.percentages[i]);
}
}
if (unlockedPercentage > MAX_PERCENTAGE) {
return 0;
}
return MAX_PERCENTAGE.sub(unlockedPercentage);
}
/**
* @dev change account's milestone policy.
* @param _from address for milestone policy applyed from.
* @param _prevPolicy index of original milestone policy.
* @param _newPolicy index of milestone policy to be changed.
*/
function modifyMilestoneFrom(address _from, uint8 _prevPolicy, uint8 _newPolicy) public
onlyOwner
returns (bool)
{
require(_from != address(0));
require(_prevPolicy != _newPolicy);
require(_prevPolicy < MAX_POLICY);
require(_checkPolicyEnabled(_prevPolicy));
require(_newPolicy < MAX_POLICY);
require(_checkPolicyEnabled(_newPolicy));
uint256 prevPolicyIndex = _getAppliedPolicyIndex(_from, _prevPolicy);
require(prevPolicyIndex < MAX_POLICY);
_setMilestoneTo(_from, milestoneLocks[_from].standardBalances[prevPolicyIndex], _newPolicy);
milestoneLocks[_from].standardBalances[prevPolicyIndex] = 0;
return true;
}
/**
* @dev remove milestone policy from account.
* @param _from address for applied milestone policy removes from.
* @param _policy index of milestone policy remove.
*/
function removeMilestoneFrom(address _from, uint8 _policy) public
onlyOwner
returns (bool)
{
require(_from != address(0));
require(_policy < MAX_POLICY);
uint256 policyIndex = _getAppliedPolicyIndex(_from, _policy);
require(policyIndex < MAX_POLICY);
milestoneLocks[_from].standardBalances[policyIndex] = 0;
return true;
}
/**
* @dev get accounts milestone policy state information.
* @param _account address for milestone policy applied.
*/
function getUserMilestone(address _account) public
view
returns (uint8[] accountPolicies, uint256[] standardBalances)
{
return (
milestoneLocks[_account].policies,
milestoneLocks[_account].standardBalances
);
}
/**
* @dev available unlock balance.
* @param _account address for available unlock balance.
*/
function getAvailableBalance(address _account) public
view
returns (uint256)
{
return balances[_account].sub(getTotalLockedBalance(_account));
}
/**
* @dev calcuate locked balance of milestone policy from now.
* @param _account address for lock balance.
* @param _policy index of applied milestone policy.
*/
function getLockedBalance(address _account, uint8 _policy) public
view
returns (uint256)
{
require(_policy < MAX_POLICY);
uint256 policyIndex = _getAppliedPolicyIndex(_account, _policy);
if (policyIndex >= MAX_POLICY) {
return 0;
}
MilestoneLock storage milestoneLock = milestoneLocks[_account];
if (milestoneLock.standardBalances[policyIndex] == 0) {
return 0;
}
uint256 lockedPercentage =
getPolicyLockedPercentage(milestoneLock.policies[policyIndex]);
return milestoneLock.standardBalances[policyIndex].div(MAX_PERCENTAGE).mul(lockedPercentage);
}
/**
* @dev calcuate locked balance of milestone policy from now.
* @param _account address for lock balance.
*/
function getTotalLockedBalance(address _account) public
view
returns (uint256)
{
MilestoneLock storage milestoneLock = milestoneLocks[_account];
uint256 totalLockedBalance = 0;
for (uint256 i = 0; i < milestoneLock.policies.length; i++) {
totalLockedBalance = totalLockedBalance.add(
getLockedBalance(_account, milestoneLock.policies[i])
);
}
return totalLockedBalance;
}
/**
* @dev check for policy is enabled
* @param _policy index of milestone policy.
*/
function _checkPolicyEnabled(uint8 _policy) internal
view
returns (bool)
{
return (policies[_policy].periods.length > 0);
}
/**
* @dev get milestone policy index applied to a user.
* @param _to address The address which you want get to.
* @param _policy index of milestone policy applied.
*/
function _getAppliedPolicyIndex(address _to, uint8 _policy) internal
view
returns (uint8)
{
require(_policy < MAX_POLICY);
MilestoneLock storage milestoneLock = milestoneLocks[_to];
for (uint8 i = 0; i < milestoneLock.policies.length; i++) {
if (milestoneLock.policies[i] == _policy) {
return i;
}
}
return MAX_POLICY;
}
/**
* @dev set milestone policy applies to a user.
* @param _to address The address which
* @param _value The amount to apply
* @param _policy index of milestone policy to apply.
*/
function _setMilestoneTo(address _to, uint256 _value, uint8 _policy) internal
{
uint8 policyIndex = _getAppliedPolicyIndex(_to, _policy);
if (policyIndex < MAX_POLICY) {
milestoneLocks[_to].standardBalances[policyIndex] =
milestoneLocks[_to].standardBalances[policyIndex].add(_value);
} else {
milestoneLocks[_to].policies.push(_policy);
milestoneLocks[_to].standardBalances.push(_value);
}
}
/**
* @dev utility for uint256 array
* @param _array target array
* @param _index array index to remove
*/
function _removeElementAt256(uint256[] storage _array, uint256 _index) internal
returns (bool)
{
if (_array.length <= _index) {
return false;
}
for (uint256 i = _index; i < _array.length - 1; i++) {
_array[i] = _array[i + 1];
}
delete _array[_array.length - 1];
_array.length--;
return true;
}
/**
* @dev utility for uint8 array
* @param _array target array
* @param _index array index to remove
*/
function _removeElementAt8(uint8[] storage _array, uint256 _index) internal
returns (bool)
{
if (_array.length <= _index) {
return false;
}
for (uint256 i = _index; i < _array.length - 1; i++) {
_array[i] = _array[i + 1];
}
delete _array[_array.length - 1];
_array.length--;
return true;
}
}
// File: contracts\Hena.sol
/**
* @title Hena token
*/
contract Hena is
Pausable,
MintableToken,
BurnableToken,
AccountLockableToken,
WithdrawableToken,
MilestoneLockToken
{
uint256 constant MAX_SUFFLY = 1000000000;
string public name;
string public symbol;
uint8 public decimals;
constructor() public
{
name = "Hena";
symbol = "HENA";
decimals = 18;
totalSupply_ = MAX_SUFFLY * (10 ** uint(decimals));
balances[owner] = totalSupply_;
emit Transfer(address(0), owner, totalSupply_);
}
function() public
{
revert();
}
/**
* @dev Transfer token for a specified address when if not paused and not locked account
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public
whenNotPaused
whenNotLocked
returns (bool)
{
return super.transfer(_to, _value);
}
/**
* @dev Transfer tokens from one address to anther when if not paused and not locked account
* @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
whenNotPaused
whenNotLocked
returns (bool)
{
require(!lockStates[_from]);
return super.transferFrom(_from, _to, _value);
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender
when if not paused and not locked account
* @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
whenNotPaused
whenNotLocked
returns (bool)
{
return super.approve(_spender, _value);
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender when if not paused and not locked account
* @param _spender address which will spend the funds.
* @param _addedValue amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint256 _addedValue) public
whenNotPaused
whenNotLocked
returns (bool)
{
return super.increaseApproval(_spender, _addedValue);
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* @param _spender address which will spend the funds.
* @param _subtractedValue amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint256 _subtractedValue) public
whenNotPaused
whenNotLocked
returns (bool)
{
return super.decreaseApproval(_spender, _subtractedValue);
}
/**
* @dev Distribute the amount of tokens to owner's balance.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function distribute(address _to, uint256 _value) public
onlyOwner
returns (bool)
{
require(_to != address(0));
require(_value <= balances[owner]);
balances[owner] = balances[owner].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(owner, _to, _value);
return true;
}
/**
* @dev Burns a specific amount of tokens by owner.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public
onlyOwner
{
super.burn(_value);
}
/**
* @dev batch to the policy to account's available balance.
* @param _policy index of milestone policy to apply.
* @param _addresses The addresses to apply.
*/
function batchToApplyMilestone(uint8 _policy, address[] _addresses) public
onlyOwner
returns (bool[])
{
require(_policy < MAX_POLICY);
require(_checkPolicyEnabled(_policy));
require(_addresses.length > 0);
bool[] memory results = new bool[](_addresses.length);
for (uint256 i = 0; i < _addresses.length; i++) {
results[i] = false;
if (_addresses[i] != address(0)) {
uint256 availableBalance = getAvailableBalance(_addresses[i]);
results[i] = (availableBalance > 0);
if (results[i]) {
_setMilestoneTo(_addresses[i], availableBalance, _policy);
}
}
}
return results;
}
}
|
get policy's locked percentage of milestone policy from now. _policy index of milestone policy for calculate locked percentage./
|
function getPolicyLockedPercentage(uint8 _policy) public view
returns (uint256)
{
require(_policy < MAX_POLICY);
Policy storage policy = policies[_policy];
if (policy.periods.length == 0) {
return 0;
}
if (policy.kickOff == 0 ||
policy.kickOff > now) {
return MAX_PERCENTAGE;
}
uint256 unlockedPercentage = 0;
for (uint256 i = 0; i < policy.periods.length; i++) {
if (policy.kickOff.add(policy.periods[i]) <= now) {
unlockedPercentage =
unlockedPercentage.add(policy.percentages[i]);
}
}
if (unlockedPercentage > MAX_PERCENTAGE) {
return 0;
}
return MAX_PERCENTAGE.sub(unlockedPercentage);
}
| 13,627,738
|
pragma solidity ^0.5.0;
import "./ERC1155.sol";
contract ERC1155withAdapter is ERC1155 {
mapping(uint256 => address) public adapter;
mapping(uint256 => uint256) public totalSupply;
address public template;
event NewAdapter(uint256 indexed id, address indexed adapter);
constructor() public {
template = address(new ERC20Adapter());
}
function createAdapter(uint256 _id, string memory _name, string memory _symbol, uint8 _decimals) public {
require(adapter[_id] == address(0));
address a = createClone(template);
ERC20Adapter(a).setup(_id, _name, _symbol, _decimals);
adapter[_id] = a;
emit NewAdapter(_id, a);
}
function createClone(address target) internal returns (address result) {
bytes20 targetBytes = bytes20(target);
assembly {
let clone := mload(0x40)
mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone, 0x14), targetBytes)
mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
result := create(0, clone, 0x37)
}
}
function transferByAdapter(address _from, address _to, uint256 _id, uint256 _value) public returns(bool) {
require(adapter[_id] == msg.sender);
// SafeMath will throw with insuficient funds _from
// or if _id is not valid (balance will be 0)
balances[_id][_from] = balances[_id][_from].sub(_value);
balances[_id][_to] = _value.add(balances[_id][_to]);
bytes memory _data;
if(_to.isContract()){
if(ERC165(_from).supportsInterface(0x4e2312e0)){
_doSafeTransferAcceptanceCheck(_from, _from, _to, _id, _value, _data);
}
}
// MUST emit event
emit TransferSingle(msg.sender, _from, _to, _id, _value);
return true;
}
}
contract ERC20Adapter {
using SafeMath for uint256;
ERC1155withAdapter public entity;
uint256 public id;
string public name;
string public symbol;
uint8 public decimals;
mapping (address => mapping (address => uint256)) private allowed;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev setup the adapter, use as a constructor.
*/
function setup(uint256 _id, string memory _name, string memory _symbol, uint8 _decimals) public {
require(id == 0 && address(entity) == address(0));
entity = ERC1155withAdapter(msg.sender);
id = _id;
name = _name;
symbol = _symbol;
decimals = _decimals;
}
function totalSupply() external view returns (uint256){
return entity.totalSupply(id);
}
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256){
return entity.balanceOf(account, id);
}
/**
* @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){
require(entity.transferByAdapter(msg.sender, recipient, id, amount));
emit Transfer(msg.sender, recipient, amount);
return true;
}
/**
* @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){
return allowed[owner][spender];
}
/**
* @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) external returns (bool){
allowed[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @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){
allowed[sender][msg.sender] = allowed[sender][msg.sender].sub(amount);
require(entity.transferByAdapter(sender, recipient, id, amount));
emit Transfer(sender, recipient, amount);
return true;
}
}
|
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){
require(entity.transferByAdapter(msg.sender, recipient, id, amount));
emit Transfer(msg.sender, recipient, amount);
return true;
}
| 2,496,933
|
// Dependency file: openzeppelin-solidity/contracts/ownership/Ownable.sol
// pragma solidity ^0.4.24;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
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;
}
}
// Dependency file: @evolutionland/common/contracts/interfaces/IInterstellarEncoder.sol
// pragma solidity ^0.4.24;
contract IInterstellarEncoder {
uint256 constant CLEAR_HIGH = 0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff;
uint256 public constant MAGIC_NUMBER = 42; // Interstellar Encoding Magic Number.
uint256 public constant CHAIN_ID = 1; // Ethereum mainet.
uint256 public constant CURRENT_LAND = 1; // 1 is Atlantis, 0 is NaN.
enum ObjectClass {
NaN,
LAND,
APOSTLE,
OBJECT_CLASS_COUNT
}
function registerNewObjectClass(address _objectContract, uint8 objectClass) public;
function registerNewTokenContract(address _tokenAddress) public;
function encodeTokenId(address _tokenAddress, uint8 _objectClass, uint128 _objectIndex) public view returns (uint256 _tokenId);
function encodeTokenIdForObjectContract(
address _tokenAddress, address _objectContract, uint128 _objectId) public view returns (uint256 _tokenId);
function getContractAddress(uint256 _tokenId) public view returns (address);
function getObjectId(uint256 _tokenId) public view returns (uint128 _objectId);
function getObjectClass(uint256 _tokenId) public view returns (uint8);
function getObjectAddress(uint256 _tokenId) public view returns (address);
}
// Dependency file: @evolutionland/common/contracts/InterstellarEncoder.sol
// pragma solidity ^0.4.24;
// import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
// import "@evolutionland/common/contracts/interfaces/IInterstellarEncoder.sol";
contract InterstellarEncoder is IInterstellarEncoder, Ownable {
// [magic_number, chain_id, contract_id <2>, origin_chain_id, origin_contract_id<2>, object_class, convert_type, <6>, land, <128>]
mapping(uint16 => address) public contractId2Address;
mapping(address => uint16) public contractAddress2Id;
mapping(address => uint8) public objectContract2ObjectClass;
uint16 public lastContractId = 0;
function encodeTokenId(address _tokenAddress, uint8 _objectClass, uint128 _objectId) public view returns (uint256 _tokenId) {
uint16 contractId = contractAddress2Id[_tokenAddress];
require(contractAddress2Id[_tokenAddress] > 0, "Contract address does not exist");
_tokenId = (MAGIC_NUMBER << 248) + (CHAIN_ID << 240) + (uint256(contractId) << 224)
+ (CHAIN_ID << 216) + (uint256(contractId) << 200) + (uint256(_objectClass) << 192) + (CURRENT_LAND << 128) + uint256(_objectId);
}
function encodeTokenIdForObjectContract(
address _tokenAddress, address _objectContract, uint128 _objectId) public view returns (uint256 _tokenId) {
require (objectContract2ObjectClass[_objectContract] > 0, "Object class for this object contract does not exist.");
_tokenId = encodeTokenId(_tokenAddress, objectContract2ObjectClass[_objectContract], _objectId);
}
function registerNewTokenContract(address _tokenAddress) public onlyOwner {
require(contractAddress2Id[_tokenAddress] == 0, "Contract address already exist");
require(lastContractId < 65535, "Contract Id already reach maximum.");
lastContractId += 1;
contractAddress2Id[_tokenAddress] = lastContractId;
contractId2Address[lastContractId] = _tokenAddress;
}
function registerNewObjectClass(address _objectContract, uint8 objectClass) public onlyOwner {
objectContract2ObjectClass[_objectContract] = objectClass;
}
function getContractAddress(uint256 _tokenId) public view returns (address) {
return contractId2Address[uint16((_tokenId << 16) >> 240)];
}
function getObjectId(uint256 _tokenId) public view returns (uint128 _objectId) {
return uint128(_tokenId & CLEAR_HIGH);
}
}
// Dependency file: @evolutionland/common/contracts/interfaces/ISettingsRegistry.sol
// pragma solidity ^0.4.24;
contract ISettingsRegistry {
enum SettingsValueTypes { NONE, UINT, STRING, ADDRESS, BYTES, BOOL, INT }
function uintOf(bytes32 _propertyName) public view returns (uint256);
function stringOf(bytes32 _propertyName) public view returns (string);
function addressOf(bytes32 _propertyName) public view returns (address);
function bytesOf(bytes32 _propertyName) public view returns (bytes);
function boolOf(bytes32 _propertyName) public view returns (bool);
function intOf(bytes32 _propertyName) public view returns (int);
function setUintProperty(bytes32 _propertyName, uint _value) public;
function setStringProperty(bytes32 _propertyName, string _value) public;
function setAddressProperty(bytes32 _propertyName, address _value) public;
function setBytesProperty(bytes32 _propertyName, bytes _value) public;
function setBoolProperty(bytes32 _propertyName, bool _value) public;
function setIntProperty(bytes32 _propertyName, int _value) public;
function getValueTypeOf(bytes32 _propertyName) public view returns (uint /* SettingsValueTypes */ );
event ChangeProperty(bytes32 indexed _propertyName, uint256 _type);
}
// Dependency file: @evolutionland/common/contracts/interfaces/IAuthority.sol
// pragma solidity ^0.4.24;
contract IAuthority {
function canCall(
address src, address dst, bytes4 sig
) public view returns (bool);
}
// Dependency file: @evolutionland/common/contracts/DSAuth.sol
// pragma solidity ^0.4.24;
// import '/Users/echo/workspace/contract/evolutionlandorg/land/node_modules/@evolutionland/common/contracts/interfaces/IAuthority.sol';
contract DSAuthEvents {
event LogSetAuthority (address indexed authority);
event LogSetOwner (address indexed owner);
}
/**
* @title DSAuth
* @dev The DSAuth contract is reference implement of https://github.com/dapphub/ds-auth
* But in the isAuthorized method, the src from address(this) is remove for safty concern.
*/
contract DSAuth is DSAuthEvents {
IAuthority public authority;
address public owner;
constructor() public {
owner = msg.sender;
emit LogSetOwner(msg.sender);
}
function setOwner(address owner_)
public
auth
{
owner = owner_;
emit LogSetOwner(owner);
}
function setAuthority(IAuthority authority_)
public
auth
{
authority = authority_;
emit LogSetAuthority(authority);
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig));
_;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
if (src == owner) {
return true;
} else if (authority == IAuthority(0)) {
return false;
} else {
return authority.canCall(src, this, sig);
}
}
}
// Dependency file: @evolutionland/common/contracts/SettingsRegistry.sol
// pragma solidity ^0.4.24;
// import "@evolutionland/common/contracts/interfaces/ISettingsRegistry.sol";
// import "@evolutionland/common/contracts/DSAuth.sol";
/**
* @title SettingsRegistry
* @dev This contract holds all the settings for updating and querying.
*/
contract SettingsRegistry is ISettingsRegistry, DSAuth {
mapping(bytes32 => uint256) public uintProperties;
mapping(bytes32 => string) public stringProperties;
mapping(bytes32 => address) public addressProperties;
mapping(bytes32 => bytes) public bytesProperties;
mapping(bytes32 => bool) public boolProperties;
mapping(bytes32 => int256) public intProperties;
mapping(bytes32 => SettingsValueTypes) public valueTypes;
function uintOf(bytes32 _propertyName) public view returns (uint256) {
require(valueTypes[_propertyName] == SettingsValueTypes.UINT, "Property type does not match.");
return uintProperties[_propertyName];
}
function stringOf(bytes32 _propertyName) public view returns (string) {
require(valueTypes[_propertyName] == SettingsValueTypes.STRING, "Property type does not match.");
return stringProperties[_propertyName];
}
function addressOf(bytes32 _propertyName) public view returns (address) {
require(valueTypes[_propertyName] == SettingsValueTypes.ADDRESS, "Property type does not match.");
return addressProperties[_propertyName];
}
function bytesOf(bytes32 _propertyName) public view returns (bytes) {
require(valueTypes[_propertyName] == SettingsValueTypes.BYTES, "Property type does not match.");
return bytesProperties[_propertyName];
}
function boolOf(bytes32 _propertyName) public view returns (bool) {
require(valueTypes[_propertyName] == SettingsValueTypes.BOOL, "Property type does not match.");
return boolProperties[_propertyName];
}
function intOf(bytes32 _propertyName) public view returns (int) {
require(valueTypes[_propertyName] == SettingsValueTypes.INT, "Property type does not match.");
return intProperties[_propertyName];
}
function setUintProperty(bytes32 _propertyName, uint _value) public auth {
require(
valueTypes[_propertyName] == SettingsValueTypes.NONE || valueTypes[_propertyName] == SettingsValueTypes.UINT, "Property type does not match.");
uintProperties[_propertyName] = _value;
valueTypes[_propertyName] = SettingsValueTypes.UINT;
emit ChangeProperty(_propertyName, uint256(SettingsValueTypes.UINT));
}
function setStringProperty(bytes32 _propertyName, string _value) public auth {
require(
valueTypes[_propertyName] == SettingsValueTypes.NONE || valueTypes[_propertyName] == SettingsValueTypes.STRING, "Property type does not match.");
stringProperties[_propertyName] = _value;
valueTypes[_propertyName] = SettingsValueTypes.STRING;
emit ChangeProperty(_propertyName, uint256(SettingsValueTypes.STRING));
}
function setAddressProperty(bytes32 _propertyName, address _value) public auth {
require(
valueTypes[_propertyName] == SettingsValueTypes.NONE || valueTypes[_propertyName] == SettingsValueTypes.ADDRESS, "Property type does not match.");
addressProperties[_propertyName] = _value;
valueTypes[_propertyName] = SettingsValueTypes.ADDRESS;
emit ChangeProperty(_propertyName, uint256(SettingsValueTypes.ADDRESS));
}
function setBytesProperty(bytes32 _propertyName, bytes _value) public auth {
require(
valueTypes[_propertyName] == SettingsValueTypes.NONE || valueTypes[_propertyName] == SettingsValueTypes.BYTES, "Property type does not match.");
bytesProperties[_propertyName] = _value;
valueTypes[_propertyName] = SettingsValueTypes.BYTES;
emit ChangeProperty(_propertyName, uint256(SettingsValueTypes.BYTES));
}
function setBoolProperty(bytes32 _propertyName, bool _value) public auth {
require(
valueTypes[_propertyName] == SettingsValueTypes.NONE || valueTypes[_propertyName] == SettingsValueTypes.BOOL, "Property type does not match.");
boolProperties[_propertyName] = _value;
valueTypes[_propertyName] = SettingsValueTypes.BOOL;
emit ChangeProperty(_propertyName, uint256(SettingsValueTypes.BOOL));
}
function setIntProperty(bytes32 _propertyName, int _value) public auth {
require(
valueTypes[_propertyName] == SettingsValueTypes.NONE || valueTypes[_propertyName] == SettingsValueTypes.INT, "Property type does not match.");
intProperties[_propertyName] = _value;
valueTypes[_propertyName] = SettingsValueTypes.INT;
emit ChangeProperty(_propertyName, uint256(SettingsValueTypes.INT));
}
function getValueTypeOf(bytes32 _propertyName) public view returns (uint256 /* SettingsValueTypes */ ) {
return uint256(valueTypes[_propertyName]);
}
}
// Dependency file: @evolutionland/common/contracts/SettingIds.sol
// pragma solidity ^0.4.24;
/**
Id definitions for SettingsRegistry.sol
Can be used in conjunction with the settings registry to get properties
*/
contract SettingIds {
bytes32 public constant CONTRACT_RING_ERC20_TOKEN = "CONTRACT_RING_ERC20_TOKEN";
bytes32 public constant CONTRACT_KTON_ERC20_TOKEN = "CONTRACT_KTON_ERC20_TOKEN";
bytes32 public constant CONTRACT_GOLD_ERC20_TOKEN = "CONTRACT_GOLD_ERC20_TOKEN";
bytes32 public constant CONTRACT_WOOD_ERC20_TOKEN = "CONTRACT_WOOD_ERC20_TOKEN";
bytes32 public constant CONTRACT_WATER_ERC20_TOKEN = "CONTRACT_WATER_ERC20_TOKEN";
bytes32 public constant CONTRACT_FIRE_ERC20_TOKEN = "CONTRACT_FIRE_ERC20_TOKEN";
bytes32 public constant CONTRACT_SOIL_ERC20_TOKEN = "CONTRACT_SOIL_ERC20_TOKEN";
bytes32 public constant CONTRACT_OBJECT_OWNERSHIP = "CONTRACT_OBJECT_OWNERSHIP";
bytes32 public constant CONTRACT_TOKEN_LOCATION = "CONTRACT_TOKEN_LOCATION";
bytes32 public constant CONTRACT_LAND_BASE = "CONTRACT_LAND_BASE";
bytes32 public constant CONTRACT_USER_POINTS = "CONTRACT_USER_POINTS";
bytes32 public constant CONTRACT_INTERSTELLAR_ENCODER = "CONTRACT_INTERSTELLAR_ENCODER";
bytes32 public constant CONTRACT_DIVIDENDS_POOL = "CONTRACT_DIVIDENDS_POOL";
bytes32 public constant CONTRACT_TOKEN_USE = "CONTRACT_TOKEN_USE";
bytes32 public constant CONTRACT_REVENUE_POOL = "CONTRACT_REVENUE_POOL";
bytes32 public constant CONTRACT_ERC721_BRIDGE = "CONTRACT_ERC721_BRIDGE";
bytes32 public constant CONTRACT_PET_BASE = "CONTRACT_PET_BASE";
// Cut owner takes on each auction, measured in basis points (1/100 of a percent).
// this can be considered as transaction fee.
// Values 0-10,000 map to 0%-100%
// set ownerCut to 4%
// ownerCut = 400;
bytes32 public constant UINT_AUCTION_CUT = "UINT_AUCTION_CUT"; // Denominator is 10000
bytes32 public constant UINT_TOKEN_OFFER_CUT = "UINT_TOKEN_OFFER_CUT"; // Denominator is 10000
// Cut referer takes on each auction, measured in basis points (1/100 of a percent).
// which cut from transaction fee.
// Values 0-10,000 map to 0%-100%
// set refererCut to 4%
// refererCut = 400;
bytes32 public constant UINT_REFERER_CUT = "UINT_REFERER_CUT";
bytes32 public constant CONTRACT_LAND_RESOURCE = "CONTRACT_LAND_RESOURCE";
}
// Dependency file: @evolutionland/common/contracts/interfaces/ERC223ReceivingContract.sol
// pragma solidity ^0.4.23;
/*
* Contract that is working with ERC223 tokens
* https://github.com/ethereum/EIPs/issues/223
*/
/// @title ERC223ReceivingContract - Standard contract implementation for compatibility with ERC223 tokens.
contract ERC223ReceivingContract {
/// @dev Function that is called when a user or another contract wants to transfer funds.
/// @param _from Transaction initiator, analogue of msg.sender
/// @param _value Number of tokens to transfer.
/// @param _data Data containig a function signature and/or parameters
function tokenFallback(address _from, uint256 _value, bytes _data) public;
}
// Dependency file: @evolutionland/common/contracts/interfaces/TokenController.sol
// pragma solidity ^0.4.23;
/// @dev The token controller contract must implement these functions
contract TokenController {
/// @notice Called when `_owner` sends ether to the MiniMe Token contract
/// @param _owner The address that sent the ether to create tokens
/// @return True if the ether is accepted, false if it throws
function proxyPayment(address _owner, bytes4 sig, bytes data) payable public returns (bool);
/// @notice Notifies the controller about a token transfer allowing the
/// controller to react if desired
/// @param _from The origin of the transfer
/// @param _to The destination of the transfer
/// @param _amount The amount of the transfer
/// @return False if the controller does not authorize the transfer
function onTransfer(address _from, address _to, uint _amount) public returns (bool);
/// @notice Notifies the controller about an approval allowing the
/// controller to react if desired
/// @param _owner The address that calls `approve()`
/// @param _spender The spender in the `approve()` call
/// @param _amount The amount in the `approve()` call
/// @return False if the controller does not authorize the approval
function onApprove(address _owner, address _spender, uint _amount) public returns (bool);
}
// Dependency file: @evolutionland/common/contracts/interfaces/ApproveAndCallFallBack.sol
// pragma solidity ^0.4.23;
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public;
}
// Dependency file: @evolutionland/common/contracts/interfaces/ERC223.sol
// pragma solidity ^0.4.23;
contract ERC223 {
function transfer(address to, uint amount, bytes data) public returns (bool ok);
function transferFrom(address from, address to, uint256 amount, bytes data) public returns (bool ok);
event ERC223Transfer(address indexed from, address indexed to, uint amount, bytes data);
}
// Dependency file: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
// pragma solidity ^0.4.24;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// Dependency file: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
// pragma solidity ^0.4.24;
// import "openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol";
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address _owner, address _spender)
public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// Dependency file: openzeppelin-solidity/contracts/math/SafeMath.sol
// pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 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;
}
}
// Dependency file: @evolutionland/common/contracts/StandardERC20Base.sol
// pragma solidity ^0.4.23;
// import '/Users/echo/workspace/contract/evolutionlandorg/land/node_modules/openzeppelin-solidity/contracts/token/ERC20/ERC20.sol';
// import "openzeppelin-solidity/contracts/math/SafeMath.sol";
contract StandardERC20Base is ERC20 {
using SafeMath for uint256;
uint256 _supply;
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) _approvals;
function totalSupply() public view returns (uint) {
return _supply;
}
function balanceOf(address src) public view returns (uint) {
return _balances[src];
}
function allowance(address src, address guy) public view returns (uint) {
return _approvals[src][guy];
}
function transfer(address dst, uint wad) public returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(address src, address dst, uint wad)
public
returns (bool)
{
if (src != msg.sender) {
_approvals[src][msg.sender] = _approvals[src][msg.sender].sub(wad);
}
_balances[src] = _balances[src].sub(wad);
_balances[dst] = _balances[dst].add(wad);
emit Transfer(src, dst, wad);
return true;
}
function approve(address guy, uint wad) public returns (bool) {
_approvals[msg.sender][guy] = wad;
emit Approval(msg.sender, guy, wad);
return true;
}
}
// Dependency file: @evolutionland/common/contracts/StandardERC223.sol
// pragma solidity ^0.4.24;
// import '/Users/echo/workspace/contract/evolutionlandorg/land/node_modules/@evolutionland/common/contracts/interfaces/ERC223ReceivingContract.sol';
// import '/Users/echo/workspace/contract/evolutionlandorg/land/node_modules/@evolutionland/common/contracts/interfaces/TokenController.sol';
// import '/Users/echo/workspace/contract/evolutionlandorg/land/node_modules/@evolutionland/common/contracts/interfaces/ApproveAndCallFallBack.sol';
// import '/Users/echo/workspace/contract/evolutionlandorg/land/node_modules/@evolutionland/common/contracts/interfaces/ERC223.sol';
// import '/Users/echo/workspace/contract/evolutionlandorg/land/node_modules/@evolutionland/common/contracts/StandardERC20Base.sol';
// import '/Users/echo/workspace/contract/evolutionlandorg/land/node_modules/@evolutionland/common/contracts/DSAuth.sol';
// This is a contract for demo and test.
contract StandardERC223 is StandardERC20Base, DSAuth, ERC223 {
event Burn(address indexed burner, uint256 value);
event Mint(address indexed to, uint256 amount);
bytes32 public symbol;
uint256 public decimals = 18; // standard token precision. override to customize
// Optional token name
bytes32 public name = "";
address public controller;
constructor(bytes32 _symbol) public {
symbol = _symbol;
controller = msg.sender;
}
function setName(bytes32 name_) public auth {
name = name_;
}
//////////
// Controller Methods
//////////
/// @notice Changes the controller of the contract
/// @param _newController The new controller of the contract
function changeController(address _newController) public auth {
controller = _newController;
}
/// @notice Send `_amount` tokens to `_to` from `_from` on the condition it
/// is approved by `_from`
/// @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
function transferFrom(address _from, address _to, uint256 _amount
) public returns (bool success) {
// Alerts the token controller of the transfer
if (isContract(controller)) {
if (!TokenController(controller).onTransfer(_from, _to, _amount))
revert();
}
success = super.transferFrom(_from, _to, _amount);
}
/*
* ERC 223
* Added support for the ERC 223 "tokenFallback" method in a "transfer" function with a payload.
*/
function transferFrom(address _from, address _to, uint256 _amount, bytes _data)
public
returns (bool success)
{
// Alerts the token controller of the transfer
if (isContract(controller)) {
if (!TokenController(controller).onTransfer(_from, _to, _amount))
revert();
}
require(super.transferFrom(_from, _to, _amount));
if (isContract(_to)) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(_from, _amount, _data);
}
emit ERC223Transfer(_from, _to, _amount, _data);
return true;
}
function issue(address _to, uint256 _amount) public auth {
mint(_to, _amount);
}
function destroy(address _from, uint256 _amount) public auth {
burn(_from, _amount);
}
function mint(address _to, uint _amount) public auth {
_supply = _supply.add(_amount);
_balances[_to] = _balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
}
function burn(address _who, uint _value) public auth {
require(_value <= _balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
_balances[_who] = _balances[_who].sub(_value);
_supply = _supply.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
/*
* ERC 223
* Added support for the ERC 223 "tokenFallback" method in a "transfer" function with a payload.
* https://github.com/ethereum/EIPs/issues/223
* function transfer(address _to, uint256 _value, bytes _data) public returns (bool success);
*/
/// @notice Send `_value` tokens to `_to` from `msg.sender` and trigger
/// tokenFallback if sender is a contract.
/// @dev Function that is called when a user or another contract wants to transfer funds.
/// @param _to Address of token receiver.
/// @param _amount Number of tokens to transfer.
/// @param _data Data to be sent to tokenFallback
/// @return Returns success of function call.
function transfer(
address _to,
uint256 _amount,
bytes _data)
public
returns (bool success)
{
return transferFrom(msg.sender, _to, _amount, _data);
}
/// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on
/// its behalf. This is a modified version of the ERC20 approve function
/// to be a little bit safer
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the approval was successful
function approve(address _spender, uint256 _amount) public returns (bool success) {
// Alerts the token controller of the approve function call
if (isContract(controller)) {
if (!TokenController(controller).onApprove(msg.sender, _spender, _amount))
revert();
}
return super.approve(_spender, _amount);
}
/// @notice `msg.sender` approves `_spender` to send `_amount` tokens on
/// its behalf, and then a function is triggered in the contract that is
/// being approved, `_spender`. This allows users to use their tokens to
/// interact with contracts in one function call instead of two
/// @param _spender The address of the contract able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the function call was successful
function approveAndCall(address _spender, uint256 _amount, bytes _extraData
) public returns (bool success) {
if (!approve(_spender, _amount)) revert();
ApproveAndCallFallBack(_spender).receiveApproval(
msg.sender,
_amount,
this,
_extraData
);
return true;
}
/// @dev Internal function to determine if an address is a contract
/// @param _addr The address being queried
/// @return True if `_addr` is a contract
function isContract(address _addr) constant internal returns(bool) {
uint size;
if (_addr == 0) return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
/// @notice The fallback function: If the contract's controller has not been
/// set to 0, then the `proxyPayment` method is called which relays the
/// ether and creates tokens as described in the token controller contract
function () public payable {
if (isContract(controller)) {
if (! TokenController(controller).proxyPayment.value(msg.value)(msg.sender, msg.sig, msg.data))
revert();
} else {
revert();
}
}
//////////
// Safety Methods
//////////
/// @notice This method can be used by the owner to extract mistakenly
/// sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
function claimTokens(address _token) public auth {
if (_token == 0x0) {
address(msg.sender).transfer(address(this).balance);
return;
}
ERC20 token = ERC20(_token);
uint balance = token.balanceOf(this);
token.transfer(address(msg.sender), balance);
emit ClaimedTokens(_token, address(msg.sender), balance);
}
////////////////
// Events
////////////////
event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount);
}
// Dependency file: openzeppelin-solidity/contracts/introspection/ERC165.sol
// pragma solidity ^0.4.24;
/**
* @title ERC165
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
*/
interface ERC165 {
/**
* @notice Query if a contract implements an interface
* @param _interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool);
}
// Dependency file: openzeppelin-solidity/contracts/token/ERC721/ERC721Basic.sol
// pragma solidity ^0.4.24;
// import "openzeppelin-solidity/contracts/introspection/ERC165.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Basic is ERC165 {
bytes4 internal constant InterfaceId_ERC721 = 0x80ac58cd;
/*
* 0x80ac58cd ===
* bytes4(keccak256('balanceOf(address)')) ^
* bytes4(keccak256('ownerOf(uint256)')) ^
* bytes4(keccak256('approve(address,uint256)')) ^
* bytes4(keccak256('getApproved(uint256)')) ^
* bytes4(keccak256('setApprovalForAll(address,bool)')) ^
* bytes4(keccak256('isApprovedForAll(address,address)')) ^
* bytes4(keccak256('transferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
*/
bytes4 internal constant InterfaceId_ERC721Exists = 0x4f558e79;
/*
* 0x4f558e79 ===
* bytes4(keccak256('exists(uint256)'))
*/
bytes4 internal constant InterfaceId_ERC721Enumerable = 0x780e9d63;
/**
* 0x780e9d63 ===
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
bytes4 internal constant InterfaceId_ERC721Metadata = 0x5b5e139f;
/**
* 0x5b5e139f ===
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
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
);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function exists(uint256 _tokenId) public view returns (bool _exists);
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 transferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId)
public;
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public;
}
// Dependency file: openzeppelin-solidity/contracts/token/ERC721/ERC721.sol
// pragma solidity ^0.4.24;
// import "openzeppelin-solidity/contracts/token/ERC721/ERC721Basic.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Enumerable is ERC721Basic {
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);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Metadata is ERC721Basic {
function name() external view returns (string _name);
function symbol() external view returns (string _symbol);
function tokenURI(uint256 _tokenId) public view returns (string);
}
/**
* @title ERC-721 Non-Fungible Token Standard, full implementation interface
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata {
}
// Dependency file: openzeppelin-solidity/contracts/token/ERC721/ERC721Receiver.sol
// pragma solidity ^0.4.24;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract ERC721Receiver {
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 internal constant ERC721_RECEIVED = 0x150b7a02;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. Return of other than the magic value MUST result in the
* transaction being reverted.
* Note: the 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(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes _data
)
public
returns(bytes4);
}
// Dependency file: openzeppelin-solidity/contracts/AddressUtils.sol
// pragma solidity ^0.4.24;
/**
* 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;
}
}
// Dependency file: openzeppelin-solidity/contracts/introspection/SupportsInterfaceWithLookup.sol
// pragma solidity ^0.4.24;
// import "openzeppelin-solidity/contracts/introspection/ERC165.sol";
/**
* @title SupportsInterfaceWithLookup
* @author Matt Condon (@shrugs)
* @dev Implements ERC165 using a lookup table.
*/
contract SupportsInterfaceWithLookup is ERC165 {
bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7;
/**
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) internal supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor()
public
{
_registerInterface(InterfaceId_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool)
{
return supportedInterfaces[_interfaceId];
}
/**
* @dev private method for registering an interface
*/
function _registerInterface(bytes4 _interfaceId)
internal
{
require(_interfaceId != 0xffffffff);
supportedInterfaces[_interfaceId] = true;
}
}
// Dependency file: openzeppelin-solidity/contracts/token/ERC721/ERC721BasicToken.sol
// pragma solidity ^0.4.24;
// import "openzeppelin-solidity/contracts/token/ERC721/ERC721Basic.sol";
// import "openzeppelin-solidity/contracts/token/ERC721/ERC721Receiver.sol";
// import "openzeppelin-solidity/contracts/math/SafeMath.sol";
// import "openzeppelin-solidity/contracts/AddressUtils.sol";
// import "openzeppelin-solidity/contracts/introspection/SupportsInterfaceWithLookup.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721BasicToken is SupportsInterfaceWithLookup, ERC721Basic {
using SafeMath for uint256;
using AddressUtils for address;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
bytes4 private constant ERC721_RECEIVED = 0x150b7a02;
// Mapping from token ID to owner
mapping (uint256 => address) internal tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) internal tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => uint256) internal ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) internal operatorApprovals;
constructor()
public
{
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(InterfaceId_ERC721);
_registerInterface(InterfaceId_ERC721Exists);
}
/**
* @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));
return ownedTokensCount[_owner];
}
/**
* @dev Gets the owner of the specified token ID
* @param _tokenId uint256 ID of the token to query the owner of
* @return owner 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));
return owner;
}
/**
* @dev Returns whether the specified token exists
* @param _tokenId uint256 ID of the token to query the existence of
* @return whether the token exists
*/
function exists(uint256 _tokenId) public view returns (bool) {
address owner = tokenOwner[_tokenId];
return owner != address(0);
}
/**
* @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);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
tokenApprovals[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* @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) {
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 != msg.sender);
operatorApprovals[msg.sender][_to] = _approved;
emit ApprovalForAll(msg.sender, _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
{
require(isApprovedOrOwner(msg.sender, _tokenId));
require(_from != address(0));
require(_to != address(0));
clearApproval(_from, _tokenId);
removeTokenFrom(_from, _tokenId);
addTokenTo(_to, _tokenId);
emit Transfer(_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 `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
{
// solium-disable-next-line arg-overflow
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 `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 _data
)
public
{
transferFrom(_from, _to, _tokenId);
// solium-disable-next-line arg-overflow
require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
/**
* @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)
{
address owner = ownerOf(_tokenId);
// Disable solium check because of
// https://github.com/duaraghav8/Solium/issues/175
// solium-disable-next-line operator-whitespace
return (
_spender == owner ||
getApproved(_tokenId) == _spender ||
isApprovedForAll(owner, _spender)
);
}
/**
* @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 by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
require(_to != address(0));
addTokenTo(_to, _tokenId);
emit Transfer(address(0), _to, _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 by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
clearApproval(_owner, _tokenId);
removeTokenFrom(_owner, _tokenId);
emit Transfer(_owner, address(0), _tokenId);
}
/**
* @dev Internal function to clear current approval of a given token ID
* Reverts if the given address is not indeed the owner of the token
* @param _owner owner of the token
* @param _tokenId uint256 ID of the token to be transferred
*/
function clearApproval(address _owner, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _owner);
if (tokenApprovals[_tokenId] != address(0)) {
tokenApprovals[_tokenId] = address(0);
}
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @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 addTokenTo(address _to, uint256 _tokenId) internal {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
ownedTokensCount[_to] = ownedTokensCount[_to].add(1);
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @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 removeTokenFrom(address _from, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _from);
ownedTokensCount[_from] = ownedTokensCount[_from].sub(1);
tokenOwner[_tokenId] = address(0);
}
/**
* @dev Internal function to invoke `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 whether the call correctly returned the expected magic value
*/
function checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
internal
returns (bool)
{
if (!_to.isContract()) {
return true;
}
bytes4 retval = ERC721Receiver(_to).onERC721Received(
msg.sender, _from, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
}
// Dependency file: openzeppelin-solidity/contracts/token/ERC721/ERC721Token.sol
// pragma solidity ^0.4.24;
// import "openzeppelin-solidity/contracts/token/ERC721/ERC721.sol";
// import "openzeppelin-solidity/contracts/token/ERC721/ERC721BasicToken.sol";
// import "openzeppelin-solidity/contracts/introspection/SupportsInterfaceWithLookup.sol";
/**
* @title Full ERC721 Token
* This implementation includes all the required and some optional functionality of the ERC721 standard
* Moreover, it includes approve all functionality using operator terminology
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Token is SupportsInterfaceWithLookup, ERC721BasicToken, ERC721 {
// Token name
string internal name_;
// Token symbol
string internal symbol_;
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) internal ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) internal ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] internal allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) internal allTokensIndex;
// Optional mapping for token URIs
mapping(uint256 => string) internal tokenURIs;
/**
* @dev Constructor function
*/
constructor(string _name, string _symbol) public {
name_ = _name;
symbol_ = _symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(InterfaceId_ERC721Enumerable);
_registerInterface(InterfaceId_ERC721Metadata);
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() external view returns (string) {
return name_;
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() external view returns (string) {
return symbol_;
}
/**
* @dev Returns an URI for a given token ID
* Throws if the token ID does not exist. May return an empty string.
* @param _tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 _tokenId) public view returns (string) {
require(exists(_tokenId));
return tokenURIs[_tokenId];
}
/**
* @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));
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());
return allTokens[_index];
}
/**
* @dev Internal function to set the token URI for a given token
* Reverts if the token ID does not exist
* @param _tokenId uint256 ID of the token to set its URI
* @param _uri string URI to assign
*/
function _setTokenURI(uint256 _tokenId, string _uri) internal {
require(exists(_tokenId));
tokenURIs[_tokenId] = _uri;
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @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 addTokenTo(address _to, uint256 _tokenId) internal {
super.addTokenTo(_to, _tokenId);
uint256 length = ownedTokens[_to].length;
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @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 removeTokenFrom(address _from, uint256 _tokenId) internal {
super.removeTokenFrom(_from, _tokenId);
// To prevent a gap in the array, we store the last token in the index of the token to delete, and
// then delete the last slot.
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = ownedTokens[_from].length.sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
ownedTokens[_from][tokenIndex] = lastToken;
// This also deletes the contents at the last position of the array
ownedTokens[_from].length--;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to
// be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping
// the lastToken to the first position, and then dropping the element placed in the last position of the list
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
}
/**
* @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 by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
super._mint(_to, _tokenId);
allTokensIndex[_tokenId] = allTokens.length;
allTokens.push(_tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param _owner owner of the token to burn
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
super._burn(_owner, _tokenId);
// Clear metadata (if any)
if (bytes(tokenURIs[_tokenId]).length != 0) {
delete tokenURIs[_tokenId];
}
// Reorg all tokens array
uint256 tokenIndex = allTokensIndex[_tokenId];
uint256 lastTokenIndex = allTokens.length.sub(1);
uint256 lastToken = allTokens[lastTokenIndex];
allTokens[tokenIndex] = lastToken;
allTokens[lastTokenIndex] = 0;
allTokens.length--;
allTokensIndex[_tokenId] = 0;
allTokensIndex[lastToken] = tokenIndex;
}
}
// Dependency file: @evolutionland/common/contracts/ObjectOwnership.sol
// pragma solidity ^0.4.24;
// import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
// import "openzeppelin-solidity/contracts/token/ERC721/ERC721Token.sol";
// import "@evolutionland/common/contracts/interfaces/IInterstellarEncoder.sol";
// import "@evolutionland/common/contracts/interfaces/ISettingsRegistry.sol";
// import "@evolutionland/common/contracts/DSAuth.sol";
// import "@evolutionland/common/contracts/SettingIds.sol";
contract ObjectOwnership is ERC721Token("Evolution Land Objects","EVO"), DSAuth, SettingIds {
ISettingsRegistry public registry;
bool private singletonLock = false;
/*
* Modifiers
*/
modifier singletonLockCall() {
require(!singletonLock, "Only can call once");
_;
singletonLock = true;
}
/**
* @dev Atlantis's constructor
*/
constructor () public {
// initializeContract();
}
/**
* @dev Same with constructor, but is used and called by storage proxy as logic contract.
*/
function initializeContract(address _registry) public singletonLockCall {
// Ownable constructor
owner = msg.sender;
emit LogSetOwner(msg.sender);
// SupportsInterfaceWithLookup constructor
_registerInterface(InterfaceId_ERC165);
// ERC721BasicToken constructor
_registerInterface(InterfaceId_ERC721);
_registerInterface(InterfaceId_ERC721Exists);
// ERC721Token constructor
name_ = "Evolution Land Objects";
symbol_ = "EVO"; // Evolution Land Objects
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(InterfaceId_ERC721Enumerable);
_registerInterface(InterfaceId_ERC721Metadata);
registry = ISettingsRegistry(_registry);
}
function mintObject(address _to, uint128 _objectId) public auth returns (uint256 _tokenId) {
address interstellarEncoder = registry.addressOf(CONTRACT_INTERSTELLAR_ENCODER);
_tokenId = IInterstellarEncoder(interstellarEncoder).encodeTokenIdForObjectContract(
address(this), msg.sender, _objectId);
super._mint(_to, _tokenId);
}
function burnObject(address _to, uint128 _objectId) public auth returns (uint256 _tokenId) {
address interstellarEncoder = registry.addressOf(CONTRACT_INTERSTELLAR_ENCODER);
_tokenId = IInterstellarEncoder(interstellarEncoder).encodeTokenIdForObjectContract(
address(this), msg.sender, _objectId);
super._burn(_to, _tokenId);
}
function mint(address _to, uint256 _tokenId) public auth {
super._mint(_to, _tokenId);
}
function burn(address _to, uint256 _tokenId) public auth {
super._burn(_to, _tokenId);
}
//@dev user invoke approveAndCall to create auction
//@param _to - address of auction contractß
function approveAndCall(
address _to,
uint _tokenId,
bytes _extraData
) public {
// set _to to the auction contract
approve(_to, _tokenId);
if(!_to.call(
bytes4(keccak256("receiveApproval(address,uint256,bytes)")), abi.encode(msg.sender, _tokenId, _extraData)
)) {
revert();
}
}
}
// Dependency file: @evolutionland/upgraeability-using-unstructured-storage/contracts/Proxy.sol
// pragma solidity ^0.4.21;
/**
* @title Proxy
* @dev Gives the possibility to delegate any call to a foreign implementation.
*/
contract Proxy {
/**
* @dev Tells the address of the implementation where every call will be delegated.
* @return address of the implementation to which it will be delegated
*/
function implementation() public view returns (address);
/**
* @dev Fallback function allowing to perform a delegatecall to the given implementation.
* This function will return whatever the implementation call returns
*/
function () payable public {
address _impl = implementation();
require(_impl != address(0));
assembly {
let ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize)
let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0)
let size := returndatasize
returndatacopy(ptr, 0, size)
switch result
case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
}
// Dependency file: @evolutionland/upgraeability-using-unstructured-storage/contracts/UpgradeabilityProxy.sol
// pragma solidity ^0.4.21;
// import '/Users/echo/workspace/contract/evolutionlandorg/land/node_modules/@evolutionland/upgraeability-using-unstructured-storage/contracts/Proxy.sol';
/**
* @title UpgradeabilityProxy
* @dev This contract represents a proxy where the implementation address to which it will delegate can be upgraded
*/
contract UpgradeabilityProxy is Proxy {
/**
* @dev This event will be emitted every time the implementation gets upgraded
* @param implementation representing the address of the upgraded implementation
*/
event Upgraded(address indexed implementation);
// Storage position of the address of the current implementation
bytes32 private constant implementationPosition = keccak256("org.zeppelinos.proxy.implementation");
/**
* @dev Constructor function
*/
function UpgradeabilityProxy() public {}
/**
* @dev Tells the address of the current implementation
* @return address of the current implementation
*/
function implementation() public view returns (address impl) {
bytes32 position = implementationPosition;
assembly {
impl := sload(position)
}
}
/**
* @dev Sets the address of the current implementation
* @param newImplementation address representing the new implementation to be set
*/
function setImplementation(address newImplementation) internal {
bytes32 position = implementationPosition;
assembly {
sstore(position, newImplementation)
}
}
/**
* @dev Upgrades the implementation address
* @param newImplementation representing the address of the new implementation to be set
*/
function _upgradeTo(address newImplementation) internal {
address currentImplementation = implementation();
require(currentImplementation != newImplementation);
setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
}
// Dependency file: @evolutionland/upgraeability-using-unstructured-storage/contracts/OwnedUpgradeabilityProxy.sol
// pragma solidity ^0.4.21;
// import '/Users/echo/workspace/contract/evolutionlandorg/land/node_modules/@evolutionland/upgraeability-using-unstructured-storage/contracts/UpgradeabilityProxy.sol';
/**
* @title OwnedUpgradeabilityProxy
* @dev This contract combines an upgradeability proxy with basic authorization control functionalities
*/
contract OwnedUpgradeabilityProxy is UpgradeabilityProxy {
/**
* @dev Event to show ownership has been transferred
* @param previousOwner representing the address of the previous owner
* @param newOwner representing the address of the new owner
*/
event ProxyOwnershipTransferred(address previousOwner, address newOwner);
// Storage position of the owner of the contract
bytes32 private constant proxyOwnerPosition = keccak256("org.zeppelinos.proxy.owner");
/**
* @dev the constructor sets the original owner of the contract to the sender account.
*/
function OwnedUpgradeabilityProxy() public {
setUpgradeabilityOwner(msg.sender);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyProxyOwner() {
require(msg.sender == proxyOwner());
_;
}
/**
* @dev Tells the address of the owner
* @return the address of the owner
*/
function proxyOwner() public view returns (address owner) {
bytes32 position = proxyOwnerPosition;
assembly {
owner := sload(position)
}
}
/**
* @dev Sets the address of the owner
*/
function setUpgradeabilityOwner(address newProxyOwner) internal {
bytes32 position = proxyOwnerPosition;
assembly {
sstore(position, newProxyOwner)
}
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferProxyOwnership(address newOwner) public onlyProxyOwner {
require(newOwner != address(0));
emit ProxyOwnershipTransferred(proxyOwner(), newOwner);
setUpgradeabilityOwner(newOwner);
}
/**
* @dev Allows the proxy owner to upgrade the current version of the proxy.
* @param implementation representing the address of the new implementation to be set.
*/
function upgradeTo(address implementation) public onlyProxyOwner {
_upgradeTo(implementation);
}
/**
* @dev Allows the proxy owner to upgrade the current version of the proxy and call the new implementation
* to initialize whatever is needed through a low level call.
* @param implementation representing the address of the new implementation to be set.
* @param data represents the msg.data to bet sent in the low level call. This parameter may include the function
* signature of the implementation to be called with the needed payload
*/
function upgradeToAndCall(address implementation, bytes data) payable public onlyProxyOwner {
upgradeTo(implementation);
require(this.call.value(msg.value)(data));
}
}
// Dependency file: @evolutionland/common/contracts/interfaces/ITokenLocation.sol
// pragma solidity ^0.4.24;
contract ITokenLocation {
function hasLocation(uint256 _tokenId) public view returns (bool);
function getTokenLocation(uint256 _tokenId) public view returns (int, int);
function setTokenLocation(uint256 _tokenId, int _x, int _y) public;
function getTokenLocationHM(uint256 _tokenId) public view returns (int, int);
function setTokenLocationHM(uint256 _tokenId, int _x, int _y) public;
}
// Dependency file: @evolutionland/common/contracts/LocationCoder.sol
// pragma solidity ^0.4.24;
library LocationCoder {
// the allocation of the [x, y, z] is [0<1>, x<21>, y<21>, z<21>]
uint256 constant CLEAR_YZ = 0x0fffffffffffffffffffff000000000000000000000000000000000000000000;
uint256 constant CLEAR_XZ = 0x0000000000000000000000fffffffffffffffffffff000000000000000000000;
uint256 constant CLEAR_XY = 0x0000000000000000000000000000000000000000000fffffffffffffffffffff;
uint256 constant NOT_ZERO = 0x1000000000000000000000000000000000000000000000000000000000000000;
uint256 constant APPEND_HIGH = 0xfffffffffffffffffffffffffffffffffffffffffff000000000000000000000;
uint256 constant MAX_LOCATION_ID = 0x2000000000000000000000000000000000000000000000000000000000000000;
int256 constant HMETER_DECIMAL = 10 ** 8;
// x, y, z should between -2^83 (-9671406556917033397649408) and 2^83 - 1 (9671406556917033397649407).
int256 constant MIN_Location_XYZ = -9671406556917033397649408;
int256 constant MAX_Location_XYZ = 9671406556917033397649407;
// 96714065569170334.50000000
int256 constant MAX_HM_DECIMAL = 9671406556917033450000000;
int256 constant MAX_HM = 96714065569170334;
function encodeLocationIdXY(int _x, int _y) internal pure returns (uint result) {
return encodeLocationId3D(_x, _y, 0);
}
function decodeLocationIdXY(uint _positionId) internal pure returns (int _x, int _y) {
(_x, _y, ) = decodeLocationId3D(_positionId);
}
function encodeLocationId3D(int _x, int _y, int _z) internal pure returns (uint result) {
return _unsafeEncodeLocationId3D(_x, _y, _z);
}
function _unsafeEncodeLocationId3D(int _x, int _y, int _z) internal pure returns (uint) {
require(_x >= MIN_Location_XYZ && _x <= MAX_Location_XYZ, "Invalid value.");
require(_y >= MIN_Location_XYZ && _y <= MAX_Location_XYZ, "Invalid value.");
require(_z >= MIN_Location_XYZ && _z <= MAX_Location_XYZ, "Invalid value.");
// uint256 constant FACTOR_2 = 0x1000000000000000000000000000000000000000000; // <16 ** 42> or <2 ** 168>
// uint256 constant FACTOR = 0x1000000000000000000000; // <16 ** 21> or <2 ** 84>
return ((uint(_x) << 168) & CLEAR_YZ) | (uint(_y << 84) & CLEAR_XZ) | (uint(_z) & CLEAR_XY) | NOT_ZERO;
}
function decodeLocationId3D(uint _positionId) internal pure returns (int, int, int) {
return _unsafeDecodeLocationId3D(_positionId);
}
function _unsafeDecodeLocationId3D(uint _value) internal pure returns (int x, int y, int z) {
require(_value >= NOT_ZERO && _value < MAX_LOCATION_ID, "Invalid Location Id");
x = expandNegative84BitCast((_value & CLEAR_YZ) >> 168);
y = expandNegative84BitCast((_value & CLEAR_XZ) >> 84);
z = expandNegative84BitCast(_value & CLEAR_XY);
}
function toHM(int _x) internal pure returns (int) {
return (_x + MAX_HM_DECIMAL)/HMETER_DECIMAL - MAX_HM;
}
function toUM(int _x) internal pure returns (int) {
return _x * LocationCoder.HMETER_DECIMAL;
}
function expandNegative84BitCast(uint _value) internal pure returns (int) {
if (_value & (1<<83) != 0) {
return int(_value | APPEND_HIGH);
}
return int(_value);
}
function encodeLocationIdHM(int _x, int _y) internal pure returns (uint result) {
return encodeLocationIdXY(toUM(_x), toUM(_y));
}
function decodeLocationIdHM(uint _positionId) internal pure returns (int, int) {
(int _x, int _y) = decodeLocationIdXY(_positionId);
return (toHM(_x), toHM(_y));
}
}
// Dependency file: @evolutionland/common/contracts/TokenLocation.sol
// pragma solidity ^0.4.24;
// import "@evolutionland/common/contracts/interfaces/ITokenLocation.sol";
// import "@evolutionland/common/contracts/DSAuth.sol";
// import "@evolutionland/common/contracts/LocationCoder.sol";
contract TokenLocation is DSAuth, ITokenLocation {
using LocationCoder for *;
bool private singletonLock = false;
// token id => encode(x,y) postiion in map, the location is in micron.
mapping (uint256 => uint256) public tokenId2LocationId;
/*
* Modifiers
*/
modifier singletonLockCall() {
require(!singletonLock, "Only can call once");
_;
singletonLock = true;
}
function initializeContract() public singletonLockCall {
owner = msg.sender;
emit LogSetOwner(msg.sender);
}
function hasLocation(uint256 _tokenId) public view returns (bool) {
return tokenId2LocationId[_tokenId] != 0;
}
function getTokenLocationHM(uint256 _tokenId) public view returns (int, int){
(int _x, int _y) = getTokenLocation(_tokenId);
return (LocationCoder.toHM(_x), LocationCoder.toHM(_y));
}
function setTokenLocationHM(uint256 _tokenId, int _x, int _y) public auth {
setTokenLocation(_tokenId, LocationCoder.toUM(_x), LocationCoder.toUM(_y));
}
// decode tokenId to get (x,y)
function getTokenLocation(uint256 _tokenId) public view returns (int, int) {
uint locationId = tokenId2LocationId[_tokenId];
return LocationCoder.decodeLocationIdXY(locationId);
}
function setTokenLocation(uint256 _tokenId, int _x, int _y) public auth {
tokenId2LocationId[_tokenId] = LocationCoder.encodeLocationIdXY(_x, _y);
}
}
// Dependency file: @evolutionland/common/contracts/ObjectOwnershipAuthority.sol
// pragma solidity ^0.4.24;
contract ObjectOwnershipAuthority {
mapping (address => bool) public whiteList;
constructor(address[] _whitelists) public {
for (uint i = 0; i < _whitelists.length; i ++) {
whiteList[_whitelists[i]] = true;
}
}
function canCall(
address _src, address _dst, bytes4 _sig
) public view returns (bool) {
return ( whiteList[_src] && _sig == bytes4(keccak256("mintObject(address,uint128)")) ) ||
( whiteList[_src] && _sig == bytes4(keccak256("burnObject(address,uint128)")) );
}
}
// Dependency file: @evolutionland/common/contracts/TokenLocationAuthority.sol
// pragma solidity ^0.4.24;
contract TokenLocationAuthority {
mapping (address => bool) public whiteList;
constructor(address[] _whitelists) public {
for (uint i = 0; i < _whitelists.length; i ++) {
whiteList[_whitelists[i]] = true;
}
}
function canCall(
address _src, address _dst, bytes4 _sig
) public view returns (bool) {
return ( whiteList[_src] && _sig == bytes4(keccak256("setTokenLocationHM(uint256,int256,int256)"))) ;
}
}
// Root file: contracts/DeployAndTest.sol
pragma solidity ^0.4.23;
// import '/Users/echo/workspace/contract/evolutionlandorg/land/node_modules/@evolutionland/common/contracts/InterstellarEncoder.sol';
// import '/Users/echo/workspace/contract/evolutionlandorg/land/node_modules/@evolutionland/common/contracts/SettingsRegistry.sol';
// import '/Users/echo/workspace/contract/evolutionlandorg/land/node_modules/@evolutionland/common/contracts/SettingIds.sol';
// import '/Users/echo/workspace/contract/evolutionlandorg/land/node_modules/@evolutionland/common/contracts/StandardERC223.sol';
// import '/Users/echo/workspace/contract/evolutionlandorg/land/node_modules/@evolutionland/common/contracts/ObjectOwnership.sol';
// import "@evolutionland/upgraeability-using-unstructured-storage/contracts/OwnedUpgradeabilityProxy.sol";
// import "@evolutionland/common/contracts/TokenLocation.sol";
// import '/Users/echo/workspace/contract/evolutionlandorg/land/node_modules/@evolutionland/common/contracts/ObjectOwnershipAuthority.sol';
// import "@evolutionland/common/contracts/TokenLocationAuthority.sol";
contract DeployAndTest {
}
|
the constructor sets the original owner of the contract to the sender account./
|
function OwnedUpgradeabilityProxy() public {
setUpgradeabilityOwner(msg.sender);
}
| 1,005,299
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol";
import "@manifoldxyz/libraries-solidity/contracts/access/AdminControl.sol";
import "../../core/IERC1155CreatorCore.sol";
import "./IERC1155CreatorMintPermissions.sol";
/**
* @dev Basic implementation of a permission contract that works with a singular creator contract.
* approveMint requires the sender to be the configured creator.
*/
abstract contract ERC1155CreatorMintPermissions is ERC165, AdminControl, IERC1155CreatorMintPermissions {
address internal immutable _creator;
constructor(address creator_) {
require(ERC165Checker.supportsInterface(creator_, type(IERC1155CreatorCore).interfaceId), "Must implement IERC1155CreatorCore");
_creator = creator_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165, AdminControl) returns (bool) {
return interfaceId == type(IERC1155CreatorMintPermissions).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155CreatorMintPermissions-approve}.
*/
function approveMint(address, address[] calldata, uint256[] calldata, uint256[] calldata) public virtual override {
require(msg.sender == _creator, "Can only be called by token creator");
}
}
|
See {IERC1155CreatorMintPermissions-approve}./
|
function approveMint(address, address[] calldata, uint256[] calldata, uint256[] calldata) public virtual override {
require(msg.sender == _creator, "Can only be called by token creator");
}
| 2,519,831
|
pragma solidity ^0.4.24;
import "./IERC20.sol";
import "../math/SafeMath.sol";
/**
* @title Standard ERC20 token.
* @dev Implementation of the basic standard token.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @return Total number of tokens in existence.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the given address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Transfers tokens for the 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 Transfers tokens from one address to another.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value The amount of tokens to be transferred.
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
/**
* @dev Approves 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) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Checks 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 An 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 Increases the amount of tokens that an owner allowed to a spender.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = (_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decreases the amount of tokens that an owner allowed to a spender.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = (_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfers tokens for a specified address.
* @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(value <= _balances[from]);
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Mints an amount of the token and assigns it to an account.
* @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 != 0);
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
}
|
Transfers tokens from one address to another. from address The address which you want to send tokens from to address The address which you want to transfer to value The amount of tokens to be transferred./
|
function transferFrom(address from, address to, uint256 value) public returns (bool) {
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
| 7,229,008
|
./full_match/420/0x9c57DDCbD3359Db43f155C674aC36eC5EFe143C4/sources/contracts/SportMarkets/SportsAMM.sol
|
setters Setting all key parameters for AMM _minimalTimeLeftToMaturity The time period in seconds. _minSpread Minimum spread percentage expressed in ether unit (uses 18 decimals -> 1% = 0.011e18) _maxSpread Maximum spread percentage expressed in ether unit (uses 18 decimals -> 1% = 0.011e18) _minSupportedOdds Minimal oracle odd in ether unit (18 decimals) _maxSupportedOdds Maximum oracle odds in ether unit (18 decimals) _defaultCapPerGame Default sUSD cap per market (18 decimals) _safeBoxImpact Percentage expressed in ether unit (uses 18 decimals -> 1% = 0.011e18) _referrerFee how much of a fee to pay to referrers
|
function setParameters(
uint _minimalTimeLeftToMaturity,
uint _minSpread,
uint _maxSpread,
uint _minSupportedOdds,
uint _maxSupportedOdds,
uint _defaultCapPerGame,
uint _safeBoxImpact,
uint _referrerFee,
uint _threshold
) external onlyOwner {
minimalTimeLeftToMaturity = _minimalTimeLeftToMaturity;
min_spread = _minSpread;
max_spread = _maxSpread;
minSupportedOdds = _minSupportedOdds;
maxSupportedOdds = _maxSupportedOdds;
defaultCapPerGame = _defaultCapPerGame;
safeBoxImpact = _safeBoxImpact;
referrerFee = _referrerFee;
thresholdForOddsUpdate = _threshold;
emit ParametersUpdated(
_minimalTimeLeftToMaturity,
_minSpread,
_maxSpread,
_minSupportedOdds,
_maxSupportedOdds,
_defaultCapPerGame,
_safeBoxImpact,
_referrerFee,
_threshold
);
}
| 13,228,223
|
./full_match/80001/0xe1065F5eD9d0C1C57b0036332Cd06FEDc5F962D8/sources/contracts/WrappedERC20.sol
|
Returns number of decimals of the token return The number of decimals of the token
|
function decimals() public view override(ERC20Upgradeable, IWrappedERC20) returns(uint8) {
return _decimals;
}
| 5,638,534
|
./full_match/5/0xe0C569c7b48ffF6e2a0ee8C76895cf031836bAE7/sources/contracts/digicrowd.sol
|
Contract transfers the funds to fundraiser
|
function donateToCampaign(
address _from,
uint256 _id,
uint256 _amount
) public payable {
Campaign storage campaign = campaigns[_id];
require(baseContract.balance >= _amount, "Transaction failed 106!!!");
require(sent, "Transaction failed 110!!!");
campaign.amountCollected = campaign.amountCollected + _amount;
campaign.donators.push(_from);
campaign.donations.push(_amount);
}
| 1,915,331
|
// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
//
// Trust math, not hardware.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.5;
import "./interfaces/IRiskManagerV1.sol";
import "./RiskManagerV1.sol";
import "./CoveragePool.sol";
import "./CoveragePoolConstants.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/// @notice Interface for the Uniswap v2 router.
/// @dev This is an interface with just a few function signatures of the
/// router contract. For more info and function description please see:
/// https://uniswap.org/docs/v2/smart-contracts/router02
interface IUniswapV2Router {
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function factory() external pure returns (address);
/* solhint-disable-next-line func-name-mixedcase */
function WETH() external pure returns (address);
}
/// @notice Interface for the Uniswap v2 pair.
/// @dev This is an interface with just a few function signatures of the
/// pair contract. For more info and function description please see:
/// https://uniswap.org/docs/v2/smart-contracts/pair
interface IUniswapV2Pair {
function getReserves()
external
view
returns (
uint112 reserve0,
uint112 reserve1,
uint32 blockTimestampLast
);
}
/// @title SignerBondsUniswapV2
/// @notice ETH purchased by the risk manager from tBTC signer bonds needs to be
/// swapped and deposited back to the coverage pool as collateral.
/// SignerBondsUniswapV2 is a swap strategy implementation which
/// can withdraw the given bonds amount from the risk manager, swap them
/// on Uniswap v2 exchange and deposit as coverage pool collateral.
/// The governance can set crucial swap parameters: max allowed
/// percentage impact, slippage tolerance and swap deadline, to force
/// reasonable swap outcomes. It is up to the governance to decide what
/// these values should be.
contract SignerBondsUniswapV2 is ISignerBondsSwapStrategy, Ownable {
// One basis point is equivalent to 1/100th of a percent.
uint256 public constant BASIS_POINTS_DIVISOR = 10000;
IUniswapV2Router public immutable uniswapRouter;
IUniswapV2Pair public immutable uniswapPair;
address public immutable assetPool;
address public immutable collateralToken;
mapping(address => bool) public approvedSwappers;
// Determines the maximum allowed price impact for the swap transaction.
// If transaction's price impact is higher, transaction will be reverted.
// Default value is 100 basis points (1%).
uint256 public maxAllowedPriceImpact = 100;
// Determines the slippage tolerance for the swap transaction.
// If transaction's slippage is higher, transaction will be reverted.
// Default value is 50 basis points (0.5%).
uint256 public slippageTolerance = 50;
// Determines the deadline in which the swap transaction has to be mined.
// If that deadline is exceeded, transaction will be reverted.
uint256 public swapDeadline = 20 minutes;
// Determines if the swap should revert when open auctions exists. If true,
// swaps cannot be performed if there is at least one open auction.
// If false, open auctions are not taken into account.
bool public revertIfAuctionOpen = true;
event SignerBondsSwapperApproved(address swapper);
event SignerBondsSwapperUnapproved(address swapper);
event UniswapV2SwapExecuted(uint256[] amounts);
/// @notice Reverts if called by a signer bonds swapper that is not approved
modifier onlyApprovedSwapper() {
require(
approvedSwappers[msg.sender],
"Signer bonds swapper not approved"
);
_;
}
constructor(IUniswapV2Router _uniswapRouter, CoveragePool _coveragePool) {
uniswapRouter = _uniswapRouter;
assetPool = address(_coveragePool.assetPool());
address _collateralToken = address(_coveragePool.collateralToken());
collateralToken = _collateralToken;
uniswapPair = IUniswapV2Pair(
computePairAddress(
_uniswapRouter.factory(),
_uniswapRouter.WETH(),
_collateralToken
)
);
}
/// @notice Receive ETH upon withdrawal of risk manager's signer bonds.
/// @dev Do not send arbitrary funds. They will be locked forever.
receive() external payable {}
/// @notice Notifies the strategy about signer bonds purchase.
/// @param amount Amount of purchased signer bonds.
function onSignerBondsPurchased(uint256 amount) external override {}
/// @notice Sets the maximum price impact allowed for a swap transaction.
/// @param _maxAllowedPriceImpact Maximum allowed price impact specified
/// in basis points. Value of this parameter must be between
/// 0 and 10000 (inclusive). It should be chosen carefully as
/// high limit level will accept transactions with high volumes.
/// Those transactions may result in poor execution prices. Very low
/// limit will force low swap volumes. Limit equal to 0 will
/// effectively make swaps impossible.
function setMaxAllowedPriceImpact(uint256 _maxAllowedPriceImpact)
external
onlyOwner
{
require(
_maxAllowedPriceImpact <= BASIS_POINTS_DIVISOR,
"Maximum value is 10000 basis points"
);
maxAllowedPriceImpact = _maxAllowedPriceImpact;
}
/// @notice Sets the slippage tolerance for a swap transaction.
/// @param _slippageTolerance Slippage tolerance in basis points. Value of
/// this parameter must be between 0 and 10000 (inclusive). It
/// should be chosen carefully as transactions with high slippage
/// tolerance result in poor execution prices. On the other hand,
/// very low slippage tolerance may cause transactions to be
/// reverted frequently. Slippage tolerance equal to 0 is possible
/// and disallows any slippage to happen on the swap at the cost
/// of higher revert risk.
function setSlippageTolerance(uint256 _slippageTolerance)
external
onlyOwner
{
require(
_slippageTolerance <= BASIS_POINTS_DIVISOR,
"Maximum value is 10000 basis points"
);
slippageTolerance = _slippageTolerance;
}
/// @notice Sets the deadline for a swap transaction.
/// @param _swapDeadline Swap deadline in seconds. Value of this parameter
/// should be equal or greater than 0. It should be chosen carefully
/// as transactions with long deadlines may result in poor execution
/// prices. On the other hand, very short deadlines may cause
/// transactions to be reverted frequently, especially in a
/// gas-expensive environment. Deadline equal to 0 will effectively
// make swaps impossible.
function setSwapDeadline(uint256 _swapDeadline) external onlyOwner {
swapDeadline = _swapDeadline;
}
/// @notice Sets whether a swap should revert if at least one
/// open auction exists.
/// @param _revertIfAuctionOpen If true, revert the swap if there is at
/// least one open auction. If false, open auctions won't be taken
/// into account.
function setRevertIfAuctionOpen(bool _revertIfAuctionOpen)
external
onlyOwner
{
revertIfAuctionOpen = _revertIfAuctionOpen;
}
/// @notice Swaps signer bonds on Uniswap v2 exchange.
/// @dev Swaps the given ETH amount for the collateral token using the
/// Uniswap exchange. The maximum ETH amount is capped by the
/// contract balance. Some governance parameters are applied on the
/// transaction. The swap's price impact must fit within the
/// maximum allowed price impact and the transaction is constrained
/// with the slippage tolerance and deadline. Acquired collateral
/// tokens are sent to the asset pool address set during
/// contract construction.
/// @param riskManager Address of the risk manager which holds the bonds.
/// @param amount Amount to swap.
function swapSignerBondsOnUniswapV2(
IRiskManagerV1 riskManager,
uint256 amount
) external onlyApprovedSwapper {
require(amount > 0, "Amount must be greater than 0");
require(
amount <= address(riskManager).balance,
"Amount exceeds risk manager balance"
);
if (revertIfAuctionOpen) {
require(!riskManager.hasOpenAuctions(), "There are open auctions");
}
riskManager.withdrawSignerBonds(amount);
// Setup the swap path. WETH must be the first component.
address[] memory path = new address[](2);
path[0] = uniswapRouter.WETH();
path[1] = collateralToken;
// Calculate the maximum output token amount basing on pair reserves.
// This value will be used as the minimum amount of output tokens that
// must be received for the transaction not to revert.
// This value includes liquidity fee equal to 0.3%.
uint256 amountOutMin = uniswapRouter.getAmountsOut(amount, path)[1];
require(
isAllowedPriceImpact(amountOutMin),
"Price impact exceeds allowed limit"
);
// Include slippage tolerance into the minimum amount of output tokens.
amountOutMin =
(amountOutMin * (BASIS_POINTS_DIVISOR - slippageTolerance)) /
BASIS_POINTS_DIVISOR;
// slither-disable-next-line arbitrary-send,reentrancy-events
uint256[] memory amounts = uniswapRouter.swapExactETHForTokens{
value: amount
}(
amountOutMin,
path,
assetPool,
/* solhint-disable-next-line not-rely-on-time */
block.timestamp + swapDeadline
);
emit UniswapV2SwapExecuted(amounts);
}
/// @notice Approves the signer bonds swapper. The change takes effect
/// immediately.
/// @dev Can be called only by the contract owner.
/// @param swapper Swapper that will be approved
function approveSwapper(address swapper) external onlyOwner {
require(
!approvedSwappers[swapper],
"Signer bonds swapper has been already approved"
);
emit SignerBondsSwapperApproved(swapper);
approvedSwappers[swapper] = true;
}
/// @notice Unapproves the signer bonds swapper. The change takes effect
/// immediately.
/// @dev Can be called only by the contract owner.
/// @param swapper Swapper that will be unapproved
function unapproveSwapper(address swapper) external onlyOwner {
require(
approvedSwappers[swapper],
"Signer bonds swapper is not approved"
);
emit SignerBondsSwapperUnapproved(swapper);
delete approvedSwappers[swapper];
}
/// @notice Checks the price impact of buying a given amount of tokens
/// against the maximum allowed price impact limit.
/// @param amount Amount of tokens.
/// @return True if the price impact is allowed, false otherwise.
function isAllowedPriceImpact(uint256 amount) public view returns (bool) {
// Get reserve of the collateral token.
address WETH = uniswapRouter.WETH();
address token0 = WETH < collateralToken ? WETH : collateralToken;
(uint256 reserve0, uint256 reserve1, ) = uniswapPair.getReserves();
uint256 collateralTokenReserve = WETH == token0 ? reserve1 : reserve0;
// Same as: priceImpact <= priceImpactLimit
return
amount * BASIS_POINTS_DIVISOR <=
maxAllowedPriceImpact * collateralTokenReserve;
}
/// @notice Compute Uniswap v2 pair address.
/// @param factory Address of the Uniswap v2 factory.
/// @param tokenA Address of token A.
/// @param tokenB Address of token B.
/// @return Address of token pair.
function computePairAddress(
address factory,
address tokenA,
address tokenB
) internal pure returns (address) {
(address token0, address token1) = tokenA < tokenB
? (tokenA, tokenB)
: (tokenB, tokenA);
return
address(
uint160(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
factory,
keccak256(abi.encodePacked(token0, token1)),
hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f"
)
)
)
)
);
}
}
|
Compute Uniswap v2 pair address. factory Address of the Uniswap v2 factory. tokenA Address of token A. tokenB Address of token B. return Address of token pair.
|
function computePairAddress(
address factory,
address tokenA,
address tokenB
) internal pure returns (address) {
(address token0, address token1) = tokenA < tokenB
? (tokenA, tokenB)
: (tokenB, tokenA);
return
address(
uint160(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
factory,
keccak256(abi.encodePacked(token0, token1)),
hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f"
)
)
)
)
);
}
| 919,701
|
./partial_match/4/0x19f562f9Be9B684BDc8999E485f9f4f97da2A1C6/sources/contracts/AddressRegistry.sol
|
Update Marketplace contract address _marketplace Marketplace contract address/
|
function updateMarketplace(address _marketplace) external onlyOwner {
marketplace = _marketplace;
emit UpdateMarktplace(_marketplace);
}
| 8,747,599
|
./partial_match/1/0xAbb62cEEBB0BFBe6D1e1A3F7e43ea8e66B022d49/sources/VestingExecutor.sol
|
Sets up a token vesting schedule for the provided vestor Available only when vesting is active and only the owner can execute this function. If not enough tokens are available to vest, the transaction will be reverted. vestor The address of the wallet to receive vesting tokens amount The amount of tokens to be vested for the participant/Ensure vesting start time is valid
|
function standardVesting(
address vestor,
uint256 amount,
VestingParams memory _vestingParams
) public whenStandardVestingActive onlyOwner {
require(
_vestingParams.startTime >= block.timestamp - 60 minutes,
"Invalid start time set"
);
uint256 vestingAmount = amount;
_vest(vestor, vestingAmount, _vestingParams);
emit vestingTransactionComplete(msg.sender, vestingAmount);
}
| 3,629,240
|
pragma solidity ^0.4.18;
import "./ICO_B2E.sol";
contract Proxy_Buyer_Payment_Channel {
struct Channel {
bool open;
uint timestamp_opened;
uint valueMax;
uint value;
}
mapping(bytes32 => Channel) channels;
mapping(address => bytes32) channel_hashs;
address public owner;
ICO_B2E ico;
// Functions with this modifier can only be executed by the owner
modifier onlyOwner() {
if (msg.sender != owner) {
revert();
}
_;
}
function Proxy_Buyer_Payment_Channel(address _ico_B2E) public {
owner = msg.sender;
ico = ICO_B2E(_ico_B2E);
}
function Invest() public payable {
require(msg.value > 0);
ico.DelegateTokenTo.value(msg.value)(msg.sender);
}
// Creates a payment channel with the user
function OpenChannel() public payable {
require(msg.value > 0); // You can't open a channel without funding it.
require(channel_hashs[msg.sender] == 0); // If there is already an opened channel with this user, throw.
Channel memory channel = Channel(true, block.timestamp, msg.value, 0);
// Hash the channel details using keccak256 (= sha3())
bytes32 channel_hash = keccak256(msg.sender, ico, block.timestamp); // This hash needs to be unique to avoid replay attacks by copying messages
channel_hashs[msg.sender] = channel_hash;
channels[channel_hash] = channel;
}
function SendMessage(bytes32 _h, uint8 _v, bytes32 _r, bytes32 _s, uint _value) public {
bytes32 channel_hash = channel_hashs[msg.sender];
Channel memory channel = channels[channel_hash];
// Check the message is legitimate
require(VerifyMessage(msg.sender, _h, _v, _r, _s, _value) == true);
require(_value > channel.value);
// If so, update the user's commitments
channel.value = _value;
channels[channel_hash] = channel;
}
function VerifyMessage(address _user, bytes32 _h, uint8 _v, bytes32 _r, bytes32 _s, uint _value) public constant returns (bool) {
bytes32 channel_hash = channel_hashs[_user];
Channel memory channel = channels[channel_hash];
// Check the channel exists, is open and has and ether in
if (channel.open == false) {return false;}
if (_value <= 0) {return false;}
if (_value > channel.valueMax) {return false;}
address signer = ecrecover(_h, _v, _r, _s);
// Check the signer of the message is the channel's user
if (signer != _user) {return false;}
bytes32 computed_hash = keccak256(channel_hash, _value);
// Check the value hashed in the message is the one given in argument
if (computed_hash != _h) {return false;}
return true;
}
function CloseChannel() public {
bytes32 channel_hash = channel_hashs[msg.sender];
Channel memory channel = channels[channel_hash];
require(channel.open == true);
channel.open = false;
uint payToICO = channel.value;
uint refundUser = channel.valueMax - channel.value;
channel_hashs[msg.sender] = bytes32(0);
if(ico.icoEnded() == true) {
if (!msg.sender.send(channel.valueMax)) {
revert();
}
}
else {
ico.DelegateTokenTo.value(payToICO)(msg.sender);
if (!msg.sender.send(refundUser)) {
revert();
}
}
delete channels[channel_hash];
}
// Getters for Channel infos
function GetChannelHash(address _user) public constant returns (bytes32 channel_hash) {
channel_hash = channel_hashs[_user];
}
function GetChannelOpen(bytes32 _channel_hash) public constant returns (bool open) {
open = channels[_channel_hash].open;
}
function GetChannelTimestampOpened(bytes32 _channel_hash) public constant returns (uint timestamp_opened) {
timestamp_opened = channels[_channel_hash].timestamp_opened;
}
function GetChannelValueMax(bytes32 _channel_hash) public constant returns (uint valueMax) {
valueMax = channels[_channel_hash].valueMax;
}
function GetChannelCurrentValue(bytes32 _channel_hash) public constant returns (uint value) {
value = channels[_channel_hash].value;
}
function destruct() public onlyOwner() {
selfdestruct(owner);
}
}
|
Check the message is legitimate If so, update the user's commitments
|
function SendMessage(bytes32 _h, uint8 _v, bytes32 _r, bytes32 _s, uint _value) public {
bytes32 channel_hash = channel_hashs[msg.sender];
Channel memory channel = channels[channel_hash];
require(VerifyMessage(msg.sender, _h, _v, _r, _s, _value) == true);
require(_value > channel.value);
channel.value = _value;
channels[channel_hash] = channel;
}
| 12,994,947
|
./full_match/5/0x0fEa7ce4cC0121a96B41d18cC8bed8f3F7744611/sources/contracts/smart-wallet/non-upgradeable/Account.sol
|
Returns whether a given address is authorized to sign requests.
|
function _isAuthorizedSigner(address _signer) internal view virtual override returns (bool) {
return isValidSigner(_signer);
}
| 11,591,880
|
pragma solidity ^0.4.18;
import './Genbby-Token.sol';
/**
* @title Genbby Cash
* @dev A contract that handle the buying of Genbby cash in the platform
*/
contract GenbbyCash is Pausable {
GenbbyToken public token;
event Cash(address who, uint256 bet);
/**
* @dev The `owner` can set the token that uses these contract (Genbby tokens)
*/
function setToken(address tokenAddress) onlyOwner public {
token = GenbbyToken(tokenAddress);
}
/**
* @dev Function that handle the decrement of Genbby Tokens equivalent for the buying of 'bet' Genbby Cash
* @param who The buyer
* @param bet The amount of the bet
*/
function cash(address who, uint256 bet) onlyOwner whenNotPaused public {
token.buy(who, bet);
Cash(who, bet);
}
/*
* @dev Do not allow direct deposits
*/
function () public payable {
revert();
}
}
|
Function that handle the decrement of Genbby Tokens equivalent for the buying of 'bet' Genbby Cash who The buyer bet The amount of the bet/
|
function cash(address who, uint256 bet) onlyOwner whenNotPaused public {
token.buy(who, bet);
Cash(who, bet);
}
| 12,887,081
|
pragma solidity 0.4.19;
// File: contracts\ERC20.sol
/**
* Starndard ERC20 interface: https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 {
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);
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);
/**
* @dev Fix for the ERC20 short address attack.
* Remove short address attack checks from tokens(https://github.com/OpenZeppelin/openzeppelin-solidity/issues/261)
*/
modifier onlyPayloadSize(uint256 size) {
require(msg.data.length >= size + 4);
_;
}
}
// File: contracts\MultiOwnable.sol
/**
* FEATURE 2): MultiOwnable implementation
* Transactions approved by _multiRequires of _multiOwners' addresses will be executed.
* All functions needing unit-tests cannot be INTERNAL
*/
contract MultiOwnable {
address[8] m_owners;
uint m_numOwners;
uint m_multiRequires;
mapping (bytes32 => uint) internal m_pendings;
event AcceptConfirm(bytes32 operation, address indexed who, uint confirmTotal);
// constructor is given number of sigs required to do protected "multiOwner" transactions
function MultiOwnable (address[] _multiOwners, uint _multiRequires) public {
require(0 < _multiRequires && _multiRequires <= _multiOwners.length);
m_numOwners = _multiOwners.length;
require(m_numOwners <= 8); // Bigger then 8 co-owners, not support !
for (uint i = 0; i < _multiOwners.length; ++i) {
m_owners[i] = _multiOwners[i];
require(m_owners[i] != address(0));
}
m_multiRequires = _multiRequires;
}
// Any one of the owners, will approve the action
modifier anyOwner {
if (isOwner(msg.sender)) {
_;
}
}
// Requiring num > m_multiRequires owners, to approve the action
modifier mostOwner(bytes32 operation) {
if (checkAndConfirm(msg.sender, operation)) {
_;
}
}
function isOwner(address currentUser) public view returns (bool) {
for (uint i = 0; i < m_numOwners; ++i) {
if (m_owners[i] == currentUser) {
return true;
}
}
return false;
}
function checkAndConfirm(address currentUser, bytes32 operation) public returns (bool) {
uint ownerIndex = m_numOwners;
uint i;
for (i = 0; i < m_numOwners; ++i) {
if (m_owners[i] == currentUser) {
ownerIndex = i;
}
}
if (ownerIndex == m_numOwners) {
return false; // Not Owner
}
uint newBitFinger = (m_pendings[operation] | (2 ** ownerIndex));
uint confirmTotal = 0;
for (i = 0; i < m_numOwners; ++i) {
if ((newBitFinger & (2 ** i)) > 0) {
confirmTotal ++;
}
}
AcceptConfirm(operation, currentUser, confirmTotal);
if (confirmTotal >= m_multiRequires) {
delete m_pendings[operation];
return true;
}
else {
m_pendings[operation] = newBitFinger;
return false;
}
}
}
// File: contracts\Pausable.sol
/**
* FEATURE 3): Pausable implementation
*/
contract Pausable is MultiOwnable {
event Pause();
event Unpause();
bool paused = false;
// Modifier to make a function callable only when the contract is not paused.
modifier whenNotPaused() {
require(!paused);
_;
}
// Modifier to make a function callable only when the contract is paused.
modifier whenPaused() {
require(paused);
_;
}
// called by the owner to pause, triggers stopped state
function pause() mostOwner(keccak256(msg.data)) whenNotPaused public {
paused = true;
Pause();
}
// called by the owner to unpause, returns to normal state
function unpause() mostOwner(keccak256(msg.data)) whenPaused public {
paused = false;
Unpause();
}
function isPause() view public returns(bool) {
return paused;
}
}
// File: contracts\SafeMath.sol
/**
* Standard SafeMath Library: zeppelin-solidity/contracts/math/SafeMath.sol
*/
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;
}
}
// File: contracts\Convertible.sol
/**
* Exchange all my ParcelX token to mainchain GPX
*/
contract Convertible {
function convertMainchainGPX(string destinationAccount, string extra) external returns (bool);
// ParcelX deamon program is monitoring this event.
// Once it triggered, ParcelX will transfer corresponding GPX to destination account
event Converted(address indexed who, string destinationAccount, uint256 amount, string extra);
}
// File: contracts\ParcelXGPX.sol
/**
* The main body of final smart contract
*/
contract ParcelXGPX is ERC20, MultiOwnable, Pausable, Convertible {
using SafeMath for uint256;
string public constant name = "ParcelX";
string public constant symbol = "GPX";
uint8 public constant decimals = 18;
// Main - 50000 ETH * int(1 / 0.000268) = 186550000
uint256 public constant TOTAL_SUPPLY = uint256(186550000) * (uint256(10) ** decimals);
address internal tokenPool = address(0); // Use a token pool holding all GPX. Avoid using sender address.
mapping(address => uint256) internal balances;
mapping (address => mapping (address => uint256)) internal allowed;
function ParcelXGPX(address[] _multiOwners, uint _multiRequires)
MultiOwnable(_multiOwners, _multiRequires) public {
require(tokenPool == address(0));
tokenPool = this;
require(tokenPool != address(0));
balances[tokenPool] = TOTAL_SUPPLY;
}
/**
* FEATURE 1): ERC20 implementation
*/
function totalSupply() public view returns (uint256) {
return TOTAL_SUPPLY;
}
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) 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;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) 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;
}
function approve(address _spender, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
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;
}
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;
}
/**
* FEATURE 4): Buyable implements
* 0.000268 eth per GPX, so the rate is 1.0 / 0.000268 = 3731.3432835820895
*/
uint256 internal buyRate = uint256(3731);
event Deposit(address indexed who, uint256 value);
event Withdraw(address indexed who, uint256 value, address indexed lastApprover, string extra);
function getBuyRate() external view returns (uint256) {
return buyRate;
}
function setBuyRate(uint256 newBuyRate) mostOwner(keccak256(msg.data)) external {
buyRate = newBuyRate;
}
/**
* FEATURE 4): Buyable
* minimum of 0.001 ether for purchase in the public, pre-ico, and private sale
*/
function buy() payable whenNotPaused public returns (uint256) {
Deposit(msg.sender, msg.value);
require(msg.value >= 0.001 ether);
// Token compute & transfer
uint256 tokens = msg.value.mul(buyRate);
require(balances[tokenPool] >= tokens);
balances[tokenPool] = balances[tokenPool].sub(tokens);
balances[msg.sender] = balances[msg.sender].add(tokens);
Transfer(tokenPool, msg.sender, tokens);
return tokens;
}
// gets called when no other function matches
function () payable public {
if (msg.value > 0) {
buy();
}
}
/**
* FEATURE 6): Budget control
* Malloc GPX for airdrops, marketing-events, bonus, etc
*/
function mallocBudget(address _admin, uint256 _value) mostOwner(keccak256(msg.data)) external returns (bool) {
require(_admin != address(0));
require(_value <= balances[tokenPool]);
balances[tokenPool] = balances[tokenPool].sub(_value);
balances[_admin] = balances[_admin].add(_value);
Transfer(tokenPool, _admin, _value);
return true;
}
function execute(address _to, uint256 _value, string _extra) mostOwner(keccak256(msg.data)) external returns (bool){
require(_to != address(0));
_to.transfer(_value); // Prevent using call() or send()
Withdraw(_to, _value, msg.sender, _extra);
return true;
}
/**
* FEATURE 5): 'Convertible' implements
* Below actions would be performed after token being converted into mainchain:
* - KYC / AML
* - Unsold tokens are discarded.
* - Tokens sold with bonus will be locked for a period (see Whitepaper).
* - Token distribution for team will be locked for a period (see Whitepaper).
*/
function convertMainchainGPX(string destinationAccount, string extra) external returns (bool) {
require(bytes(destinationAccount).length > 10 && bytes(destinationAccount).length < 1024);
require(balances[msg.sender] > 0);
uint256 amount = balances[msg.sender];
balances[msg.sender] = 0;
balances[tokenPool] = balances[tokenPool].add(amount); // return GPX to tokenPool - the init account
Converted(msg.sender, destinationAccount, amount, extra);
return true;
}
}
|
FEATURE 5): &39;Convertible&39; implements Below actions would be performed after token being converted into mainchain: - KYC / AML - Unsold tokens are discarded. - Tokens sold with bonus will be locked for a period (see Whitepaper). - Token distribution for team will be locked for a period (see Whitepaper)./
|
function convertMainchainGPX(string destinationAccount, string extra) external returns (bool) {
require(bytes(destinationAccount).length > 10 && bytes(destinationAccount).length < 1024);
require(balances[msg.sender] > 0);
uint256 amount = balances[msg.sender];
balances[msg.sender] = 0;
Converted(msg.sender, destinationAccount, amount, extra);
return true;
}
| 2,261,376
|
./full_match/137/0xb2bc344d91ac43aEdDCB5d6bA5E7e208ce29f2DA/sources/contracts/helper.sol
|
Change decimal places to `UNIFORM_DECIMALS`.
|
function toUniform(
uint256 amount,
address token
) internal view returns (uint256) {
return
changeDecimals(
amount,
IERC20Extended(token).decimals(),
UNIFORM_DECIMALS
);
}
| 4,665,588
|
./full_match/5/0xC8F794b9470776da248120528C06ACc6a6bEd5e1/sources/nat_contracts/birthroom.sol
|
Sets `tokenURI` as the tokenURI of `tokenId`./
|
function _setURI(uint256 tokenId, string memory tokenURI) internal virtual {
_tokenURIs[tokenId] = tokenURI;
emit URI(uri(tokenId), tokenId);
}
| 1,923,107
|
pragma solidity ^0.5.5;
//DCC VERSION 5
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
/// @author Dieter Shirley <dete@axiomzen.co> (https://github.com/dete)
interface ERC721 {
// Required methods
function totalSupply() external view returns (uint256 total);
function balanceOf(address _owner) external view returns (uint256 balance);
function ownerOf(uint256 _tokenId) external view returns (address owner);
function exists(uint256 _tokenId) external view returns (bool _exists);
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
// Events
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Metadata is ERC721 {
function name() external view returns (string memory _name);
function symbol() external view returns (string memory _symbol);
function tokenURI(uint256 _tokenId) public view returns (string memory);
}
/**
* These are required for the DCC contract to interact with the WLC contract
*/
interface WLCCompatible {
function getWLCReward(uint256 _boughtWLCAmount, address _owner) external returns (uint256 _remaining);
function setWLCParams(address _address, uint256 _reward) external;
function resetWLCParams() external;
function getForWLC(address _owner) external;
function getWLCRewardAmount() external view returns (uint256 _amount);
function getWLCAddress() external view returns (address _address);
}
contract DreamCarToken1 is ERC721, ERC721Metadata, WLCCompatible {
string internal constant tokenName = 'DreamCarCoin1';
string internal constant tokenSymbol = 'DCC1';
uint8 public constant decimals = 0;
//ERC721 VARIABLES
//the total count of wishes
uint256 internal totalTokenSupply;
//this address is the CEO
address payable public CEO;
bytes4 constant InterfaceSignature_ERC165 =
bytes4(keccak256('supportsInterface(bytes4)'));
bytes4 constant InterfaceSignature_ERC721 =
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('totalTokenSupply()')) ^
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('transfer(address,uint256)')) ^
bytes4(keccak256('transferFrom(address,address,uint256)')) ^
bytes4(keccak256('tokensOfOwner(address)')) ^
bytes4(keccak256('tokenMetadata(uint256,string)'));
// Mapping from owner to number of owned tokens
//mapping (address => uint256) internal tokensBalanceOf;
// Mapping from token ID to owner
mapping (uint256 => address) internal tokenOwner;
// Optional mapping for token URIs
mapping(uint256 => string) internal tokenURIs;
//TOKEN SPECIFIC VARIABLES
mapping (address => uint256) internal tokenBallanceOf;
//Token price in WEI
uint256 public tokenPrice;
//A list of price admins; they can change price, in addition to the CEO
address[] public priceAdmins;
//Next id that will be assigned to token
uint256 internal nextTokenId = 1;
//The winning token id
uint256 public winningTokenId = 0;
//The winner's address, it will be empty, until the reward is claimed
address public winnerAddress;
//WLC CONTRACT INTERACTION VARIABLES
//WLC tokens in a single purchase to earn a DCC token
uint256 internal WLCRewardAmount;
//WLC deployed contract address
address internal WLCAdress;
//ERC721 FUNCTIONS IMPLEMENTATIONS
function supportsInterface(bytes4 _interfaceID) external view returns (bool) {
return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
}
/**
* Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256 total) {
return totalTokenSupply;
}
/**
* 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 _balance) {
return tokenBallanceOf[_owner];
}
/**
* Gets the owner of the specified token ID
* @param _tokenId uint256 ID of the token to query the owner of
* @return owner address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 _tokenId) public view returns (address _owner) {
return tokenOwner[_tokenId];
}
/**
* Returns whether the specified token exists
* @param _tokenId uint256 ID of the token to query the existence of
* @return whether the token exists
*/
function exists(uint256 _tokenId) public view returns (bool) {
address owner = tokenOwner[_tokenId];
return owner != address(0);
}
/**
* Not necessary in the contract
*/
function transfer(address _to, uint256 _tokenId) external { }
/**
* Not necessary in the contract
*/
function approve(address _to, uint256 _tokenId) external { }
/**
* Not necessary in the contract - reverts
*/
function transferFrom(address _from, address _to, uint256 _tokenId) external { }
/**
* Internal function to set the token URI for a given token
* Reverts if the token ID does not exist
* @param _tokenId uint256 ID of the token to set its URI
* @param _uri string URI to assign
*/
function _setTokenURI(uint256 _tokenId, string storage _uri) internal {
require(exists(_tokenId));
tokenURIs[_tokenId] = _uri;
}
//ERC721Metadata FUNCTIONS IMPLEMENTATIONS
/**
* Gets the token name
* @return string representing the token name
*/
function name() external view returns (string memory _name) {
return tokenName;
}
/**
* Gets the token symbol
* @return string representing the token symbol
*/
function symbol() external view returns (string memory _symbol) {
return tokenSymbol;
}
/**
* Returns an URI for a given token ID
* Throws if the token ID does not exist. May return an empty string.
* @param _tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 _tokenId) public view returns (string memory) {
require(exists(_tokenId));
return tokenURIs[_tokenId];
}
//TOKEN SPECIFIC FUNCTIONS
event Buy(address indexed from, uint256 amount, uint256 fromTokenId, uint256 toTokenId);
event RewardIsClaimed(address indexed from, uint256 tokenId);
event WinnerIsChosen(address indexed from, uint256 tokenId);
/**
* Ensures that the caller of the function is the CEO of contract
*/
modifier onlyCEO {
require(msg.sender == CEO, 'You need to be the CEO to do that!');
_;
}
/**
* Constructor of the contract
* @param _ceo address the CEO (owner) of the contract
*/
constructor (address payable _ceo) public {
CEO = _ceo;
totalTokenSupply = 40000;
tokenPrice = 6384880602732729; // (if eth = 156.62USD, 1 USD for token)
}
/**
* Gets the last existing token ids
* @return uint256 the id of the token
*/
function lastTokenId() public view returns (uint256 tokenId) {
return nextTokenId - 1;
}
/**
* Sets a new price for the tokensExchangedBy
* @param _newPrice uint256 the new price in WEI
*/
function setTokenPriceInWEI(uint256 _newPrice) public {
bool transactionAllowed = false;
if (msg.sender == CEO) {
transactionAllowed = true;
} else {
for (uint256 i = 0; i < priceAdmins.length; i++) {
if (msg.sender == priceAdmins[i]) {
transactionAllowed = true;
break;
}
}
}
require((transactionAllowed == true), 'You cannot do that!');
tokenPrice = _newPrice;
}
/**
* Add a new price admin address to the list
* @param _newPriceAdmin address the address of the new price admin
*/
function addPriceAdmin(address _newPriceAdmin) onlyCEO public {
priceAdmins.push(_newPriceAdmin);
}
/**
* Remove existing price admin address from the list
* @param _existingPriceAdmin address the address of the existing price admin
*/
function removePriceAdmin(address _existingPriceAdmin) onlyCEO public {
for (uint256 i = 0; i < priceAdmins.length; i++) {
if (_existingPriceAdmin == priceAdmins[i]) {
delete priceAdmins[i];
break;
}
}
}
/**
* Adds the specified number of tokens to the specified address
* Internal method, used when creating new tokens
* @param _to address The address, which is going to own the tokens
* @param _amount uint256 The number of tokens
*/
function _addTokensToAddress(address _to, uint256 _amount) internal {
for (uint256 i = 0; i < _amount; i++) {
tokenOwner[nextTokenId + i] = _to;
}
tokenBallanceOf[_to] += _amount;
nextTokenId += _amount;
}
/**
* Checks if the specified token is owned by the transaction sender
*/
function ensureAddressIsTokenOwner(address _owner, uint256 _tokenId) internal view {
require(balanceOf(_owner) >= 1, 'You do not own any tokens!');
require(tokenOwner[_tokenId] == _owner, 'You do not own this token!');
}
/**
* Generates a random number between 1 and totalTokenSupply variable
* This is used to choose the winning token id
*/
function getRandomNumber() internal view returns (uint16) {
return uint16(
uint256(
keccak256(
abi.encodePacked(block.timestamp, block.difficulty, block.number)
)
)%totalTokenSupply
) + 1;
}
/**
* Chooses a winning token id, if all tokens are purchased
*/
function chooseWinner() internal {
if ((nextTokenId - 1) == totalTokenSupply) {
winningTokenId = getRandomNumber();
emit WinnerIsChosen(tokenOwner[winningTokenId], winningTokenId);
}
}
/**
* Scales the amount of tokens in a purchase, to ensure it will be less or equal to the amount of unsold tokens
* If there are no tokens left, it will return 0
* @param _amount uint256 the amout of tokens in the purchase attempt
* @return _exactAmount uint256
*/
function scalePurchaseTokenAmountToMatchRemainingTokens(uint256 _amount) internal view returns (uint256 _exactAmount) {
if (nextTokenId + _amount - 1 > totalTokenSupply) {
_amount = totalTokenSupply - nextTokenId + 1;
}
return _amount;
}
/**
* Buy new tokens with ETH
* Calculates the nubmer of tokens for the given ETH amount
* Creates the new tokens when they are purchased
* Returns the excessive ETH (if any) to the transaction sender
*/
function buy() payable public {
require(msg.value >= tokenPrice, "You did't send enough ETH");
uint256 amount = scalePurchaseTokenAmountToMatchRemainingTokens(msg.value / tokenPrice);
require(amount > 0, "Not enough tokens are available for purchase!");
_addTokensToAddress(msg.sender, amount);
emit Buy(msg.sender, amount, nextTokenId - amount, nextTokenId - 1);
//transfer ETH to CEO
CEO.transfer((amount * tokenPrice));
//returns excessive ETH
msg.sender.transfer(msg.value - (amount * tokenPrice));
chooseWinner();
}
/**
* Allows user to destroy a specified token
* This would allow a user to claim his prize for the destroyed token
* @param _tokenId uint256 ID of the token
*/
function claimReward(uint256 _tokenId) public {
require(winningTokenId > 0, "The is not winner yet!");
require(_tokenId == winningTokenId, "This token is not the winner!");
ensureAddressIsTokenOwner(msg.sender, _tokenId);
winnerAddress = msg.sender;
emit RewardIsClaimed(msg.sender, _tokenId);
}
//WLC INTERACTION FUNCTIONS
/**
* Allows the CEO to set the address and the reward values for a connected WishListToken
* @param _address address the address of the deployed contract
* @param _reward uint256 how many tokens need to be bought in a single transaction to the one DCC token
*/
function setWLCParams(address _address, uint256 _reward) public onlyCEO {
WLCAdress = _address;
WLCRewardAmount = _reward;
}
/**
* Allows the CEO to revmove a connected WishListToken
* This revokes the reward and exchange functions
*/
function resetWLCParams() public onlyCEO {
WLCAdress = address(0);
WLCRewardAmount = 0;
}
/**
* How many WLC tokens need to be bought in a single transaction to the one DCC token
* @return _amount uint256
*/
function getWLCRewardAmount() public view returns (uint256 _amount) {
return WLCRewardAmount;
}
/**
* The address of the deployed WLC contract
* @return _address address
*/
function getWLCAddress() public view returns (address _address) {
return WLCAdress;
}
/**
* Allows the buyer of at least the number of WLC tokens, specified in WLCRewardAmount
* to receive a DCC as a bonus.
* This can only be called by the deployed WLC contract, by the address specified in WLCAdress
* @param _boughtWLCAmount uint256 the number of bought WLC tokens
* @param _owner address the address of the buyer
*/
function getWLCReward(uint256 _boughtWLCAmount, address _owner) public returns (uint256 _remaining) {
if (WLCAdress != address(0) && WLCRewardAmount > 0 && _boughtWLCAmount >= WLCRewardAmount) {
require(WLCAdress == msg.sender, "You cannot invoke this function directly!");
uint256 DCCAmount = scalePurchaseTokenAmountToMatchRemainingTokens(_boughtWLCAmount / WLCRewardAmount);
if (DCCAmount > 0) {
_addTokensToAddress(_owner, DCCAmount);
emit Buy(_owner, DCCAmount, nextTokenId - DCCAmount, nextTokenId - 1);
chooseWinner();
return _boughtWLCAmount - (DCCAmount * WLCRewardAmount);
}
}
return _boughtWLCAmount;
}
/**
* Allows an onwer of WLC token to excange it for DCC token
* This can only be called by the deployed WLC contract, by the address specified in WLCAdress
* @param _owner address the address of the exchanger
*/
function getForWLC(address _owner) public {
require(WLCAdress == msg.sender, "You cannot invoke this function directly!");
require(nextTokenId <= totalTokenSupply, "Not enough tokens are available for purchase!");
_addTokensToAddress(_owner, 1);
emit Buy(_owner, 1, nextTokenId - 1, nextTokenId - 1);
chooseWinner();
}
}
|
ERC721Metadata FUNCTIONS IMPLEMENTATIONS Gets the token name return string representing the token name/
|
function name() external view returns (string memory _name) {
return tokenName;
}
| 6,380,466
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.